/* global React, Icon, Avatar */
const { useState, useMemo } = React;

// ── Wiki nav sections ─────────────────────────────────────
const WIKI_SECTIONS = [
  { id: "knowledge", label: "Knowledge base", icon: "Wiki" },
  { id: "decisions", label: "Decision log", icon: "Decision" },
  { id: "experiments", label: "Experiments", icon: "Idea" },
];

const KNOWLEDGE_CATS = [
  { id: "tech", label: "Tech", icon: "Building" },
  { id: "design", label: "Design", icon: "Eye" },
  { id: "waysOfWorking", label: "Ways of working", icon: "Users" },
];

// ── Shared: knowledge article row ────────────────────────
function ArticleRow({
  item,
  isNew,
  authUser,
  authToken,
  onRefresh,
  isFocused,
}) {
  const [toggling, setToggling] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const isAuthor = authUser && item.author_id && authUser.id === item.author_id;
  const isDraft = item.status === "draft";
  const handleToggleStatus = async (e) => {
    e.stopPropagation();
    if (toggling) return;
    setToggling(true);
    const apiBase = window.PULSE_CONFIG?.apiBase || "http://localhost:8000";
    await fetch(`${apiBase}/wiki/articles/${item.id}`, {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${authToken}`,
      },
      body: JSON.stringify({ status: isDraft ? "live" : "draft" }),
    });
    setToggling(false);
    if (onRefresh) onRefresh();
  };
  const handleDelete = async (e) => {
    e.stopPropagation();
    if (deleting) return;
    if (!confirm("Delete this article? This cannot be undone.")) return;
    setDeleting(true);
    const apiBase = window.PULSE_CONFIG?.apiBase || "http://localhost:8000";
    const r = await fetch(`${apiBase}/wiki/articles/${item.id}`, {
      method: "DELETE",
      headers: { Authorization: `Bearer ${authToken}` },
    });
    setDeleting(false);
    if (r.ok && onRefresh) onRefresh();
  };

  return (
    <div
      data-wiki-id={item.id}
      className={`wiki-item ${isNew ? "fan-new" : ""} ${isFocused ? "wiki-focus" : ""}`}
    >
      <div className="wiki-body">
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "flex-start",
            gap: 12,
          }}
        >
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <div className="wiki-title">{item.title}</div>
            {isNew && (
              <span
                style={{
                  fontSize: 10.5,
                  color: "var(--accent)",
                  fontWeight: 600,
                  padding: "2px 7px",
                  background: "var(--accent-soft)",
                  borderRadius: 4,
                }}
              >
                NEW
              </span>
            )}
          </div>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 8,
              flexShrink: 0,
            }}
          >
            <span className={`wiki-status ${item.status}`}>{item.status}</span>
            {isAuthor && (
              <button
                className="btn"
                onClick={handleToggleStatus}
                disabled={toggling}
                style={{
                  fontSize: 11.5,
                  padding: "2px 9px",
                  color: isDraft ? "var(--accent)" : "var(--ink-3)",
                }}
              >
                {toggling ? "…" : isDraft ? "Publish" : "Set to draft"}
              </button>
            )}
            {isAuthor && (
              <button
                className="btn"
                onClick={handleDelete}
                disabled={deleting}
                style={{
                  fontSize: 11.5,
                  padding: "2px 9px",
                  color: "var(--err, #ef4444)",
                }}
              >
                {deleting ? "…" : "Delete"}
              </button>
            )}
          </div>
        </div>
        <div className="wiki-desc">{item.desc}</div>
        <div className="wiki-foot">
          <Avatar
            name={item.author}
            size="sm"
            you={authUser && item.author === authUser.name}
          />
          <span>{item.author}</span>
          <span>·</span>
          <span>{item.date}</span>
          <div className="tags">
            {(item.tags || []).map((t) => (
              <span className="tag ghost" key={t}>
                {t}
              </span>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Decision row ─────────────────────────────────────────
function DecisionRow({ d, authUser, authToken, onRefresh, isFocused }) {
  const [open, setOpen] = useState(!!isFocused);
  const [confirmingDecide, setConfirmingDecide] = useState(false);
  const [decideComment, setDecideComment] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [deleting, setDeleting] = useState(false);
  React.useEffect(() => {
    if (isFocused) setOpen(true);
  }, [isFocused]);
  const statusMeta = {
    decided: { cls: "outcome", label: "Decided" },
    open: { cls: "decision", label: "Open · needs decision" },
    superseded: { cls: "ghost", label: "Superseded" },
  };
  const sm = statusMeta[d.status] || statusMeta.open;
  const isAuthor = authUser && d.author_id === authUser.id;

  const canDecide = d.status === "open";
  const decideBlocked = false;

  const handleDecideClick = (e) => {
    e.stopPropagation();
    if (!canDecide || submitting) return;
    setConfirmingDecide(true);
    setOpen(true);
  };

  const handleDelete = async (e) => {
    e.stopPropagation();
    if (deleting) return;
    if (!confirm("Delete this decision? This cannot be undone.")) return;
    setDeleting(true);
    const apiBase = window.PULSE_CONFIG?.apiBase || "http://localhost:8000";
    const r = await fetch(`${apiBase}/wiki/decisions/${d.id}`, {
      method: "DELETE",
      headers: { Authorization: `Bearer ${authToken}` },
    });
    setDeleting(false);
    if (r.ok && onRefresh) onRefresh();
  };

  const handleConfirmDecide = async (e) => {
    e.stopPropagation();
    setSubmitting(true);
    const apiBase = window.PULSE_CONFIG?.apiBase || "http://localhost:8000";
    await fetch(`${apiBase}/wiki/decisions/${d.id}`, {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${authToken}`,
      },
      body: JSON.stringify({
        status: "decided",
        decided_comment: decideComment.trim() || null,
      }),
    });
    setSubmitting(false);
    setConfirmingDecide(false);
    setDecideComment("");
    if (onRefresh) onRefresh();
  };

  const handleCancelDecide = (e) => {
    e.stopPropagation();
    setConfirmingDecide(false);
    setDecideComment("");
  };

  return (
    <div
      data-wiki-id={d.id}
      className={`decision-row ${isFocused ? "wiki-focus" : ""}`}
      onClick={() => !confirmingDecide && setOpen((o) => !o)}
    >
      <div className="decision-row-head">
        <Icon.Decision
          style={{
            width: 13,
            height: 13,
            color:
              d.status === "open"
                ? "var(--warn)"
                : d.status === "superseded"
                  ? "var(--ink-4)"
                  : "var(--ok)",
            flexShrink: 0,
          }}
        />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 10,
              flexWrap: "wrap",
            }}
          >
            <span className="decision-title">{d.title}</span>
            <span className={`tag ${sm.cls}`} style={{ fontSize: 10.5 }}>
              {sm.label}
            </span>
          </div>
          <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 3 }}>
            {d.decider ? (
              <>
                <b style={{ color: "var(--ink-2)", fontWeight: 500 }}>
                  {d.decider}
                </b>{" "}
                ·{" "}
              </>
            ) : (
              <span style={{ color: "var(--warn)", fontWeight: 500 }}>
                No decider yet ·{" "}
              </span>
            )}
            {d.date}
          </div>
        </div>
        {d.status === "open" && !confirmingDecide && (
          <button
            className="btn"
            style={{
              fontSize: 11.5,
              padding: "3px 10px",
              flexShrink: 0,
              opacity: decideBlocked ? 0.4 : 1,
              cursor: decideBlocked ? "not-allowed" : "pointer",
            }}
            title={
              decideBlocked
                ? `Only ${d.decider} can mark this as decided`
                : "Mark as decided"
            }
            onClick={handleDecideClick}
            disabled={decideBlocked}
          >
            ✓ Decide
          </button>
        )}
        <Icon.Chevron
          style={{
            width: 14,
            height: 14,
            color: "var(--ink-3)",
            transform: open ? "rotate(180deg)" : "none",
            transition: "transform 180ms ease",
            flexShrink: 0,
          }}
        />
      </div>
      {open && (
        <div className="decision-body">
          <p
            style={{
              margin: "0 0 10px",
              fontSize: 13.5,
              color: "var(--ink-2)",
              lineHeight: 1.55,
            }}
          >
            {d.body}
          </p>
          {d.decided_comment && (
            <div
              style={{
                background: "var(--ok-soft, rgba(34,197,94,0.08))",
                border: "1px solid rgba(34,197,94,0.2)",
                borderRadius: 7,
                padding: "8px 12px",
                marginBottom: 10,
                fontSize: 13,
                color: "var(--ink-2)",
                lineHeight: 1.5,
              }}
            >
              <span
                style={{
                  fontSize: 11,
                  fontWeight: 600,
                  color: "var(--ok)",
                  display: "block",
                  marginBottom: 3,
                }}
              >
                Decision note
              </span>
              {d.decided_comment}
            </div>
          )}
          {confirmingDecide && (
            <div
              style={{
                background: "var(--surface-2)",
                border: "1px solid var(--line)",
                borderRadius: 8,
                padding: 12,
                marginBottom: 10,
              }}
              onClick={(e) => e.stopPropagation()}
            >
              <div
                style={{
                  fontSize: 12,
                  fontWeight: 600,
                  marginBottom: 8,
                  color: "var(--ink-2)",
                }}
              >
                Add a decision note{" "}
                <span style={{ fontWeight: 400, color: "var(--ink-4)" }}>
                  (optional)
                </span>
              </div>
              <textarea
                autoFocus
                style={{
                  width: "100%",
                  minHeight: 72,
                  background: "var(--surface-1)",
                  border: "1px solid var(--line)",
                  borderRadius: 6,
                  padding: "8px 10px",
                  fontSize: 13,
                  color: "var(--ink-1)",
                  resize: "vertical",
                  boxSizing: "border-box",
                }}
                placeholder="e.g. Went with option B — lower risk given current timeline."
                value={decideComment}
                onChange={(e) => setDecideComment(e.target.value)}
              />
              <div
                style={{
                  display: "flex",
                  gap: 8,
                  marginTop: 8,
                  justifyContent: "flex-end",
                }}
              >
                <button className="btn" onClick={handleCancelDecide}>
                  Cancel
                </button>
                <button
                  className="btn accent"
                  onClick={handleConfirmDecide}
                  disabled={submitting}
                >
                  {submitting ? "Saving…" : "✓ Confirm decision"}
                </button>
              </div>
            </div>
          )}
          <div
            style={{
              display: "flex",
              gap: 16,
              fontSize: 12,
              color: "var(--ink-3)",
              flexWrap: "wrap",
              alignItems: "center",
            }}
          >
            {d.stakeholders && d.stakeholders.length > 0 && (
              <span>Stakeholders: {d.stakeholders.join(", ")}</span>
            )}
            <div
              style={{
                marginLeft: "auto",
                display: "flex",
                gap: 5,
                alignItems: "center",
              }}
            >
              {d.tags.map((t) => (
                <span className="tag ghost" key={t}>
                  {t}
                </span>
              ))}
              {isAuthor && (
                <button
                  className="btn"
                  onClick={handleDelete}
                  disabled={deleting}
                  style={{
                    fontSize: 11,
                    padding: "2px 8px",
                    color: "var(--err, #ef4444)",
                    marginLeft: 4,
                  }}
                >
                  {deleting ? "…" : "Delete"}
                </button>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ── Experiment row ────────────────────────────────────────
function ExperimentRow({ e, authUser, authToken, onRefresh, isFocused }) {
  const [open, setOpen] = useState(!!isFocused);
  const [wrappingUp, setWrappingUp] = useState(false);
  const [wrapResult, setWrapResult] = useState("success");
  const [wrapOutcome, setWrapOutcome] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [deleting, setDeleting] = useState(false);
  React.useEffect(() => {
    if (isFocused) setOpen(true);
  }, [isFocused]);

  const apiBase = window.PULSE_CONFIG?.apiBase || "http://localhost:8000";

  const statusMeta = {
    running: { cls: "decision", label: "Running" },
    complete: { cls: "outcome", label: "Complete" },
    abandoned: { cls: "ghost", label: "Abandoned" },
  };
  const resultMeta = {
    success: { cls: "outcome", label: "✓ Success" },
    mixed: { cls: "decision", label: "~ Mixed" },
    failed: { cls: "blocker", label: "✕ Failed" },
  };
  const sm = statusMeta[e.status] || statusMeta.running;
  const rm = e.result ? resultMeta[e.result] : null;

  const canWrap =
    authUser && (e.author_id === authUser.id || e.owner_id === authUser.id);
  const isAuthor = authUser && e.author_id === authUser.id;

  const handleDelete = async (evt) => {
    evt.stopPropagation();
    if (deleting) return;
    if (!confirm("Delete this experiment? This cannot be undone.")) return;
    setDeleting(true);
    const r = await fetch(`${apiBase}/wiki/experiments/${e.id}`, {
      method: "DELETE",
      headers: { Authorization: `Bearer ${authToken}` },
    });
    setDeleting(false);
    if (r.ok && onRefresh) onRefresh();
  };

  const handleWrapClick = (evt) => {
    evt.stopPropagation();
    setWrappingUp(true);
    setOpen(true);
  };

  const handleConfirmWrap = async (evt) => {
    evt.stopPropagation();
    setSubmitting(true);
    await fetch(`${apiBase}/wiki/experiments/${e.id}`, {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${authToken}`,
      },
      body: JSON.stringify({
        status: "complete",
        result: wrapResult,
        outcome: wrapOutcome.trim() || null,
      }),
    });
    setSubmitting(false);
    setWrappingUp(false);
    setWrapOutcome("");
    if (onRefresh) onRefresh();
  };

  return (
    <div
      data-wiki-id={e.id}
      className={`decision-row ${isFocused ? "wiki-focus" : ""}`}
      onClick={() => {
        if (!wrappingUp) setOpen((o) => !o);
      }}
    >
      <div className="decision-row-head">
        <Icon.Idea
          style={{
            width: 13,
            height: 13,
            color:
              e.status === "complete" && e.result === "success"
                ? "var(--ok)"
                : e.status === "complete" && e.result === "failed"
                  ? "var(--danger)"
                  : "var(--warn)",
            flexShrink: 0,
          }}
        />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 10,
              flexWrap: "wrap",
            }}
          >
            <span className="decision-title">{e.title}</span>
            <span className={`tag ${sm.cls}`} style={{ fontSize: 10.5 }}>
              {sm.label}
            </span>
            {rm && (
              <span className={`tag ${rm.cls}`} style={{ fontSize: 10.5 }}>
                {rm.label}
              </span>
            )}
          </div>
          <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 3 }}>
            {e.owner ? `Owner: ${e.owner}` : `Added by ${e.author}`} · {e.date}
          </div>
        </div>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 8,
            flexShrink: 0,
          }}
        >
          {canWrap && e.status === "running" && !wrappingUp && (
            <button
              className="btn"
              style={{
                fontSize: 11.5,
                padding: "3px 10px",
                color: "var(--accent)",
              }}
              onClick={handleWrapClick}
            >
              Wrap up
            </button>
          )}
          <Icon.Chevron
            style={{
              width: 14,
              height: 14,
              color: "var(--ink-3)",
              transform: open ? "rotate(180deg)" : "none",
              transition: "transform 180ms ease",
            }}
          />
        </div>
      </div>
      {open && (
        <div className="decision-body">
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: 14,
              marginBottom: 10,
            }}
          >
            <div>
              <div className="kicker" style={{ marginBottom: 6 }}>
                Hypothesis
              </div>
              <div
                style={{
                  fontSize: 13,
                  color: "var(--ink-2)",
                  lineHeight: 1.55,
                }}
              >
                {e.hypothesis}
              </div>
            </div>
            <div>
              <div className="kicker" style={{ marginBottom: 6 }}>
                Outcome
              </div>
              <div
                style={{
                  fontSize: 13,
                  color: e.outcome ? "var(--ink-2)" : "var(--ink-4)",
                  lineHeight: 1.55,
                  fontStyle: e.outcome ? "normal" : "italic",
                }}
              >
                {e.outcome ||
                  (e.status === "running"
                    ? "Experiment in progress…"
                    : "No outcome recorded.")}
              </div>
            </div>
          </div>
          {wrappingUp && (
            <div
              style={{
                background: "var(--surface-3, rgba(255,255,255,0.04))",
                border: "1px solid var(--line)",
                borderRadius: 8,
                padding: 12,
                marginBottom: 10,
              }}
              onClick={(ev) => ev.stopPropagation()}
            >
              <div className="kicker" style={{ marginBottom: 8 }}>
                Wrap up experiment
              </div>
              <div style={{ display: "flex", gap: 8, marginBottom: 10 }}>
                {[
                  ["success", "✓ Success", "outcome"],
                  ["mixed", "~ Mixed", "decision"],
                  ["failed", "✕ Failed", "blocker"],
                ].map(([val, lbl, cls]) => (
                  <button
                    key={val}
                    className={`tag ${cls}`}
                    style={{
                      cursor: "pointer",
                      fontWeight: wrapResult === val ? 700 : 400,
                      opacity: wrapResult === val ? 1 : 0.55,
                      border:
                        wrapResult === val
                          ? "2px solid currentColor"
                          : "1px solid transparent",
                      fontSize: 12,
                      padding: "4px 10px",
                    }}
                    onClick={() => setWrapResult(val)}
                  >
                    {lbl}
                  </button>
                ))}
              </div>
              <textarea
                style={{
                  width: "100%",
                  minHeight: 70,
                  background: "var(--surface-2)",
                  border: "1px solid var(--line)",
                  borderRadius: 8,
                  padding: 10,
                  fontSize: 13,
                  color: "var(--ink-1)",
                  resize: "vertical",
                  boxSizing: "border-box",
                  marginBottom: 10,
                }}
                placeholder="What did you learn? What would you do differently?"
                value={wrapOutcome}
                onChange={(ev) => setWrapOutcome(ev.target.value)}
              />
              <div style={{ display: "flex", gap: 8 }}>
                <button
                  className="btn accent"
                  onClick={handleConfirmWrap}
                  disabled={submitting}
                  style={{ fontSize: 12 }}
                >
                  {submitting ? "Saving…" : "✓ Confirm wrap-up"}
                </button>
                <button
                  className="btn"
                  onClick={(ev) => {
                    ev.stopPropagation();
                    setWrappingUp(false);
                  }}
                  style={{ fontSize: 12 }}
                >
                  Cancel
                </button>
              </div>
            </div>
          )}
          <div
            style={{
              display: "flex",
              gap: 5,
              flexWrap: "wrap",
              alignItems: "center",
            }}
          >
            {(e.tags || []).map((t) => (
              <span className="tag ghost" key={t}>
                {t}
              </span>
            ))}
            {isAuthor && (
              <button
                className="btn"
                onClick={handleDelete}
                disabled={deleting}
                style={{
                  fontSize: 11,
                  padding: "2px 8px",
                  color: "var(--err, #ef4444)",
                  marginLeft: "auto",
                }}
              >
                {deleting ? "…" : "Delete"}
              </button>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

// ── New wiki entry modal ──────────────────────────────────
function NewWikiModal({
  open,
  onClose,
  authToken,
  onSaved,
  initialType,
  scopeId,
}) {
  const [type, setType] = useState(initialType || "article");
  const [saving, setSaving] = useState(false);
  // article fields
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");
  const [category, setCategory] = useState("tech");
  const [status, setStatus] = useState("draft");
  // decision fields
  const [decBody, setDecBody] = useState("");
  const [decTitle, setDecTitle] = useState("");
  // decider autocomplete
  const [deciderQuery, setDeciderQuery] = useState("");
  const [deciderSelected, setDeciderSelected] = useState(null); // { id, name }
  const [members, setMembers] = useState([]);
  // experiment fields
  const [expTitle, setExpTitle] = useState("");
  const [hypothesis, setHypothesis] = useState("");
  // experiment owner autocomplete (reuses same members list as decider)
  const [ownerQuery, setOwnerQuery] = useState("");
  const [ownerSelected, setOwnerSelected] = useState(null); // { id, name }

  const apiBase = window.PULSE_CONFIG?.apiBase || "http://localhost:8000";

  // Fetch squad members once when modal opens
  React.useEffect(() => {
    if (!open || !authToken) return;
    fetch(`${apiBase}/squad/members`, {
      headers: { Authorization: `Bearer ${authToken}` },
    })
      .then((r) => (r.ok ? r.json() : []))
      .then((d) => setMembers(Array.isArray(d) ? d : []))
      .catch(() => {});
  }, [open, authToken]);

  const resetAll = () => {
    setTitle("");
    setBody("");
    setCategory("tech");
    setStatus("draft");
    setDecBody("");
    setDecTitle("");
    setDeciderQuery("");
    setDeciderSelected(null);
    setExpTitle("");
    setHypothesis("");
    setOwnerQuery("");
    setOwnerSelected(null);
    setSaving(false);
  };

  React.useEffect(() => {
    if (!open) {
      resetAll();
      return;
    }
    if (initialType) setType(initialType);
  }, [open, initialType]);

  React.useEffect(() => {
    const handler = (e) => {
      if (e.key === "Escape") onClose();
    };
    if (open) document.addEventListener("keydown", handler);
    return () => document.removeEventListener("keydown", handler);
  }, [open, onClose]);

  // Filter members for autocomplete
  const deciderMatches =
    deciderQuery.trim().length > 0
      ? members.filter((m) =>
          m.name.toLowerCase().includes(deciderQuery.toLowerCase()),
        )
      : [];

  const handleSave = async () => {
    setSaving(true);
    try {
      let endpoint, payload;
      if (type === "article") {
        endpoint = "/wiki/articles";
        payload = {
          title,
          body,
          category,
          status,
          tags: [],
          scope_id: scopeId || null,
        };
      } else if (type === "decision") {
        endpoint = "/wiki/decisions";
        payload = {
          title: decTitle,
          body: decBody,
          status: "open",
          tags: [],
          decider_id: deciderSelected?.id || null,
          scope_id: scopeId || null,
        };
      } else {
        endpoint = "/wiki/experiments";
        payload = {
          title: expTitle,
          hypothesis,
          owner_id: ownerSelected?.id || null,
          tags: [],
          scope_id: scopeId || null,
        };
      }
      const r = await fetch(`${apiBase}${endpoint}`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${authToken}`,
        },
        body: JSON.stringify(payload),
      });
      if (r.ok) {
        onSaved(type);
        onClose();
      } else {
        alert("Save failed — check console");
      }
    } catch (e) {
      console.error(e);
    } finally {
      setSaving(false);
    }
  };

  if (!open) return null;

  const typeLabels = {
    article: "Knowledge article",
    decision: "Decision",
    experiment: "Experiment",
  };

  return (
    <div
      className="modal-backdrop"
      onClick={(e) => e.target === e.currentTarget && onClose()}
    >
      <div className="modal" style={{ width: 520 }}>
        <div className="modal-head">
          <div className="modal-title">New wiki entry</div>
          <button className="modal-close" onClick={onClose}>
            ×
          </button>
        </div>
        <div style={{ padding: "16px 20px" }}>
          {/* Type selector */}
          <div style={{ display: "flex", gap: 8, marginBottom: 18 }}>
            {["article", "decision", "experiment"].map((t) => (
              <button
                key={t}
                onClick={() => setType(t)}
                className="btn"
                style={{
                  flex: 1,
                  fontWeight: type === t ? 600 : 400,
                  background: type === t ? "var(--accent-soft)" : undefined,
                  color: type === t ? "var(--accent)" : undefined,
                }}
              >
                {typeLabels[t]}
              </button>
            ))}
          </div>

          {type === "article" && (
            <>
              <label
                style={{
                  fontSize: 12,
                  color: "var(--ink-3)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                Title
              </label>
              <input
                className="wiki-search"
                style={{ marginBottom: 12 }}
                placeholder="e.g. Kafka throughput benchmarks"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
              />
              <label
                style={{
                  fontSize: 12,
                  color: "var(--ink-3)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                Category
              </label>
              <div style={{ display: "flex", gap: 8, marginBottom: 12 }}>
                {[
                  ["tech", "Tech"],
                  ["design", "Design"],
                  ["ways_of_working", "Ways of working"],
                ].map(([val, lbl]) => (
                  <button
                    key={val}
                    className="btn"
                    onClick={() => setCategory(val)}
                    style={{
                      flex: 1,
                      fontWeight: category === val ? 600 : 400,
                      background:
                        category === val ? "var(--accent-soft)" : undefined,
                      color: category === val ? "var(--accent)" : undefined,
                    }}
                  >
                    {lbl}
                  </button>
                ))}
              </div>
              <label
                style={{
                  fontSize: 12,
                  color: "var(--ink-3)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                Body
              </label>
              <textarea
                style={{
                  width: "100%",
                  minHeight: 100,
                  background: "var(--surface-2)",
                  border: "1px solid var(--line)",
                  borderRadius: 8,
                  padding: 10,
                  fontSize: 13,
                  color: "var(--ink-1)",
                  resize: "vertical",
                  boxSizing: "border-box",
                }}
                placeholder="What does the squad need to know?"
                value={body}
                onChange={(e) => setBody(e.target.value)}
              />
              <div style={{ display: "flex", gap: 8, marginTop: 10 }}>
                {[
                  ["draft", "Draft"],
                  ["live", "Live"],
                ].map(([val, lbl]) => (
                  <button
                    key={val}
                    className="btn"
                    onClick={() => setStatus(val)}
                    style={{
                      fontWeight: status === val ? 600 : 400,
                      background:
                        status === val ? "var(--accent-soft)" : undefined,
                      color: status === val ? "var(--accent)" : undefined,
                    }}
                  >
                    {lbl}
                  </button>
                ))}
              </div>
            </>
          )}

          {type === "decision" && (
            <>
              <label
                style={{
                  fontSize: 12,
                  color: "var(--ink-3)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                Decision title
              </label>
              <input
                className="wiki-search"
                style={{ marginBottom: 12 }}
                placeholder="e.g. Move to new ingestion path by Friday"
                value={decTitle}
                onChange={(e) => setDecTitle(e.target.value)}
              />
              <label
                style={{
                  fontSize: 12,
                  color: "var(--ink-3)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                Context / rationale
              </label>
              <textarea
                style={{
                  width: "100%",
                  minHeight: 80,
                  background: "var(--surface-2)",
                  border: "1px solid var(--line)",
                  borderRadius: 8,
                  padding: 10,
                  fontSize: 13,
                  color: "var(--ink-1)",
                  resize: "vertical",
                  boxSizing: "border-box",
                  marginBottom: 12,
                }}
                placeholder="What's the context? What options were considered?"
                value={decBody}
                onChange={(e) => setDecBody(e.target.value)}
              />
              <label
                style={{
                  fontSize: 12,
                  color: "var(--ink-3)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                Decider{" "}
                <span style={{ fontWeight: 400, color: "var(--ink-4)" }}>
                  (optional — if set, only this person can mark it as decided)
                </span>
              </label>
              {deciderSelected ? (
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 8,
                    padding: "6px 10px",
                    background: "var(--accent-soft)",
                    borderRadius: 7,
                    fontSize: 13,
                    color: "var(--accent)",
                  }}
                >
                  <Avatar name={deciderSelected.name} size="sm" />
                  <span style={{ fontWeight: 500 }}>
                    {deciderSelected.name}
                  </span>
                  <button
                    onClick={() => {
                      setDeciderSelected(null);
                      setDeciderQuery("");
                    }}
                    style={{
                      marginLeft: "auto",
                      border: 0,
                      background: "transparent",
                      color: "var(--ink-3)",
                      cursor: "pointer",
                      fontSize: 15,
                      lineHeight: 1,
                    }}
                  >
                    ×
                  </button>
                </div>
              ) : (
                <div>
                  <input
                    className="wiki-search"
                    placeholder="Search squad members…"
                    value={deciderQuery}
                    onChange={(e) => setDeciderQuery(e.target.value)}
                  />
                  {deciderMatches.length > 0 && (
                    <div
                      style={{
                        background: "var(--surface-2)",
                        border: "1px solid var(--line)",
                        borderRadius: 8,
                        marginTop: 4,
                        maxHeight: 180,
                        overflowY: "auto",
                      }}
                    >
                      {deciderMatches.map((m) => (
                        <div
                          key={m.id}
                          style={{
                            display: "flex",
                            alignItems: "center",
                            gap: 10,
                            padding: "8px 12px",
                            cursor: "pointer",
                            fontSize: 13,
                          }}
                          onMouseDown={(e) => {
                            e.preventDefault();
                            setDeciderSelected(m);
                            setDeciderQuery("");
                          }}
                          onMouseEnter={(e) =>
                            (e.currentTarget.style.background =
                              "var(--surface-3, rgba(255,255,255,0.05))")
                          }
                          onMouseLeave={(e) =>
                            (e.currentTarget.style.background = "")
                          }
                        >
                          <Avatar name={m.name} size="sm" />
                          <span>{m.name}</span>
                          <span
                            style={{
                              fontSize: 11.5,
                              color: "var(--ink-4)",
                              marginLeft: "auto",
                            }}
                          >
                            {m.role}
                          </span>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </>
          )}

          {type === "experiment" && (
            <>
              <label
                style={{
                  fontSize: 12,
                  color: "var(--ink-3)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                Experiment title
              </label>
              <input
                className="wiki-search"
                style={{ marginBottom: 12 }}
                placeholder="e.g. Progressive onboarding A/B"
                value={expTitle}
                onChange={(e) => setExpTitle(e.target.value)}
              />
              <label
                style={{
                  fontSize: 12,
                  color: "var(--ink-3)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                Hypothesis
              </label>
              <textarea
                style={{
                  width: "100%",
                  minHeight: 80,
                  background: "var(--surface-2)",
                  border: "1px solid var(--line)",
                  borderRadius: 8,
                  padding: 10,
                  fontSize: 13,
                  color: "var(--ink-1)",
                  resize: "vertical",
                  boxSizing: "border-box",
                  marginBottom: 12,
                }}
                placeholder="If we do X, we expect Y because Z."
                value={hypothesis}
                onChange={(e) => setHypothesis(e.target.value)}
              />
              <label
                style={{
                  fontSize: 12,
                  color: "var(--ink-3)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                Owner{" "}
                <span style={{ fontWeight: 400, color: "var(--ink-4)" }}>
                  (optional — who is running this experiment?)
                </span>
              </label>
              {ownerSelected ? (
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 8,
                    padding: "6px 10px",
                    background: "var(--accent-soft)",
                    borderRadius: 7,
                    fontSize: 13,
                    color: "var(--accent)",
                  }}
                >
                  <Avatar name={ownerSelected.name} size="sm" />
                  <span style={{ fontWeight: 500 }}>{ownerSelected.name}</span>
                  <button
                    onClick={() => {
                      setOwnerSelected(null);
                      setOwnerQuery("");
                    }}
                    style={{
                      marginLeft: "auto",
                      border: 0,
                      background: "transparent",
                      color: "var(--ink-3)",
                      cursor: "pointer",
                      fontSize: 15,
                      lineHeight: 1,
                    }}
                  >
                    ×
                  </button>
                </div>
              ) : (
                <div>
                  <input
                    className="wiki-search"
                    placeholder="Search squad members…"
                    value={ownerQuery}
                    onChange={(e) => setOwnerQuery(e.target.value)}
                  />
                  {ownerQuery.trim().length > 0 && (
                    <div
                      style={{
                        background: "var(--surface-2)",
                        border: "1px solid var(--line)",
                        borderRadius: 8,
                        marginTop: 4,
                        maxHeight: 180,
                        overflowY: "auto",
                      }}
                    >
                      {members
                        .filter((m) =>
                          m.name
                            .toLowerCase()
                            .includes(ownerQuery.toLowerCase()),
                        )
                        .map((m) => (
                          <div
                            key={m.id}
                            style={{
                              display: "flex",
                              alignItems: "center",
                              gap: 10,
                              padding: "8px 12px",
                              cursor: "pointer",
                              fontSize: 13,
                            }}
                            onMouseDown={(e) => {
                              e.preventDefault();
                              setOwnerSelected(m);
                              setOwnerQuery("");
                            }}
                            onMouseEnter={(e) =>
                              (e.currentTarget.style.background =
                                "var(--surface-3, rgba(255,255,255,0.05))")
                            }
                            onMouseLeave={(e) =>
                              (e.currentTarget.style.background = "")
                            }
                          >
                            <Avatar name={m.name} size="sm" />
                            <span>{m.name}</span>
                            <span
                              style={{
                                fontSize: 11.5,
                                color: "var(--ink-4)",
                                marginLeft: "auto",
                              }}
                            >
                              {m.role}
                            </span>
                          </div>
                        ))}
                    </div>
                  )}
                </div>
              )}
            </>
          )}

          <div
            style={{
              display: "flex",
              gap: 10,
              justifyContent: "flex-end",
              marginTop: 18,
            }}
          >
            <button className="btn" onClick={onClose}>
              Cancel
            </button>
            <button
              className="btn accent"
              onClick={handleSave}
              disabled={saving}
            >
              {saving ? "Saving…" : "Save"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Simple markdown renderer (bold, italic, code) ──────────
function renderMarkdown(text) {
  if (!text) return null;
  const parts = text.split(/(\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`)/g);
  return parts.map((part, i) => {
    if (part.startsWith("**") && part.endsWith("**")) {
      return React.createElement("strong", { key: i }, part.slice(2, -2));
    }
    if (part.startsWith("*") && part.endsWith("*")) {
      return React.createElement("em", { key: i }, part.slice(1, -1));
    }
    if (part.startsWith("`") && part.endsWith("`")) {
      return React.createElement(
        "code",
        {
          key: i,
          style: {
            background: "var(--accent-soft)",
            padding: "1px 4px",
            borderRadius: 3,
            fontSize: "0.9em",
          },
        },
        part.slice(1, -1),
      );
    }
    return part;
  });
}

// ── Wiki AI question bar ──────────────────────────────────
function WikiAskBar({ authToken, apiBase, scopeId }) {
  const [q, setQ] = React.useState("");
  const [answer, setAnswer] = React.useState(null);
  const [otherScopes, setOtherScopes] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);

  const submit = async () => {
    const question = q.trim();
    if (!question || loading) return;
    setLoading(true);
    setAnswer(null);
    setOtherScopes(null);
    setError(null);
    try {
      const res = await fetch(`${apiBase}/wiki/ask`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${authToken}`,
        },
        body: JSON.stringify({ question, scope_id: scopeId || null }),
      });
      if (!res.ok) throw new Error(`${res.status}`);
      const data = await res.json();
      setAnswer(data.answer);
      setOtherScopes(data.other_scopes || null);
    } catch (e) {
      setError(
        "Could not reach the AI. Check your AWS connection and try again.",
      );
    } finally {
      setLoading(false);
    }
  };

  const onKey = (e) => {
    if (e.key === "Enter") submit();
  };
  const clear = () => {
    setQ("");
    setAnswer(null);
    setOtherScopes(null);
    setError(null);
  };

  return (
    <div style={{ marginTop: 8, marginBottom: 20 }}>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 8,
          padding: "8px 14px",
          background: "var(--bg)",
          border: "1.5px solid var(--line)",
          borderRadius: 10,
          boxShadow: "0 1px 4px rgba(0,0,0,0.07)",
          transition: "border-color 0.15s, box-shadow 0.15s",
        }}
        onFocus={(e) => {
          e.currentTarget.style.borderColor = "var(--accent)";
          e.currentTarget.style.boxShadow = "0 0 0 3px var(--accent-soft)";
        }}
        onBlur={(e) => {
          e.currentTarget.style.borderColor = "var(--line)";
          e.currentTarget.style.boxShadow = "0 1px 4px rgba(0,0,0,0.07)";
        }}
      >
        <span
          style={{
            fontSize: 14,
            lineHeight: 1,
            flexShrink: 0,
            color: "var(--accent)",
          }}
        >
          ✦
        </span>
        <input
          value={q}
          onChange={(e) => setQ(e.target.value)}
          onKeyDown={onKey}
          placeholder="Ask the wiki a question…"
          style={{
            flex: 1,
            border: "none",
            background: "transparent",
            fontSize: 13,
            color: "var(--ink-1)",
            outline: "none",
            fontFamily: "inherit",
          }}
          disabled={loading}
        />
        {(q || answer !== null || error) && !loading && (
          <button
            onClick={clear}
            style={{
              border: 0,
              background: "transparent",
              color: "var(--ink-3)",
              cursor: "pointer",
              fontSize: 16,
              lineHeight: 1,
              padding: "0 2px",
            }}
          >
            ×
          </button>
        )}
        {loading && (
          <span style={{ fontSize: 12, color: "var(--ink-3)", flexShrink: 0 }}>
            Thinking…
          </span>
        )}
        {!loading && q.trim() && (
          <button
            onClick={submit}
            className="btn accent"
            style={{ padding: "3px 10px", fontSize: 12, flexShrink: 0 }}
          >
            Ask
          </button>
        )}
      </div>

      {answer !== null && (
        <div
          style={{
            marginTop: 8,
            padding: "12px 14px",
            background: "var(--bg)",
            border: "1.5px solid var(--accent-soft)",
            borderLeft: "3px solid var(--accent)",
            borderRadius: 10,
            fontSize: 13,
            lineHeight: 1.65,
            color: "var(--ink-1)",
            whiteSpace: "pre-wrap",
            boxShadow: "0 1px 4px rgba(0,0,0,0.06)",
          }}
        >
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 6,
              marginBottom: 8,
            }}
          >
            <span style={{ fontSize: 13, color: "var(--accent)" }}>✦</span>
            <span
              style={{
                fontSize: 11.5,
                fontWeight: 700,
                color: "var(--accent)",
                letterSpacing: "0.03em",
                textTransform: "uppercase",
              }}
            >
              Wiki answer
            </span>
          </div>
          {renderMarkdown(answer)}
          {otherScopes && (
            <div
              style={{
                marginTop: 12,
                paddingTop: 10,
                borderTop: "1px solid var(--line)",
                fontSize: 12.5,
                color: "var(--ink-2)",
                lineHeight: 1.6,
              }}
            >
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 5,
                  marginBottom: 4,
                  opacity: 0.7,
                }}
              >
                <Icon.Layers style={{ width: 11, height: 11 }} />
                <span
                  style={{
                    fontSize: 10.5,
                    fontWeight: 600,
                    textTransform: "uppercase",
                    letterSpacing: "0.04em",
                  }}
                >
                  From other levels
                </span>
              </div>
              {renderMarkdown(otherScopes)}
            </div>
          )}
        </div>
      )}

      {error && (
        <div
          style={{
            marginTop: 8,
            padding: "10px 14px",
            background: "var(--danger-soft)",
            border: "1px solid var(--danger)",
            borderRadius: 10,
            fontSize: 13,
            color: "var(--danger)",
          }}
        >
          {error}
        </div>
      )}
    </div>
  );
}

// ── Wiki main view ────────────────────────────────────────
function WikiView({
  authToken,
  authUser,
  highlightIds,
  wikiTarget,
  activeSquadId,
  userSquads,
  setActiveSquadId,
  canWrite = true,
  canRead = true,
}) {
  const [wiki, setWiki] = useState(null);
  const [section, setSection] = useState("knowledge");
  const [knowledgeCat, setKnowledgeCat] = useState("tech");
  const [q, setQ] = useState("");
  const [newModalOpen, setNewModalOpen] = useState(false);
  const [focusId, setFocusId] = useState(null);

  // Wiki scope hierarchy
  const [wikiScopes, setWikiScopes] = useState([]); // [{id, name, type}] — squad first, business last
  const [activeWikiScope, setActiveWikiScope] = useState(null); // scope id

  // After wiki loads or section changes, scroll the focused item into view
  React.useEffect(() => {
    if (!focusId) return;
    const attempt = (tries) => {
      const el = document.querySelector(`[data-wiki-id="${focusId}"]`);
      if (el) {
        el.scrollIntoView({ behavior: "smooth", block: "center" });
      } else if (tries > 0) {
        setTimeout(() => attempt(tries - 1), 120);
      }
    };
    attempt(8);
  }, [focusId, wiki, section, knowledgeCat]);

  // Navigate to the right section+item when a search result is clicked
  React.useEffect(() => {
    if (!wikiTarget) return;
    setSection(wikiTarget.section);
    if (wikiTarget.section === "knowledge" && wikiTarget.category) {
      const toUi = {
        tech: "tech",
        design: "design",
        ways_of_working: "waysOfWorking",
      };
      setKnowledgeCat(toUi[wikiTarget.category] || "tech");
    }
    if (wikiTarget.id) {
      setFocusId(wikiTarget.id);
      setTimeout(() => setFocusId(null), 3000);
    }
  }, [wikiTarget]);
  const [modalInitType, setModalInitType] = useState("article");

  const SECTION_TO_TYPE = {
    knowledge: "article",
    decisions: "decision",
    experiments: "experiment",
  };
  const openModal = (typeOverride) => {
    setModalInitType(typeOverride || SECTION_TO_TYPE[section] || "article");
    setNewModalOpen(true);
  };

  // File upload state
  const [uploadOpen, setUploadOpen] = useState(false);
  const [uploadFiles, setUploadFiles] = useState([]);
  const [uploadComment, setUploadComment] = useState("");
  const [uploading, setUploading] = useState(false);
  const [uploadResult, setUploadResult] = useState(null);
  const wikiFileRef = useRef(null);

  const apiBase = window.PULSE_CONFIG?.apiBase || "http://localhost:8000";

  // Load wiki scope hierarchy based on active squad
  React.useEffect(() => {
    if (!authToken) return;
    const squadParam = activeSquadId ? `?squad_id=${activeSquadId}` : "";
    fetch(`${apiBase}/wiki/scopes${squadParam}`, {
      headers: { Authorization: `Bearer ${authToken}` },
    })
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => {
        if (d && d.scopes) {
          setWikiScopes(d.scopes);
          // Default to the squad level (first item)
          if (d.scopes.length > 0) setActiveWikiScope(d.scopes[0].id);
        }
      })
      .catch(() => {});
  }, [authToken, activeSquadId]);

  const loadWiki = React.useCallback(() => {
    if (!authToken || !activeWikiScope) return;
    const scopeParam = activeWikiScope ? `?scope_id=${activeWikiScope}` : "";
    fetch(`${apiBase}/wiki${scopeParam}`, {
      headers: { Authorization: `Bearer ${authToken}` },
    })
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => {
        if (d) setWiki(d);
      })
      .catch(() => {});
  }, [authToken, activeWikiScope]);

  React.useEffect(() => {
    loadWiki();
  }, [loadWiki]);

  const handleSaved = (type) => {
    loadWiki();
    if (type === "decision") setSection("decisions");
    else if (type === "experiment") setSection("experiments");
    else setSection("knowledge");
  };

  const handleUpload = async () => {
    if (!uploadFiles.length || uploading) return;
    setUploading(true);
    setUploadResult(null);
    try {
      const formData = new FormData();
      uploadFiles.forEach((f) => formData.append("files", f));
      if (uploadComment.trim())
        formData.append("comment", uploadComment.trim());
      if (activeWikiScope) formData.append("scope_id", activeWikiScope);
      const r = await fetch(`${apiBase}/wiki/upload`, {
        method: "POST",
        headers: { Authorization: `Bearer ${authToken}` },
        body: formData,
      });
      if (!r.ok) {
        const err = await r.json().catch(() => ({}));
        setUploadResult({ error: err.detail || "Upload failed" });
      } else {
        const data = await r.json();
        setUploadResult({ success: true, created: data.created || [] });
        setUploadFiles([]);
        setUploadComment("");
        loadWiki();
      }
    } catch (e) {
      setUploadResult({ error: e.message });
    } finally {
      setUploading(false);
    }
  };

  const newIds = [...(highlightIds || []), ...(focusId ? [focusId] : [])];

  // Normalise knowledge keys (API uses ways_of_working, UI expects both)
  const knowledge = wiki
    ? {
        tech: wiki.knowledge.tech || [],
        design: wiki.knowledge.design || [],
        waysOfWorking: wiki.knowledge.ways_of_working || [],
      }
    : { tech: [], design: [], waysOfWorking: [] };

  // Map knowledgeCat UI id → key
  const CAT_KEY = {
    tech: "tech",
    design: "design",
    waysOfWorking: "waysOfWorking",
  };

  const allArticles = useMemo(
    () => [...knowledge.tech, ...knowledge.design, ...knowledge.waysOfWorking],
    [wiki],
  );

  const decisions = wiki?.decisions || [];
  const experiments = wiki?.experiments || [];

  const filteredSearch = useMemo(() => {
    if (!q || !wiki) return null;
    const lq = q.toLowerCase();
    return [
      ...allArticles.filter(
        (a) =>
          a.title.toLowerCase().includes(lq) ||
          (a.desc || "").toLowerCase().includes(lq),
      ),
      ...decisions.filter(
        (d) =>
          d.title.toLowerCase().includes(lq) ||
          d.body.toLowerCase().includes(lq),
      ),
      ...experiments.filter((e) => e.title.toLowerCase().includes(lq)),
    ];
  }, [q, wiki]);

  const decisionsOpen = decisions.filter((d) => d.status === "open");
  const decisionsDecided = decisions.filter((d) => d.status === "decided");
  const decisionsSuperseded = decisions.filter(
    (d) => d.status === "superseded",
  );

  const currentCatItems = knowledge[CAT_KEY[knowledgeCat]] || [];

  const SCOPE_LABELS = {
    squad: "Squad",
    team: "Team",
    function: "Function",
    business: "Business",
  };
  const SCOPE_ICONS = {
    squad: "Users",
    team: "Users",
    function: "Layers",
    business: "Globe",
  };
  const SCOPE_DESCS = {
    squad: "Day-to-day knowledge, decisions, and experiments",
    team: "Shared standards and patterns across squads",
    function: "Engineering-wide knowledge and policies",
    business: "Organisation-wide strategy and knowledge",
  };
  const activeScopeObj = wikiScopes.find((s) => s.id === activeWikiScope);
  const activeScopeType = activeScopeObj?.type || "squad";

  if (!canRead) {
    return (
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          padding: "80px 20px",
          textAlign: "center",
        }}
      >
        <div style={{ fontSize: 40, marginBottom: 16, opacity: 0.3 }}>🔒</div>
        <h2
          style={{
            fontSize: 16,
            fontWeight: 600,
            color: "var(--ink)",
            margin: "0 0 8px",
          }}
        >
          Wiki access restricted
        </h2>
        <p
          style={{
            fontSize: 13,
            color: "var(--ink-3)",
            margin: 0,
            maxWidth: 320,
          }}
        >
          You don't have permission to view the wiki. Contact your administrator
          to request access.
        </p>
      </div>
    );
  }

  return (
    <>
      <NewWikiModal
        open={newModalOpen}
        onClose={() => setNewModalOpen(false)}
        authToken={authToken}
        onSaved={handleSaved}
        initialType={modalInitType}
        scopeId={activeWikiScope}
      />

      <div className="main-head">
        <div>
          <div className="main-title">{activeScopeObj?.name || "Wiki"}</div>
          <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 4 }}>
            {SCOPE_DESCS[activeScopeType]}
          </div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button
            className="btn"
            onClick={() => canWrite && setUploadOpen((o) => !o)}
            disabled={!canWrite}
            style={{
              display: "flex",
              alignItems: "center",
              gap: 6,
              opacity: canWrite ? 1 : 0.4,
              cursor: canWrite ? "pointer" : "not-allowed",
            }}
          >
            <Icon.File style={{ width: 12, height: 12 }} />
            Upload docs
          </button>
          <button
            className="btn accent"
            onClick={() => canWrite && openModal()}
            disabled={!canWrite}
            style={{
              opacity: canWrite ? 1 : 0.4,
              cursor: canWrite ? "pointer" : "not-allowed",
            }}
          >
            <Icon.Plus
              style={{
                width: 12,
                height: 12,
                marginRight: 6,
                verticalAlign: -1,
              }}
            />
            New entry
          </button>
        </div>
      </div>

      {/* Scope switcher */}
      {wikiScopes.length > 1 && (
        <div className="wiki-scope-switcher">
          {wikiScopes.map((s, i) => {
            const I = Icon[SCOPE_ICONS[s.type]] || Icon.Hash;
            const isActive = s.id === activeWikiScope;
            const isSquadLevel = s.type === "squad";
            const hasMultiSquads =
              isSquadLevel && userSquads && userSquads.length > 1;
            return (
              <React.Fragment key={s.id}>
                {i > 0 && <span className="wiki-scope-sep">›</span>}
                {hasMultiSquads ? (
                  <span className="wiki-scope-squad-group">
                    {userSquads.map((sq) => (
                      <button
                        key={sq.id}
                        className={`wiki-scope-btn${activeSquadId === sq.id ? " active" : ""}`}
                        onClick={() => {
                          if (sq.id !== activeSquadId) {
                            setActiveSquadId(sq.id);
                          }
                        }}
                      >
                        <I style={{ width: 12, height: 12 }} />
                        <span>{sq.name}</span>
                        <span className="wiki-scope-type">Squad</span>
                      </button>
                    ))}
                  </span>
                ) : (
                  <button
                    className={`wiki-scope-btn${isActive ? " active" : ""}`}
                    onClick={() => {
                      if (s.id !== activeWikiScope) {
                        setActiveWikiScope(s.id);
                        setWiki(null);
                      }
                    }}
                  >
                    <I style={{ width: 12, height: 12 }} />
                    <span>{s.name}</span>
                    <span className="wiki-scope-type">
                      {SCOPE_LABELS[s.type]}
                    </span>
                  </button>
                )}
              </React.Fragment>
            );
          })}
        </div>
      )}

      {/* Upload panel */}
      {uploadOpen && (
        <div className="wiki-upload-panel">
          <input
            ref={wikiFileRef}
            type="file"
            multiple
            accept=".pdf,.docx,.pptx,.xlsx,.xls,.txt,.md,.csv,.log,.json,.yaml,.yml,.png,.jpg,.jpeg,.gif,.webp"
            style={{ display: "none" }}
            onChange={(e) => {
              const newFiles = Array.from(e.target.files || []);
              setUploadFiles((prev) => [...prev, ...newFiles].slice(0, 5));
              e.target.value = "";
            }}
          />
          {uploadFiles.length === 0 ? (
            <div
              className="file-drop-zone"
              onClick={() => wikiFileRef.current?.click()}
              onDragOver={(e) => {
                e.preventDefault();
                e.currentTarget.classList.add("dragover");
              }}
              onDragLeave={(e) => {
                e.currentTarget.classList.remove("dragover");
              }}
              onDrop={(e) => {
                e.preventDefault();
                e.currentTarget.classList.remove("dragover");
                const newFiles = Array.from(e.dataTransfer.files || []);
                setUploadFiles((prev) => [...prev, ...newFiles].slice(0, 5));
              }}
            >
              <Icon.File
                style={{ width: 20, height: 20, color: "var(--ink-3)" }}
              />
              <span>Drop files here or click to browse</span>
              <span className="file-hint">
                AI will read your documents and create wiki entries
                automatically
              </span>
            </div>
          ) : (
            <div>
              <div className="file-list">
                {uploadFiles.map((f, i) => (
                  <div key={i} className="file-item">
                    <Icon.File
                      style={{ width: 14, height: 14, flexShrink: 0 }}
                    />
                    <span className="file-name">{f.name}</span>
                    <span className="file-size">
                      {(f.size / 1024).toFixed(0)}KB
                    </span>
                    <button
                      className="file-remove"
                      onClick={() =>
                        setUploadFiles((prev) => prev.filter((_, j) => j !== i))
                      }
                      aria-label="Remove file"
                    >
                      &times;
                    </button>
                  </div>
                ))}
                {uploadFiles.length < 5 && (
                  <button
                    className="btn"
                    style={{ fontSize: 12, padding: "4px 10px", marginTop: 6 }}
                    onClick={() => wikiFileRef.current?.click()}
                  >
                    + Add more
                  </button>
                )}
              </div>
              <input
                style={{
                  width: "100%",
                  marginTop: 10,
                  padding: "8px 10px",
                  border: "1px solid var(--line)",
                  borderRadius: 7,
                  fontSize: 12.5,
                  background: "var(--surface-2)",
                  boxSizing: "border-box",
                }}
                placeholder="Optional note — e.g. 'From our Q2 retro deck'"
                value={uploadComment}
                onChange={(e) => setUploadComment(e.target.value)}
              />
              <div
                style={{
                  display: "flex",
                  gap: 8,
                  marginTop: 10,
                  justifyContent: "flex-end",
                }}
              >
                <button
                  className="btn"
                  onClick={() => {
                    setUploadOpen(false);
                    setUploadFiles([]);
                    setUploadComment("");
                    setUploadResult(null);
                  }}
                >
                  Cancel
                </button>
                <button
                  className="btn accent"
                  onClick={handleUpload}
                  disabled={uploading}
                >
                  {uploading ? (
                    <>
                      <Icon.Spark
                        style={{
                          width: 12,
                          height: 12,
                          marginRight: 6,
                          animation: "spin 1s linear infinite",
                        }}
                      />
                      AI is reading…
                    </>
                  ) : (
                    <>
                      <Icon.Spark
                        style={{ width: 12, height: 12, marginRight: 6 }}
                      />
                      Upload &amp; create entries
                    </>
                  )}
                </button>
              </div>
            </div>
          )}
          {uploadResult?.error && (
            <div
              style={{
                fontSize: 12,
                color: "var(--danger)",
                marginTop: 8,
                padding: "6px 10px",
                background: "var(--danger-soft)",
                borderRadius: 6,
              }}
            >
              ⚠ {uploadResult.error}
            </div>
          )}
          {uploadResult?.success && (
            <div
              style={{
                fontSize: 12,
                color: "var(--ok)",
                marginTop: 8,
                padding: "8px 10px",
                background: "rgba(41,178,99,0.08)",
                borderRadius: 6,
              }}
            >
              ✓ Created {uploadResult.created.length} wiki{" "}
              {uploadResult.created.length === 1 ? "entry" : "entries"}:
              {uploadResult.created.map((c, i) => (
                <span
                  key={i}
                  style={{
                    display: "block",
                    marginTop: 3,
                    color: "var(--ink-2)",
                  }}
                >
                  • {c.type}: {c.title}
                </span>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Search */}
      <div className="wiki-search">
        <Icon.Search style={{ width: 14, height: 14 }} />
        <input
          placeholder="Search wiki…"
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
        {q && (
          <button
            style={{
              border: 0,
              background: "transparent",
              color: "var(--ink-3)",
              cursor: "pointer",
              lineHeight: 1,
            }}
            onClick={() => setQ("")}
          >
            ×
          </button>
        )}
      </div>

      {/* AI question bar */}
      <WikiAskBar
        authToken={authToken}
        apiBase={apiBase}
        scopeId={activeWikiScope}
      />

      {/* Global search results */}
      {filteredSearch && (
        <>
          <div
            style={{
              fontSize: 12.5,
              color: "var(--ink-3)",
              margin: "4px 0 14px",
            }}
          >
            {filteredSearch.length} result
            {filteredSearch.length !== 1 ? "s" : ""} for "{q}"
          </div>
          {filteredSearch.length === 0 && (
            <div
              className="card"
              style={{
                textAlign: "center",
                color: "var(--ink-3)",
                padding: "32px 18px",
              }}
            >
              Nothing found. Try a different term.
            </div>
          )}
          {filteredSearch.map((item) => (
            <ArticleRow
              key={item.id}
              item={{
                ...item,
                desc: item.desc || item.body || item.outcome || "",
              }}
              isNew={newIds.includes(item.id)}
              isFocused={focusId === item.id}
              authUser={authUser}
              authToken={authToken}
              onRefresh={loadWiki}
            />
          ))}
        </>
      )}

      {/* Sectioned content (hidden during search) */}
      {!filteredSearch && (
        <div
          className="wiki-layout"
          style={{
            display: "grid",
            gridTemplateColumns: "188px 1fr",
            gap: 20,
            alignItems: "start",
          }}
        >
          {/* Section nav */}
          <nav className="wiki-nav">
            {WIKI_SECTIONS.map((s) => {
              const I = Icon[s.icon];
              const badge = s.id === "decisions" ? decisionsOpen.length : null;
              return (
                <button
                  key={s.id}
                  className="wiki-nav-item"
                  aria-current={section === s.id}
                  onClick={() => setSection(s.id)}
                >
                  <I style={{ width: 14, height: 14, flexShrink: 0 }} />
                  {s.label}
                  {badge > 0 && <span className="wiki-badge">{badge}</span>}
                </button>
              );
            })}

            <div
              style={{ borderTop: "1px solid var(--line)", margin: "8px 0" }}
            ></div>
            <div
              className="kicker"
              style={{ padding: "4px 8px 6px", display: "block" }}
            >
              Quick stats
            </div>
            <div className="wiki-stat-row">
              <span>Articles</span>
              <span className="mono">{allArticles.length}</span>
            </div>
            <div className="wiki-stat-row">
              <span>Decisions</span>
              <span className="mono">{decisions.length}</span>
            </div>
            <div className="wiki-stat-row">
              <span>Experiments</span>
              <span className="mono">{experiments.length}</span>
            </div>
            <div className="wiki-stat-row" style={{ color: "var(--warn)" }}>
              <span>Open decisions</span>
              <span className="mono">{decisionsOpen.length}</span>
            </div>
          </nav>

          {/* Section body */}
          <div className="wiki-content">
            {!wiki && (
              <div
                style={{
                  color: "var(--ink-3)",
                  fontSize: 13,
                  padding: "24px 0",
                }}
              >
                Loading…
              </div>
            )}

            {/* ── Knowledge base ── */}
            {wiki && section === "knowledge" && (
              <>
                <div className="wiki-cat-tabs">
                  {KNOWLEDGE_CATS.map((c) => {
                    const I = Icon[c.icon];
                    const items = knowledge[CAT_KEY[c.id]] || [];
                    return (
                      <button
                        key={c.id}
                        className="wiki-cat-tab"
                        aria-current={knowledgeCat === c.id}
                        onClick={() => setKnowledgeCat(c.id)}
                      >
                        <I style={{ width: 13, height: 13 }} />
                        {c.label}
                        <span
                          style={{
                            fontSize: 11,
                            color: "var(--ink-4)",
                            marginLeft: 4,
                          }}
                        >
                          {items.length}
                        </span>
                      </button>
                    );
                  })}
                </div>
                {currentCatItems.map((item) => (
                  <ArticleRow
                    key={item.id}
                    item={item}
                    isNew={newIds.includes(item.id)}
                    isFocused={focusId === item.id}
                    authUser={authUser}
                    authToken={authToken}
                    onRefresh={loadWiki}
                  />
                ))}
                {currentCatItems.length === 0 && (
                  <div
                    className="card"
                    style={{
                      textAlign: "center",
                      color: "var(--ink-3)",
                      padding: "32px 18px",
                    }}
                  >
                    No articles here yet.{" "}
                    <button
                      className="btn"
                      style={{ marginLeft: 8, fontSize: 12 }}
                      onClick={() => openModal("article")}
                    >
                      Add one
                    </button>
                  </div>
                )}
              </>
            )}

            {/* ── Decision log ── */}
            {wiki && section === "decisions" && (
              <>
                {decisionsOpen.length > 0 && (
                  <div className="wiki-section-group">
                    <div className="wiki-group-label">
                      <Icon.Blocker
                        style={{ width: 12, height: 12, color: "var(--warn)" }}
                      />
                      Needs a decision
                      <span className="wiki-badge warn">
                        {decisionsOpen.length}
                      </span>
                    </div>
                    {decisionsOpen.map((d) => (
                      <DecisionRow
                        key={d.id}
                        d={d}
                        isFocused={focusId === d.id}
                        authUser={authUser}
                        authToken={authToken}
                        onRefresh={loadWiki}
                      />
                    ))}
                  </div>
                )}
                {decisionsDecided.length > 0 && (
                  <div className="wiki-section-group">
                    <div className="wiki-group-label">
                      <Icon.Check
                        style={{ width: 12, height: 12, color: "var(--ok)" }}
                      />
                      Decided
                    </div>
                    {decisionsDecided.map((d) => (
                      <DecisionRow
                        key={d.id}
                        d={d}
                        isFocused={focusId === d.id}
                        authUser={authUser}
                        authToken={authToken}
                        onRefresh={loadWiki}
                      />
                    ))}
                  </div>
                )}
                {decisionsSuperseded.length > 0 && (
                  <div className="wiki-section-group">
                    <div className="wiki-group-label" style={{ opacity: 0.6 }}>
                      <Icon.File style={{ width: 12, height: 12 }} />
                      Superseded
                    </div>
                    {decisionsSuperseded.map((d) => (
                      <DecisionRow
                        key={d.id}
                        d={d}
                        isFocused={focusId === d.id}
                        authUser={authUser}
                        authToken={authToken}
                        onRefresh={loadWiki}
                      />
                    ))}
                  </div>
                )}
                {decisions.length === 0 && (
                  <div
                    className="card"
                    style={{
                      textAlign: "center",
                      color: "var(--ink-3)",
                      padding: "32px 18px",
                    }}
                  >
                    No decisions logged yet. Post a check-in mentioning a
                    decision, or{" "}
                    <button
                      className="btn"
                      style={{ marginLeft: 4, fontSize: 12 }}
                      onClick={() => openModal("decision")}
                    >
                      add one manually
                    </button>
                  </div>
                )}
              </>
            )}

            {/* ── Experiments ── */}
            {wiki &&
              section === "experiments" &&
              (() => {
                const running = experiments.filter(
                  (e) => e.status === "running",
                );
                const completed = experiments.filter(
                  (e) => e.status !== "running",
                );
                return (
                  <>
                    <div
                      style={{
                        fontSize: 13,
                        color: "var(--ink-3)",
                        marginBottom: 14,
                        lineHeight: 1.55,
                      }}
                    >
                      Hypotheses run by the squad, with structured outcomes.
                      Learnings feed back into the knowledge base.
                    </div>
                    {running.length > 0 && (
                      <div className="wiki-section-group">
                        <div className="wiki-group-label">
                          <Icon.Idea
                            style={{
                              width: 12,
                              height: 12,
                              color: "var(--warn)",
                            }}
                          />
                          Running
                        </div>
                        {running.map((e) => (
                          <ExperimentRow
                            key={e.id}
                            e={e}
                            isFocused={focusId === e.id}
                            authUser={authUser}
                            authToken={authToken}
                            onRefresh={loadWiki}
                          />
                        ))}
                      </div>
                    )}
                    {completed.length > 0 && (
                      <div
                        className="wiki-section-group"
                        style={{ marginTop: running.length > 0 ? 20 : 0 }}
                      >
                        <div className="wiki-group-label">
                          <Icon.Check
                            style={{
                              width: 12,
                              height: 12,
                              color: "var(--ok)",
                            }}
                          />
                          Completed / Abandoned
                        </div>
                        {completed.map((e) => (
                          <ExperimentRow
                            key={e.id}
                            e={e}
                            isFocused={focusId === e.id}
                            authUser={authUser}
                            authToken={authToken}
                            onRefresh={loadWiki}
                          />
                        ))}
                      </div>
                    )}
                    {experiments.length === 0 && (
                      <div
                        className="card"
                        style={{
                          textAlign: "center",
                          color: "var(--ink-3)",
                          padding: "32px 18px",
                        }}
                      >
                        No experiments yet.{" "}
                        <button
                          className="btn"
                          style={{ marginLeft: 4, fontSize: 12 }}
                          onClick={() => openModal("experiment")}
                        >
                          Log one
                        </button>
                      </div>
                    )}
                  </>
                );
              })()}
          </div>
        </div>
      )}
    </>
  );
}

// ── Person profile ────────────────────────────────────────
function PersonView({ personId, squad, authToken, onBack }) {
  const { SQUAD } = window.SEED;
  const liveSquad = squad && squad.length ? squad : SQUAD;
  const p =
    liveSquad.find((s) => s.id === personId) ||
    SQUAD.find((s) => s.id === personId) ||
    SQUAD[4];

  const [data, setData] = React.useState(null);
  const apiBase = window.PULSE_CONFIG?.apiBase || "http://localhost:8000";

  React.useEffect(() => {
    if (!authToken || !personId) return;
    setData(null);
    fetch(`${apiBase}/users/${personId}/history`, {
      headers: { Authorization: `Bearer ${authToken}` },
    })
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => {
        if (d) setData(d);
      })
      .catch(() => {});
  }, [authToken, personId]);

  const TAG_META = {
    decision: { cls: "decision", label: "Decision" },
    blocker: { cls: "blocker", label: "Blocker" },
    knowledge: { cls: "knowledge", label: "Knowledge" },
    experiment: { cls: "experiment", label: "Experiment" },
    idea: { cls: "idea", label: "Idea" },
    outcome: { cls: "outcome", label: "Outcome" },
    voice: { cls: "voice", label: "Voice" },
  };

  const heatClass = (cell) => {
    if (!cell.count) return "";
    const map = {
      decision: "decision-heat",
      blocker: "blocker-heat",
      knowledge: "knowledge-heat",
      experiment: "experiment-heat",
      idea: "idea-heat",
      outcome: "outcome-heat",
      voice: "voice-heat",
    };
    return map[cell.tag] || "lv2";
  };

  const name = data?.name || p?.name || "";
  const role = data?.role || p?.role || "";

  return (
    <>
      <button className="back" onClick={onBack}>
        <Icon.ArrowLeft />
        Back to updates
      </button>
      <div className="person-head">
        <Avatar name={name} size="lg" />
        <div style={{ flex: 1 }}>
          <div className="person-name">{name}</div>
          <div className="person-role">{role} · Centrica Innovation</div>
          <div className="person-actions">
            <button className="btn accent">
              <Icon.Send
                style={{
                  width: 12,
                  height: 12,
                  marginRight: 6,
                  verticalAlign: -1,
                }}
              />
              Request check-in
            </button>
            <button className="btn">
              <Icon.Mail
                style={{
                  width: 12,
                  height: 12,
                  marginRight: 6,
                  verticalAlign: -1,
                }}
              />
              Send email
            </button>
          </div>
        </div>
      </div>

      {!data && (
        <div style={{ color: "var(--ink-3)", fontSize: 13, padding: "24px 0" }}>
          Loading…
        </div>
      )}

      {data && (
        <>
          <div className="stat-grid">
            <div className="stat">
              <div className="stat-label">Check-ins this quarter</div>
              <div className="stat-value">{data.quarter_count}</div>
              <div className="stat-sub">{data.quarter_label}</div>
            </div>
            <div className="stat">
              <div className="stat-label">Current streak</div>
              <div className="stat-value ok">{data.streak}</div>
              <div className="stat-sub">Days in a row</div>
            </div>
          </div>

          <div className="card">
            <div
              style={{
                display: "flex",
                alignItems: "center",
                gap: 8,
                marginBottom: 12,
              }}
            >
              <Icon.Calendar
                style={{ color: "var(--ink-3)", width: 14, height: 14 }}
              />
              <div
                style={{
                  fontSize: 14,
                  fontWeight: 600,
                  letterSpacing: "-0.1px",
                }}
              >
                Check-in history
              </div>
              <div
                style={{
                  marginLeft: "auto",
                  fontSize: 12,
                  color: "var(--ink-3)",
                }}
              >
                Last 90 days
              </div>
            </div>
            <div className="heatmap">
              {data.heatmap.map((cell, i) => (
                <div
                  key={i}
                  className={`heat ${heatClass(cell)}`}
                  data-tip={
                    cell.count
                      ? `${cell.date}: ${cell.count} check-in${cell.count > 1 ? "s" : ""}`
                      : cell.date
                  }
                />
              ))}
            </div>
            <div className="heatmap-legend">
              <span>Less</span>
              <div className="swatches">
                <span
                  className="sw"
                  style={{ background: "rgba(31,26,46,0.06)" }}
                />
                <span className="sw" style={{ background: "var(--ok)" }} />
                <span className="sw" style={{ background: "var(--warn)" }} />
                <span className="sw" style={{ background: "var(--danger)" }} />
                <span className="sw" style={{ background: "var(--accent)" }} />
              </div>
              <span>More</span>
            </div>
          </div>

          {data.recent.length > 0 && (
            <>
              <h3
                style={{
                  fontSize: 15,
                  fontWeight: 600,
                  letterSpacing: "-0.2px",
                  margin: "20px 0 10px",
                }}
              >
                Recent check-ins
              </h3>
              {data.recent.map((ci) => (
                <div
                  key={ci.id}
                  className="update"
                  style={{ marginBottom: 10 }}
                >
                  <div
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 8,
                      marginBottom: 4,
                    }}
                  >
                    <span style={{ fontSize: 12, color: "var(--ink-3)" }}>
                      {ci.date}
                    </span>
                    <div style={{ display: "flex", gap: 4 }}>
                      {ci.tags.map((t) => {
                        const m = TAG_META[t.toLowerCase()] || {
                          cls: "ghost",
                          label: t,
                        };
                        return (
                          <span
                            key={t}
                            className={`tag ${m.cls}`}
                            style={{ fontSize: 10.5 }}
                          >
                            {m.label}
                          </span>
                        );
                      })}
                    </div>
                  </div>
                  <div style={{ fontSize: 13, color: "var(--ink-2)" }}>
                    {ci.title}
                  </div>
                </div>
              ))}
            </>
          )}
          {data.recent.length === 0 && (
            <div
              className="card"
              style={{
                textAlign: "center",
                color: "var(--ink-3)",
                padding: "24px",
                fontSize: 13,
              }}
            >
              No check-ins yet from {name.split(" ")[0]}.
            </div>
          )}
        </>
      )}
    </>
  );
}

// ── My Check-Ins history ──────────────────────────────────
function HistoryView({ authToken }) {
  const [data, setData] = React.useState(null);
  const [openCheckIn, setOpenCheckIn] = React.useState(null);

  React.useEffect(() => {
    if (!authToken) return;
    const apiBase = window.PULSE_CONFIG?.apiBase || "http://localhost:8000";
    fetch(`${apiBase}/me/history`, {
      headers: { Authorization: `Bearer ${authToken}` },
    })
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => {
        if (d) setData(d);
      })
      .catch(() => {});
  }, [authToken]);

  // Tag → CSS class + display label
  const TAG_META = {
    decision: { cls: "decision", label: "Decision" },
    blocker: { cls: "blocker", label: "Blocker" },
    knowledge: { cls: "knowledge", label: "Knowledge" },
    experiment: { cls: "experiment", label: "Experiment" },
    idea: { cls: "idea", label: "Idea" },
    outcome: { cls: "outcome", label: "Outcome" },
    voice: { cls: "voice", label: "Voice" },
  };

  // Heatmap cell colour by tag
  const heatClass = (cell) => {
    if (!cell.count) return "";
    if (!cell.tag) return "lv2";
    const map = {
      decision: "decision-heat",
      blocker: "blocker-heat",
      knowledge: "knowledge-heat",
      experiment: "experiment-heat",
      idea: "idea-heat",
      outcome: "outcome-heat",
      voice: "voice-heat",
    };
    return map[cell.tag] || "lv2";
  };

  return (
    <>
      <div className="main-head">
        <div>
          <div className="main-title">My Check-Ins</div>
          <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 4 }}>
            Your personal timeline. Nothing here is shared beyond your squad
            unless you say so.
          </div>
        </div>
      </div>

      <div className="stat-grid">
        <div className="stat">
          <div className="stat-label">Total this quarter</div>
          <div className="stat-value">{data ? data.quarter_count : "—"}</div>
          <div className="stat-sub">
            {data ? `Since ${data.quarter_since}` : ""}
          </div>
        </div>
        <div className="stat">
          <div className="stat-label">Current streak</div>
          <div className={`stat-value${data && data.streak > 0 ? " ok" : ""}`}>
            {data ? data.streak : "—"}
          </div>
          <div className="stat-sub">
            {data ? (data.streak === 1 ? "Day in a row" : "Days in a row") : ""}
          </div>
        </div>
        <div className="stat">
          <div className="stat-label">Quarter</div>
          <div className="stat-value" style={{ fontSize: 17 }}>
            {data ? data.quarter_label : "—"}
          </div>
          <div className="stat-sub">
            {data && data.quarter_count > 0
              ? `${data.quarter_count} check-in${data.quarter_count !== 1 ? "s" : ""}`
              : "No check-ins yet"}
          </div>
        </div>
      </div>

      <div className="card">
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 8,
            marginBottom: 12,
          }}
        >
          <Icon.Calendar
            style={{ color: "var(--ink-3)", width: 14, height: 14 }}
          />
          <div
            style={{ fontSize: 14, fontWeight: 600, letterSpacing: "-0.1px" }}
          >
            Check-in rhythm · last 90 days
          </div>
        </div>
        {/* Tag legend */}
        <div
          style={{
            display: "flex",
            gap: 12,
            marginBottom: 10,
            flexWrap: "wrap",
          }}
        >
          {[
            ["decision-heat", "Decision"],
            ["blocker-heat", "Blocker"],
            ["knowledge-heat", "Knowledge"],
            ["experiment-heat", "Experiment"],
            ["idea-heat", "Idea"],
            ["outcome-heat", "Outcome"],
            ["voice-heat", "Voice"],
            ["lv2", "Check-in"],
          ].map(([cls, label]) => (
            <span
              key={cls}
              style={{
                display: "flex",
                alignItems: "center",
                gap: 5,
                fontSize: 11.5,
                color: "var(--ink-3)",
              }}
            >
              <span
                style={{
                  width: 10,
                  height: 10,
                  borderRadius: 2,
                  display: "inline-block",
                }}
                className={`heat ${cls}`}
              />
              {label}
            </span>
          ))}
        </div>
        <div className="heatmap">
          {data
            ? data.heatmap.map((cell, i) => (
                <div
                  key={i}
                  data-tip={
                    cell.count
                      ? `${cell.date} · ${cell.count} check-in${cell.count !== 1 ? "s" : ""}${cell.tag ? ` · ${cell.tag}` : ""}`
                      : cell.date
                  }
                  className={`heat ${heatClass(cell)}`}
                />
              ))
            : Array.from({ length: 90 }).map((_, i) => (
                <div key={i} className="heat" />
              ))}
        </div>
      </div>

      <h3
        style={{
          fontSize: 15,
          fontWeight: 600,
          letterSpacing: "-0.2px",
          margin: "20px 0 6px",
        }}
      >
        Recent
      </h3>
      {!data && (
        <div style={{ color: "var(--ink-3)", fontSize: 13 }}>Loading…</div>
      )}
      {data && !data.recent.length && (
        <div style={{ color: "var(--ink-3)", fontSize: 13 }}>
          No check-ins yet. Post your first one above.
        </div>
      )}
      {data &&
        data.recent.map((h, i) => (
          <div
            key={h.id || i}
            className="hist-row"
            style={{ cursor: "pointer" }}
            onClick={() => {
              const dt = h.created_at ? new Date(h.created_at) : null;
              setOpenCheckIn({
                id: h.id,
                who: "You",
                role: "",
                you: true,
                title: h.title,
                body: h.has_audio ? null : h.body || null,
                fullTranscript: h.full_transcript || null,
                voice: h.has_audio
                  ? { url: null, duration: h.duration_s, transcript: h.body }
                  : null,
                tags: h.tags || [],
                time: h.date,
                createdAt: h.created_at || "",
                aiRows: (h.signals || []).map((s) => ({
                  kind: s.kind,
                  text: s.body,
                  quote: s.quote || null,
                  assignee: s.assignee || null,
                  importance: s.importance || 3,
                })),
              });
            }}
          >
            <div className="hist-date">
              {h.date}
              <br />
              <span style={{ color: "var(--ink-4)" }}>{h.year}</span>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="hist-title">{h.title}</div>
              {h.body && h.body !== h.title && (
                <div
                  className="hist-body"
                  style={{
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                    maxWidth: 480,
                  }}
                >
                  {h.body}
                </div>
              )}
            </div>
            <div className="hist-tags">
              {h.tags.map((t) => {
                const meta = TAG_META[t.toLowerCase()] || {
                  cls: "ghost",
                  label: t,
                };
                return (
                  <span key={t} className={`tag ${meta.cls}`}>
                    {meta.label}
                  </span>
                );
              })}
            </div>
          </div>
        ))}

      {openCheckIn && (
        <CheckInDetailModal
          u={openCheckIn}
          authToken={authToken}
          onClose={() => setOpenCheckIn(null)}
          onUpdate={(id, fields) =>
            setOpenCheckIn((o) => (o && o.id === id ? { ...o, ...fields } : o))
          }
          onDelete={() => {
            setOpenCheckIn(null);
            setData(null);
            const apiBase =
              window.PULSE_CONFIG?.apiBase || "http://localhost:8000";
            fetch(`${apiBase}/me/history`, {
              headers: { Authorization: `Bearer ${authToken}` },
            })
              .then((r) => (r.ok ? r.json() : null))
              .then((d) => {
                if (d) setData(d);
              });
          }}
        />
      )}
    </>
  );
}

// ── Admin: SSO Group Mappings ─────────────────────────────────────────────
function AdminView({ authToken, onDataChange }) {
  const apiBase = window.PULSE_CONFIG?.apiBase;
  const [adminTab, setAdminTab] = useState("users"); // 'users' | 'groups' | 'mappings'
  const [mappings, setMappings] = useState([]);
  const [orgs, setOrgs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [adding, setAdding] = useState(false);
  const [form, setForm] = useState({
    entra_group_id: "",
    squad_id: "",
    label: "",
    default_role: "",
    default_timezone: "",
    default_rhythm: "",
  });
  const [saving, setSaving] = useState(false);

  // Users management state
  const [users, setUsers] = useState([]);
  const [usersLoading, setUsersLoading] = useState(true);
  const [addingUser, setAddingUser] = useState(false);
  const [userForm, setUserForm] = useState({
    email: "",
    name: "",
    role: "",
    role_tag: "",
    squad_ids: [],
    timezone: "",
    rhythm: "",
    access_group_id: "",
  });
  const [savingUser, setSavingUser] = useState(false);

  // Access groups state
  const [accessGroups, setAccessGroups] = useState([]);
  const [accessGroupsLoading, setAccessGroupsLoading] = useState(true);
  const [addingGroup, setAddingGroup] = useState(false);
  const [groupForm, setGroupForm] = useState({
    name: "",
    default_squad_ids: [],
    default_role: "",
    default_timezone: "",
    default_rhythm: "",
    is_default: false,
    permissions: {
      read_scope: "business",
      checkin_scope: "business",
      todos: true,
      wiki_read: true,
      wiki_write: true,
    },
  });
  const [savingGroup, setSavingGroup] = useState(false);
  const [expandedGroup, setExpandedGroup] = useState(null);
  const [groupMembers, setGroupMembers] = useState({});

  // Vocabulary (transcription terms) state
  const [vocab, setVocab] = useState([]);
  const [vocabLoading, setVocabLoading] = useState(true);
  const [vocabForm, setVocabForm] = useState({ term: "", aliases: "" });
  const [savingVocab, setSavingVocab] = useState(false);

  // Team to-do board state
  const [todoBoard, setTodoBoard] = useState([]);
  const [todoBoardLoading, setTodoBoardLoading] = useState(true);
  const [assignForm, setAssignForm] = useState({
    user_id: "",
    text: "",
    due_date: "",
    priority: "medium",
  });
  const [assigningTodo, setAssigningTodo] = useState(false);

  const squads = useMemo(() => orgs.filter((o) => o.type === "squad"), [orgs]);

  const refresh = () => {
    fetch(`${apiBase}/admin/group-mappings`, {
      headers: { Authorization: `Bearer ${authToken}` },
    })
      .then((r) => (r.ok ? r.json() : []))
      .then(setMappings)
      .catch(() => {})
      .finally(() => setLoading(false));
  };

  const refreshUsers = () => {
    fetch(`${apiBase}/admin/users`, {
      headers: { Authorization: `Bearer ${authToken}` },
    })
      .then((r) => (r.ok ? r.json() : []))
      .then(setUsers)
      .catch(() => {})
      .finally(() => setUsersLoading(false));
  };

  const refreshAccessGroups = () => {
    fetch(`${apiBase}/admin/access-groups`, {
      headers: { Authorization: `Bearer ${authToken}` },
    })
      .then((r) => (r.ok ? r.json() : []))
      .then(setAccessGroups)
      .catch(() => {})
      .finally(() => setAccessGroupsLoading(false));
  };

  const loadGroupMembers = (groupId) => {
    fetch(`${apiBase}/admin/access-groups/${groupId}/members`, {
      headers: { Authorization: `Bearer ${authToken}` },
    })
      .then((r) => (r.ok ? r.json() : []))
      .then((members) =>
        setGroupMembers((prev) => ({ ...prev, [groupId]: members })),
      )
      .catch(() => {});
  };

  const refreshVocab = () => {
    fetch(`${apiBase}/admin/vocabulary`, {
      headers: { Authorization: `Bearer ${authToken}` },
    })
      .then((r) => (r.ok ? r.json() : []))
      .then(setVocab)
      .catch(() => {})
      .finally(() => setVocabLoading(false));
  };

  useEffect(() => {
    refresh();
    refreshUsers();
    refreshAccessGroups();
    refreshVocab();
    refreshTodoBoard();
    fetch(`${apiBase}/orgs`)
      .then((r) => r.json())
      .then(setOrgs)
      .catch(() => {});
  }, []);

  const handleAddVocab = async () => {
    const term = vocabForm.term.trim();
    if (!term) return;
    setSavingVocab(true);
    try {
      const aliases = vocabForm.aliases
        .split(",")
        .map((a) => a.trim())
        .filter(Boolean);
      const res = await fetch(`${apiBase}/admin/vocabulary`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${authToken}`,
        },
        body: JSON.stringify({ term, aliases }),
      });
      if (res.ok) {
        setVocabForm({ term: "", aliases: "" });
        refreshVocab();
      } else {
        const err = await res.json().catch(() => ({}));
        alert(err.detail || "Failed to add term");
      }
    } catch {
    } finally {
      setSavingVocab(false);
    }
  };

  const handleDeleteVocab = async (id) => {
    await fetch(`${apiBase}/admin/vocabulary/${id}`, {
      method: "DELETE",
      headers: { Authorization: `Bearer ${authToken}` },
    });
    refreshVocab();
  };

  const refreshTodoBoard = () => {
    fetch(`${apiBase}/admin/todos/board`, {
      headers: { Authorization: `Bearer ${authToken}` },
    })
      .then((r) => (r.ok ? r.json() : []))
      .then(setTodoBoard)
      .catch(() => {})
      .finally(() => setTodoBoardLoading(false));
  };

  const handleAssignTodo = async () => {
    if (!assignForm.user_id || !assignForm.text.trim()) return;
    setAssigningTodo(true);
    try {
      await fetch(`${apiBase}/admin/todos/assign`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${authToken}`,
        },
        body: JSON.stringify({
          user_id: assignForm.user_id,
          text: assignForm.text.trim(),
          due_date: assignForm.due_date || null,
          priority: assignForm.priority,
        }),
      });
      setAssignForm({
        user_id: "",
        text: "",
        due_date: "",
        priority: "medium",
      });
      refreshTodoBoard();
    } catch {
    } finally {
      setAssigningTodo(false);
    }
  };

  const handleAdd = async () => {
    if (!form.entra_group_id.trim() || !form.squad_id) return;
    setSaving(true);
    try {
      const res = await fetch(`${apiBase}/admin/group-mappings`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${authToken}`,
        },
        body: JSON.stringify({
          entra_group_id: form.entra_group_id.trim(),
          squad_id: form.squad_id,
          label: form.label.trim() || null,
          default_role: form.default_role.trim() || null,
          default_timezone: form.default_timezone || null,
          default_rhythm: form.default_rhythm || null,
        }),
      });
      if (res.ok) {
        setForm({
          entra_group_id: "",
          squad_id: "",
          label: "",
          default_role: "",
          default_timezone: "",
          default_rhythm: "",
        });
        setAdding(false);
        refresh();
      }
    } catch {
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id) => {
    await fetch(`${apiBase}/admin/group-mappings/${id}`, {
      method: "DELETE",
      headers: { Authorization: `Bearer ${authToken}` },
    });
    refresh();
  };

  const handleAddUser = async () => {
    if (!userForm.email.trim()) return;
    setSavingUser(true);
    try {
      const body = { email: userForm.email.trim() };
      if (userForm.name.trim()) body.name = userForm.name.trim();
      if (userForm.role.trim()) body.role = userForm.role.trim();
      if (userForm.role_tag) body.role_tag = userForm.role_tag;
      if (userForm.squad_ids.length) body.squad_ids = userForm.squad_ids;
      if (userForm.timezone) body.timezone = userForm.timezone;
      if (userForm.rhythm) body.rhythm = userForm.rhythm;
      const res = await fetch(`${apiBase}/admin/users`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${authToken}`,
        },
        body: JSON.stringify(body),
      });
      if (res.ok) {
        const data = await res.json();
        // Add user to access group if selected
        if (userForm.access_group_id && data.id) {
          await fetch(
            `${apiBase}/admin/access-groups/${userForm.access_group_id}/members`,
            {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
                Authorization: `Bearer ${authToken}`,
              },
              body: JSON.stringify({ user_ids: [data.id] }),
            },
          );
        }
        setUserForm({
          email: "",
          name: "",
          role: "",
          role_tag: "",
          squad_ids: [],
          timezone: "",
          rhythm: "",
          access_group_id: "",
        });
        setAddingUser(false);
        refreshUsers();
      }
    } catch {
    } finally {
      setSavingUser(false);
    }
  };

  const [userConfirmDelete, setUserConfirmDelete] = useState(null); // userId or null

  const handleDeleteUser = async (userId) => {
    const res = await fetch(`${apiBase}/admin/users/${userId}`, {
      method: "DELETE",
      headers: { Authorization: `Bearer ${authToken}` },
    });
    setUserConfirmDelete(null);
    if (!res.ok) {
      const err = await res.json().catch(() => ({}));
      alert(err.detail || "Failed to delete user");
      return;
    }
    refreshUsers();
    if (onDataChange) onDataChange();
  };

  const handleAddGroup = async () => {
    if (!groupForm.name.trim()) return;
    setSavingGroup(true);
    try {
      const res = await fetch(`${apiBase}/admin/access-groups`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${authToken}`,
        },
        body: JSON.stringify({
          name: groupForm.name.trim(),
          default_squad_ids: groupForm.default_squad_ids.length
            ? groupForm.default_squad_ids
            : null,
          default_role: groupForm.default_role || null,
          default_timezone: groupForm.default_timezone || null,
          default_rhythm: groupForm.default_rhythm || null,
          permissions: groupForm.permissions,
          is_default: groupForm.is_default,
        }),
      });
      if (res.ok) {
        setGroupForm({
          name: "",
          default_squad_ids: [],
          default_role: "",
          default_timezone: "",
          default_rhythm: "",
          is_default: false,
          permissions: {
            read_scope: "business",
            checkin_scope: "business",
            todos: true,
            wiki_read: true,
            wiki_write: true,
          },
        });
        setAddingGroup(false);
        refreshAccessGroups();
      }
    } catch {
    } finally {
      setSavingGroup(false);
    }
  };

  const [editingGroup, setEditingGroup] = useState(null); // group object being edited, or null
  const [editGroupForm, setEditGroupForm] = useState(null);

  const startEditGroup = (g) => {
    setEditGroupForm({
      name: g.name,
      default_role: g.default_role || "",
      default_timezone: g.default_timezone || "",
      default_rhythm: g.default_rhythm || "",
      default_squad_ids: g.default_squad_ids || [],
      is_default: !!g.is_default,
      permissions: g.permissions || {
        read_scope: "business",
        checkin_scope: "business",
        todos: true,
        wiki_read: true,
        wiki_write: true,
      },
    });
    setEditingGroup(g.id);
  };

  const handleSaveGroup = async (groupId) => {
    if (!editGroupForm) return;
    await fetch(`${apiBase}/admin/access-groups/${groupId}`, {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${authToken}`,
      },
      body: JSON.stringify({
        name: editGroupForm.name,
        default_role: editGroupForm.default_role || null,
        default_timezone: editGroupForm.default_timezone || null,
        default_rhythm: editGroupForm.default_rhythm || null,
        default_squad_ids: editGroupForm.default_squad_ids,
        permissions: editGroupForm.permissions,
        is_default: editGroupForm.is_default,
      }),
    });
    setEditingGroup(null);
    setEditGroupForm(null);
    refreshAccessGroups();
  };

  const handleDeleteGroup = async (groupId) => {
    if (
      !confirm("Delete this access group? Members will lose these permissions.")
    )
      return;
    await fetch(`${apiBase}/admin/access-groups/${groupId}`, {
      method: "DELETE",
      headers: { Authorization: `Bearer ${authToken}` },
    });
    refreshAccessGroups();
  };

  const handleAddMemberToGroup = async (groupId, userId) => {
    await fetch(`${apiBase}/admin/access-groups/${groupId}/members`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${authToken}`,
      },
      body: JSON.stringify({ user_ids: [userId] }),
    });
    loadGroupMembers(groupId);
    refreshAccessGroups();
  };

  const handleRemoveMemberFromGroup = async (groupId, userId) => {
    await fetch(`${apiBase}/admin/access-groups/${groupId}/members/${userId}`, {
      method: "DELETE",
      headers: { Authorization: `Bearer ${authToken}` },
    });
    loadGroupMembers(groupId);
    refreshAccessGroups();
  };

  const renderUsersTab = () => (
    <>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          marginBottom: 20,
        }}
      >
        <div>
          <h2
            style={{
              margin: 0,
              fontSize: 18,
              fontWeight: 700,
              letterSpacing: "-0.3px",
            }}
          >
            Users
          </h2>
          <p style={{ margin: "4px 0 0", fontSize: 13, color: "var(--ink-3)" }}>
            Pre-provision users so they're ready when they log in via SSO. Any
            missing fields will be completed in their setup wizard.
          </p>
        </div>
        <button
          className="btn accent"
          style={{ whiteSpace: "nowrap", flexShrink: 0 }}
          onClick={() => setAddingUser((a) => !a)}
        >
          {addingUser ? "Cancel" : "+ Add user"}
        </button>
      </div>

      {addingUser && (
        <div
          style={{
            background: "var(--bg)",
            border: "1px solid var(--line)",
            borderRadius: 10,
            padding: 16,
            marginBottom: 16,
          }}
        >
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: 10,
              marginBottom: 10,
            }}
          >
            <div>
              <label
                style={{
                  fontSize: 11,
                  fontWeight: 600,
                  color: "var(--ink-4)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                Email *
              </label>
              <input
                value={userForm.email}
                onChange={(e) =>
                  setUserForm((f) => ({ ...f, email: e.target.value }))
                }
                placeholder="jane.smith@centrica.com"
                autoFocus
                style={{
                  width: "100%",
                  fontSize: 12.5,
                  padding: "7px 10px",
                  border: "1px solid var(--line)",
                  borderRadius: 6,
                  background: "var(--surface)",
                  color: "var(--ink-1)",
                }}
              />
            </div>
            <div>
              <label
                style={{
                  fontSize: 11,
                  fontWeight: 600,
                  color: "var(--ink-4)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                Name
              </label>
              <input
                value={userForm.name}
                onChange={(e) =>
                  setUserForm((f) => ({ ...f, name: e.target.value }))
                }
                placeholder="Jane Smith"
                style={{
                  width: "100%",
                  fontSize: 12.5,
                  padding: "7px 10px",
                  border: "1px solid var(--line)",
                  borderRadius: 6,
                  background: "var(--surface)",
                  color: "var(--ink-1)",
                }}
              />
            </div>
          </div>
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr 1fr",
              gap: 10,
              marginBottom: 10,
            }}
          >
            <div>
              <label
                style={{
                  fontSize: 11,
                  fontWeight: 600,
                  color: "var(--ink-4)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                Job title
              </label>
              <input
                value={userForm.role}
                onChange={(e) =>
                  setUserForm((f) => ({ ...f, role: e.target.value }))
                }
                placeholder="e.g. Engineer"
                style={{
                  width: "100%",
                  fontSize: 12.5,
                  padding: "7px 10px",
                  border: "1px solid var(--line)",
                  borderRadius: 6,
                  background: "var(--surface)",
                  color: "var(--ink-1)",
                }}
              />
            </div>
            <div>
              <label
                style={{
                  fontSize: 11,
                  fontWeight: 600,
                  color: "var(--ink-4)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                Role
              </label>
              <select
                value={userForm.role_tag}
                onChange={(e) =>
                  setUserForm((f) => ({ ...f, role_tag: e.target.value }))
                }
                style={{
                  width: "100%",
                  fontSize: 12.5,
                  padding: "7px 10px",
                  border: "1px solid var(--line)",
                  borderRadius: 6,
                  background: "var(--surface)",
                  color: "var(--ink-1)",
                }}
              >
                <option value="">–</option>
                <option value="Developer">Developer</option>
                <option value="Designer">Designer</option>
                <option value="Project Management">Project Management</option>
              </select>
            </div>
            <div>
              <label
                style={{
                  fontSize: 11,
                  fontWeight: 600,
                  color: "var(--ink-4)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                Timezone
              </label>
              <select
                value={userForm.timezone}
                onChange={(e) =>
                  setUserForm((f) => ({ ...f, timezone: e.target.value }))
                }
                style={{
                  width: "100%",
                  fontSize: 12.5,
                  padding: "7px 10px",
                  border: "1px solid var(--line)",
                  borderRadius: 6,
                  background: "var(--surface)",
                  color: "var(--ink-1)",
                }}
              >
                <option value="">–</option>
                {[
                  "Europe/London",
                  "Europe/Dublin",
                  "Europe/Paris",
                  "Europe/Berlin",
                  "Europe/Bucharest",
                  "Asia/Kolkata",
                  "Asia/Singapore",
                  "America/New_York",
                  "America/Chicago",
                  "America/Denver",
                  "America/Los_Angeles",
                  "Australia/Sydney",
                ].map((tz) => (
                  <option key={tz} value={tz}>
                    {tz.replace(/_/g, " ")}
                  </option>
                ))}
              </select>
            </div>
          </div>
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: 10,
              marginBottom: 10,
            }}
          >
            <div>
              <label
                style={{
                  fontSize: 11,
                  fontWeight: 600,
                  color: "var(--ink-4)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                Rhythm
              </label>
              <select
                value={userForm.rhythm}
                onChange={(e) =>
                  setUserForm((f) => ({ ...f, rhythm: e.target.value }))
                }
                style={{
                  width: "100%",
                  fontSize: 12.5,
                  padding: "7px 10px",
                  border: "1px solid var(--line)",
                  borderRadius: 6,
                  background: "var(--surface)",
                  color: "var(--ink-1)",
                }}
              >
                <option value="">–</option>
                <option value="daily">Daily</option>
                <option value="3x">3x per week</option>
                <option value="weekly">Weekly</option>
              </select>
            </div>
            <div>
              <label
                style={{
                  fontSize: 11,
                  fontWeight: 600,
                  color: "var(--ink-4)",
                  display: "block",
                  marginBottom: 4,
                }}
              >
                Squads
              </label>
              <div
                style={{
                  maxHeight: 120,
                  overflowY: "auto",
                  border: "1px solid var(--line)",
                  borderRadius: 6,
                  padding: "4px 8px",
                  background: "var(--surface)",
                }}
              >
                {squads.map((s) => (
                  <label
                    key={s.id}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 6,
                      padding: "3px 0",
                      fontSize: 12,
                      cursor: "pointer",
                      color: "var(--ink-1)",
                    }}
                  >
                    <input
                      type="checkbox"
                      checked={userForm.squad_ids.includes(s.id)}
                      onChange={() =>
                        setUserForm((f) => ({
                          ...f,
                          squad_ids: f.squad_ids.includes(s.id)
                            ? f.squad_ids.filter((x) => x !== s.id)
                            : [...f.squad_ids, s.id],
                        }))
                      }
                      style={{ accentColor: "var(--accent)" }}
                    />
                    {s.name}
                  </label>
                ))}
              </div>
            </div>
          </div>
          <div style={{ marginBottom: 10 }}>
            <label
              style={{
                fontSize: 11,
                fontWeight: 600,
                color: "var(--ink-4)",
                display: "block",
                marginBottom: 4,
              }}
            >
              Access Group
            </label>
            {accessGroups.length === 0 ? (
              <div
                style={{
                  fontSize: 12,
                  color: "var(--ink-3)",
                  padding: "7px 0",
                }}
              >
                No groups yet —{" "}
                <button
                  type="button"
                  onClick={() => {
                    setAddingUser(false);
                    setAdminTab("groups");
                  }}
                  style={{
                    border: 0,
                    background: "transparent",
                    color: "var(--accent)",
                    cursor: "pointer",
                    fontSize: 12,
                    padding: 0,
                    textDecoration: "underline",
                  }}
                >
                  create one
                </button>
              </div>
            ) : (
              <select
                value={userForm.access_group_id}
                onChange={(e) => {
                  const groupId = e.target.value;
                  const group = accessGroups.find((g) => g.id === groupId);
                  setUserForm((f) => ({
                    ...f,
                    access_group_id: groupId,
                    role: f.role || group?.default_role || "",
                    timezone: f.timezone || group?.default_timezone || "",
                    rhythm: f.rhythm || group?.default_rhythm || "",
                    squad_ids: f.squad_ids.length
                      ? f.squad_ids
                      : group?.default_squad_ids || [],
                  }));
                }}
                style={{
                  width: "100%",
                  fontSize: 12.5,
                  padding: "7px 10px",
                  border: "1px solid var(--line)",
                  borderRadius: 6,
                  background: "var(--surface)",
                  color: "var(--ink-1)",
                }}
              >
                <option value="">– None –</option>
                {accessGroups.map((g) => (
                  <option key={g.id} value={g.id}>
                    {g.name}
                  </option>
                ))}
              </select>
            )}
          </div>
          <button
            className="btn accent"
            style={{ fontSize: 12 }}
            onClick={handleAddUser}
            disabled={savingUser || !userForm.email.trim()}
          >
            {savingUser ? "Saving..." : "Create user"}
          </button>
        </div>
      )}

      {usersLoading ? (
        <div
          style={{
            textAlign: "center",
            padding: 40,
            color: "var(--ink-3)",
            fontSize: 13,
          }}
        >
          Loading...
        </div>
      ) : users.length === 0 ? (
        <div
          style={{
            textAlign: "center",
            padding: 40,
            color: "var(--ink-3)",
            fontSize: 13,
            background: "var(--bg)",
            borderRadius: 10,
            border: "1px solid var(--line)",
          }}
        >
          No users yet. Add users so they're ready when they log in.
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          {users.map((u) => {
            const uSquadNames =
              u.squad_ids
                ?.map((sid) => squads.find((s) => s.id === sid)?.name)
                .filter(Boolean) || [];
            return (
              <div
                key={u.id}
                style={{
                  background: "var(--surface)",
                  border: "1px solid var(--line)",
                  borderRadius: 10,
                  padding: "12px 16px",
                  display: "flex",
                  alignItems: "center",
                  gap: 12,
                }}
              >
                <div
                  style={{
                    width: 32,
                    height: 32,
                    borderRadius: "50%",
                    background: "var(--accent-soft)",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    fontSize: 13,
                    fontWeight: 600,
                    color: "var(--accent)",
                    flexShrink: 0,
                  }}
                >
                  {(u.name || u.email)[0].toUpperCase()}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div
                    style={{ display: "flex", alignItems: "center", gap: 8 }}
                  >
                    <span style={{ fontSize: 13, fontWeight: 600 }}>
                      {u.name || u.email.split("@")[0]}
                    </span>
                    {u.needs_onboarding && (
                      <span
                        style={{
                          fontSize: 10,
                          background: "var(--warn-soft)",
                          color: "var(--danger)",
                          padding: "1px 6px",
                          borderRadius: 99,
                          fontWeight: 500,
                        }}
                      >
                        Awaiting registration
                      </span>
                    )}
                  </div>
                  <div style={{ fontSize: 11.5, color: "var(--ink-4)" }}>
                    {u.email}
                  </div>
                  <div
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 8,
                      marginTop: 3,
                    }}
                  >
                    {u.role && (
                      <span style={{ fontSize: 11, color: "var(--ink-3)" }}>
                        {u.role}
                      </span>
                    )}
                    {uSquadNames.length > 0 && (
                      <span style={{ fontSize: 11, color: "var(--accent)" }}>
                        {uSquadNames.join(", ")}
                      </span>
                    )}
                  </div>
                </div>
                <div style={{ position: "relative", flexShrink: 0 }}>
                  <button
                    onClick={() =>
                      setUserConfirmDelete((d) => (d === u.id ? null : u.id))
                    }
                    style={{
                      border: 0,
                      background: "transparent",
                      color: "var(--ink-4)",
                      cursor: "pointer",
                      padding: 4,
                      borderRadius: 4,
                      fontSize: 16,
                      lineHeight: 1,
                    }}
                    title="Remove user"
                  >
                    ×
                  </button>
                  {userConfirmDelete === u.id && (
                    <div
                      style={{
                        position: "absolute",
                        right: 0,
                        top: "100%",
                        marginTop: 4,
                        background: "var(--surface)",
                        border: "1px solid var(--line)",
                        borderRadius: 8,
                        boxShadow: "0 4px 16px rgba(0,0,0,0.1)",
                        zIndex: 100,
                        width: 240,
                        padding: "10px 14px",
                      }}
                    >
                      <p
                        style={{
                          margin: "0 0 10px",
                          fontSize: 12,
                          color: u.needs_onboarding
                            ? "var(--ink-2)"
                            : "var(--danger)",
                        }}
                      >
                        {u.needs_onboarding
                          ? "This user hasn't registered yet — remove them?"
                          : "This will permanently delete this user and all their check-ins, wiki entries, and data. Are you sure?"}
                      </p>
                      <div style={{ display: "flex", gap: 8 }}>
                        <button
                          onClick={() => handleDeleteUser(u.id)}
                          style={{
                            flex: 1,
                            border: 0,
                            background: u.needs_onboarding
                              ? "var(--accent)"
                              : "var(--danger)",
                            color: "#fff",
                            padding: "6px 10px",
                            borderRadius: 6,
                            fontSize: 12,
                            fontWeight: 600,
                            cursor: "pointer",
                          }}
                        >
                          {u.needs_onboarding ? "Yes, remove" : "Yes, delete"}
                        </button>
                        <button
                          onClick={() => setUserConfirmDelete(null)}
                          style={{
                            flex: 1,
                            border: "1px solid var(--line)",
                            background: "var(--surface)",
                            padding: "6px 10px",
                            borderRadius: 6,
                            fontSize: 12,
                            cursor: "pointer",
                            color: "var(--ink-3)",
                          }}
                        >
                          Cancel
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}

      <div
        style={{
          marginTop: 24,
          padding: 16,
          background: "var(--bg)",
          borderRadius: 10,
          border: "1px solid var(--line)",
        }}
      >
        <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 6 }}>
          How user provisioning works
        </div>
        <ol
          style={{
            margin: 0,
            paddingLeft: 18,
            fontSize: 12,
            color: "var(--ink-3)",
            lineHeight: 1.7,
          }}
        >
          <li>
            Add a user by email — fill in as much or as little as you want
          </li>
          <li>
            When they sign in via SSO, their admin-set details are already there
          </li>
          <li>
            Any missing fields (name, squad, etc.) are completed in their setup
            wizard
          </li>
          <li>
            Once Entra ID group permissions are configured, this will be
            replaced by automatic group-based provisioning
          </li>
        </ol>
      </div>
    </>
  );

  const renderMappingsTab = () => (
    <>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          padding: "60px 20px",
          textAlign: "center",
        }}
      >
        <h2
          style={{
            margin: 0,
            fontSize: 18,
            fontWeight: 700,
            letterSpacing: "-0.3px",
          }}
        >
          SSO Group Mappings
        </h2>
        <p style={{ margin: "8px 0 0", fontSize: 13, color: "var(--ink-3)" }}>
          Map Entra security groups to squads for automatic assignment on login.
        </p>
        <span
          style={{
            marginTop: 16,
            padding: "6px 14px",
            fontSize: 12,
            fontWeight: 600,
            borderRadius: 20,
            background: "var(--accent-soft)",
            color: "var(--accent)",
          }}
        >
          Coming soon
        </span>
      </div>
    </>
  );

  const renderTodoBoardTab = () => (
    <>
      <div style={{ marginBottom: 20 }}>
        <h2
          style={{
            margin: 0,
            fontSize: 18,
            fontWeight: 700,
            letterSpacing: "-0.3px",
          }}
        >
          Team To do Board
        </h2>
        <p style={{ margin: "4px 0 0", fontSize: 13, color: "var(--ink-3)" }}>
          All to-dos across the team. Assign to-dos to members below.
        </p>
      </div>

      {/* Assign form */}
      <div
        style={{
          background: "var(--bg)",
          border: "1px solid var(--line)",
          borderRadius: 10,
          padding: 14,
          marginBottom: 20,
        }}
      >
        <div
          style={{
            fontSize: 11,
            fontWeight: 600,
            color: "var(--ink-4)",
            marginBottom: 8,
          }}
        >
          Assign a to-do
        </div>
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "1fr 2fr",
            gap: 8,
            marginBottom: 8,
          }}
        >
          <select
            value={assignForm.user_id}
            onChange={(e) =>
              setAssignForm((f) => ({ ...f, user_id: e.target.value }))
            }
            style={{
              fontSize: 12,
              padding: "6px 8px",
              border: "1px solid var(--line)",
              borderRadius: 6,
              background: "var(--surface)",
            }}
          >
            <option value="">Select user…</option>
            {users.map((u) => (
              <option key={u.id} value={u.id}>
                {u.name || u.email}
              </option>
            ))}
          </select>
          <input
            value={assignForm.text}
            onChange={(e) =>
              setAssignForm((f) => ({ ...f, text: e.target.value }))
            }
            placeholder="To-do text"
            onKeyDown={(e) => {
              if (e.key === "Enter") handleAssignTodo();
            }}
            style={{
              fontSize: 12,
              padding: "6px 8px",
              border: "1px solid var(--line)",
              borderRadius: 6,
              background: "var(--surface)",
            }}
          />
        </div>
        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
          <select
            value={assignForm.priority}
            onChange={(e) =>
              setAssignForm((f) => ({ ...f, priority: e.target.value }))
            }
            style={{
              fontSize: 11,
              padding: "4px 6px",
              border: "1px solid var(--line)",
              borderRadius: 5,
            }}
          >
            <option value="high">High</option>
            <option value="medium">Medium</option>
            <option value="low">Low</option>
          </select>
          <input
            type="date"
            value={assignForm.due_date}
            onChange={(e) =>
              setAssignForm((f) => ({ ...f, due_date: e.target.value }))
            }
            style={{
              fontSize: 11,
              padding: "4px 6px",
              border: "1px solid var(--line)",
              borderRadius: 5,
            }}
          />
          <button
            className="btn accent"
            style={{ fontSize: 12, marginLeft: "auto" }}
            disabled={
              assigningTodo || !assignForm.user_id || !assignForm.text.trim()
            }
            onClick={handleAssignTodo}
          >
            {assigningTodo ? "Assigning…" : "Assign"}
          </button>
        </div>
      </div>

      {/* Board: grouped by user */}
      {todoBoardLoading ? (
        <div style={{ color: "var(--ink-3)", fontSize: 13 }}>Loading…</div>
      ) : todoBoard.length === 0 ? (
        <div style={{ color: "var(--ink-3)", fontSize: 13 }}>
          No to-dos across the team yet.
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {todoBoard.map(({ user: u, todos: ts }) => (
            <div
              key={u.id}
              style={{
                border: "1px solid var(--line)",
                borderRadius: 10,
                overflow: "hidden",
              }}
            >
              <div
                style={{
                  padding: "10px 14px",
                  background: "var(--bg)",
                  borderBottom: "1px solid var(--line)",
                  display: "flex",
                  alignItems: "center",
                  gap: 8,
                }}
              >
                <span style={{ fontSize: 13, fontWeight: 600 }}>{u.name}</span>
                <span style={{ fontSize: 11, color: "var(--ink-3)" }}>
                  {u.role}
                </span>
                <span
                  style={{
                    marginLeft: "auto",
                    fontSize: 11,
                    color: "var(--ink-4)",
                  }}
                >
                  {ts.filter((t) => !t.done).length} open ·{" "}
                  {ts.filter((t) => t.done).length} done
                </span>
              </div>
              <div style={{ padding: "8px 14px" }}>
                {ts.map((t) => {
                  const isOverdue =
                    t.due_date &&
                    !t.done &&
                    new Date(t.due_date) < new Date(new Date().toDateString());
                  const prioColor =
                    t.priority === "high"
                      ? "var(--danger)"
                      : t.priority === "low"
                        ? "var(--ink-4)"
                        : "var(--accent)";
                  return (
                    <div
                      key={t.id}
                      style={{
                        display: "flex",
                        alignItems: "flex-start",
                        gap: 8,
                        padding: "6px 0",
                        fontSize: 13,
                        opacity: t.done ? 0.5 : 1,
                      }}
                    >
                      {t.priority !== "medium" && (
                        <span
                          style={{
                            width: 6,
                            height: 6,
                            borderRadius: "50%",
                            background: prioColor,
                            marginTop: 5,
                            flexShrink: 0,
                          }}
                        />
                      )}
                      <div
                        style={{
                          flex: 1,
                          textDecoration: t.done ? "line-through" : "none",
                          color: isOverdue ? "var(--danger)" : "var(--ink-1)",
                        }}
                      >
                        {t.text}
                        {t.due_date && (
                          <span
                            style={{
                              fontSize: 11,
                              color: isOverdue
                                ? "var(--danger)"
                                : "var(--ink-4)",
                              marginLeft: 6,
                            }}
                          >
                            {isOverdue ? "overdue · " : "due "}
                            {t.due_date}
                          </span>
                        )}
                        {t.assigned_by_name && (
                          <span
                            style={{
                              fontSize: 11,
                              color: "var(--ink-4)",
                              marginLeft: 6,
                            }}
                          >
                            ← {t.assigned_by_name}
                          </span>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      )}
    </>
  );

  const renderVocabTab = () => (
    <>
      <div style={{ marginBottom: 20 }}>
        <h2
          style={{
            margin: 0,
            fontSize: 18,
            fontWeight: 700,
            letterSpacing: "-0.3px",
          }}
        >
          Transcription Vocabulary
        </h2>
        <p style={{ margin: "4px 0 0", fontSize: 13, color: "var(--ink-3)" }}>
          Domain terms the transcription should spell correctly. The{" "}
          <strong>term</strong> is the canonical spelling;{" "}
          <strong>aliases</strong> are common mis-hearings that get
          auto-corrected (e.g. term "CenAI", aliases "Sen AI, Sen Ay Eye").
        </p>
      </div>

      <div
        style={{
          background: "var(--bg)",
          border: "1px solid var(--line)",
          borderRadius: 10,
          padding: 16,
          marginBottom: 16,
          display: "grid",
          gridTemplateColumns: "1fr 2fr auto",
          gap: 10,
          alignItems: "end",
        }}
      >
        <div>
          <label
            style={{
              fontSize: 11,
              fontWeight: 600,
              color: "var(--ink-4)",
              display: "block",
              marginBottom: 4,
            }}
          >
            Term
          </label>
          <input
            value={vocabForm.term}
            onChange={(e) =>
              setVocabForm((f) => ({ ...f, term: e.target.value }))
            }
            placeholder="e.g. CenAI"
            style={{
              width: "100%",
              fontSize: 12.5,
              padding: "7px 10px",
              border: "1px solid var(--line)",
              borderRadius: 6,
              background: "var(--surface)",
              color: "var(--ink-1)",
            }}
          />
        </div>
        <div>
          <label
            style={{
              fontSize: 11,
              fontWeight: 600,
              color: "var(--ink-4)",
              display: "block",
              marginBottom: 4,
            }}
          >
            Aliases (comma-separated)
          </label>
          <input
            value={vocabForm.aliases}
            onChange={(e) =>
              setVocabForm((f) => ({ ...f, aliases: e.target.value }))
            }
            placeholder="e.g. Sen AI, Sen Ay Eye, Cen AI"
            onKeyDown={(e) => {
              if (e.key === "Enter") handleAddVocab();
            }}
            style={{
              width: "100%",
              fontSize: 12.5,
              padding: "7px 10px",
              border: "1px solid var(--line)",
              borderRadius: 6,
              background: "var(--surface)",
              color: "var(--ink-1)",
            }}
          />
        </div>
        <button
          className="btn accent"
          style={{ fontSize: 12 }}
          disabled={savingVocab || !vocabForm.term.trim()}
          onClick={handleAddVocab}
        >
          {savingVocab ? "Adding…" : "+ Add term"}
        </button>
      </div>

      {vocabLoading ? (
        <div style={{ color: "var(--ink-3)", fontSize: 13 }}>Loading…</div>
      ) : vocab.length === 0 ? (
        <div style={{ color: "var(--ink-3)", fontSize: 13 }}>
          No terms yet. Add one above.
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {vocab.map((v) => (
            <div
              key={v.id}
              style={{
                display: "flex",
                alignItems: "center",
                gap: 12,
                background: "var(--surface)",
                border: "1px solid var(--line)",
                borderRadius: 8,
                padding: "10px 14px",
              }}
            >
              <span style={{ fontSize: 13, fontWeight: 600, minWidth: 120 }}>
                {v.term}
              </span>
              <span style={{ flex: 1, fontSize: 12, color: "var(--ink-3)" }}>
                {v.aliases && v.aliases.length ? (
                  v.aliases.join(" · ")
                ) : (
                  <em>no aliases</em>
                )}
              </span>
              <button
                onClick={() => handleDeleteVocab(v.id)}
                style={{
                  border: 0,
                  background: "transparent",
                  color: "var(--ink-4)",
                  cursor: "pointer",
                  padding: 4,
                  fontSize: 16,
                  lineHeight: 1,
                }}
                title="Delete term"
              >
                ×
              </button>
            </div>
          ))}
        </div>
      )}
    </>
  );

  const SCOPE_OPTIONS = [
    "none",
    "squad",
    "team",
    "group",
    "function",
    "business",
  ];
  const SCOPE_LABELS = {
    none: "No permission",
    squad: "Squad",
    team: "Team",
    group: "Group",
    function: "Function",
    business: "Business",
  };

  const renderGroupsTab = () => (
    <>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          marginBottom: 20,
        }}
      >
        <div>
          <h2
            style={{
              margin: 0,
              fontSize: 18,
              fontWeight: 700,
              letterSpacing: "-0.3px",
            }}
          >
            Access Groups
          </h2>
          <p style={{ margin: "4px 0 0", fontSize: 13, color: "var(--ink-3)" }}>
            Bundle permissions and defaults. Users inherit the highest
            permission across all their groups.
          </p>
        </div>
        <button
          className="btn accent"
          style={{ fontSize: 12 }}
          onClick={() => setAddingGroup((a) => !a)}
        >
          {addingGroup ? "Cancel" : "+ Create group"}
        </button>
      </div>

      {addingGroup && (
        <div
          style={{
            background: "var(--bg)",
            border: "1px solid var(--line)",
            borderRadius: 10,
            padding: 16,
            marginBottom: 16,
          }}
        >
          <div style={{ marginBottom: 10 }}>
            <label
              style={{
                fontSize: 11,
                fontWeight: 600,
                color: "var(--ink-4)",
                display: "block",
                marginBottom: 4,
              }}
            >
              Group Name *
            </label>
            <input
              value={groupForm.name}
              onChange={(e) =>
                setGroupForm((f) => ({ ...f, name: e.target.value }))
              }
              placeholder="e.g. Engineering Read-Only"
              autoFocus
              style={{
                width: "100%",
                fontSize: 12.5,
                padding: "7px 10px",
                border: "1px solid var(--line)",
                borderRadius: 6,
                background: "var(--surface)",
                color: "var(--ink-1)",
              }}
            />
          </div>

          <div
            style={{
              fontSize: 11,
              fontWeight: 600,
              color: "var(--ink-4)",
              marginBottom: 6,
            }}
          >
            Permissions
          </div>
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: 10,
              marginBottom: 12,
            }}
          >
            <div>
              <label
                style={{
                  fontSize: 10.5,
                  color: "var(--ink-4)",
                  display: "block",
                  marginBottom: 3,
                }}
              >
                Check-in read scope
              </label>
              <select
                value={groupForm.permissions.read_scope}
                onChange={(e) =>
                  setGroupForm((f) => ({
                    ...f,
                    permissions: {
                      ...f.permissions,
                      read_scope: e.target.value,
                    },
                  }))
                }
                style={{
                  width: "100%",
                  fontSize: 12,
                  padding: "6px 8px",
                  border: "1px solid var(--line)",
                  borderRadius: 6,
                  background: "var(--surface)",
                  color: "var(--ink-1)",
                }}
              >
                {SCOPE_OPTIONS.map((s) => (
                  <option key={s} value={s}>
                    {SCOPE_LABELS[s]}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label
                style={{
                  fontSize: 10.5,
                  color: "var(--ink-4)",
                  display: "block",
                  marginBottom: 3,
                }}
              >
                Check-in write scope
              </label>
              <select
                value={groupForm.permissions.checkin_scope}
                onChange={(e) =>
                  setGroupForm((f) => ({
                    ...f,
                    permissions: {
                      ...f.permissions,
                      checkin_scope: e.target.value,
                    },
                  }))
                }
                style={{
                  width: "100%",
                  fontSize: 12,
                  padding: "6px 8px",
                  border: "1px solid var(--line)",
                  borderRadius: 6,
                  background: "var(--surface)",
                  color: "var(--ink-1)",
                }}
              >
                {SCOPE_OPTIONS.map((s) => (
                  <option key={s} value={s}>
                    {SCOPE_LABELS[s]}
                  </option>
                ))}
              </select>
            </div>
          </div>
          <div style={{ display: "flex", gap: 16, marginBottom: 12 }}>
            <label
              style={{
                display: "flex",
                alignItems: "center",
                gap: 6,
                fontSize: 12,
                cursor: "pointer",
              }}
            >
              <input
                type="checkbox"
                checked={groupForm.permissions.todos}
                onChange={(e) =>
                  setGroupForm((f) => ({
                    ...f,
                    permissions: { ...f.permissions, todos: e.target.checked },
                  }))
                }
                style={{ accentColor: "var(--accent)" }}
              />
              Todos
            </label>
            <label
              style={{
                display: "flex",
                alignItems: "center",
                gap: 6,
                fontSize: 12,
                cursor: "pointer",
              }}
            >
              <input
                type="checkbox"
                checked={groupForm.permissions.wiki_read}
                onChange={(e) =>
                  setGroupForm((f) => ({
                    ...f,
                    permissions: {
                      ...f.permissions,
                      wiki_read: e.target.checked,
                    },
                  }))
                }
                style={{ accentColor: "var(--accent)" }}
              />
              Wiki (read)
            </label>
            <label
              style={{
                display: "flex",
                alignItems: "center",
                gap: 6,
                fontSize: 12,
                cursor: "pointer",
              }}
            >
              <input
                type="checkbox"
                checked={groupForm.permissions.wiki_write}
                onChange={(e) =>
                  setGroupForm((f) => ({
                    ...f,
                    permissions: {
                      ...f.permissions,
                      wiki_write: e.target.checked,
                    },
                  }))
                }
                style={{ accentColor: "var(--accent)" }}
              />
              Wiki (write)
            </label>
          </div>

          <label
            style={{
              display: "flex",
              alignItems: "center",
              gap: 6,
              fontSize: 12,
              cursor: "pointer",
              marginBottom: 12,
            }}
          >
            <input
              type="checkbox"
              checked={groupForm.is_default}
              onChange={(e) =>
                setGroupForm((f) => ({ ...f, is_default: e.target.checked }))
              }
              style={{ accentColor: "var(--accent)" }}
            />
            Default group{" "}
            <span style={{ color: "var(--ink-4)" }}>
              — new self-registered users join this group (only one allowed)
            </span>
          </label>

          <div
            style={{
              fontSize: 11,
              fontWeight: 600,
              color: "var(--ink-4)",
              marginBottom: 6,
            }}
          >
            Defaults (applied when user is added - optional)
          </div>
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr 1fr",
              gap: 10,
              marginBottom: 10,
            }}
          >
            <div>
              <label
                style={{
                  fontSize: 10.5,
                  color: "var(--ink-4)",
                  display: "block",
                  marginBottom: 3,
                }}
              >
                Job title
              </label>
              <input
                value={groupForm.default_role}
                onChange={(e) =>
                  setGroupForm((f) => ({ ...f, default_role: e.target.value }))
                }
                placeholder="e.g. Engineer"
                style={{
                  width: "100%",
                  fontSize: 12,
                  padding: "6px 8px",
                  border: "1px solid var(--line)",
                  borderRadius: 6,
                  background: "var(--surface)",
                  color: "var(--ink-1)",
                }}
              />
            </div>
            <div>
              <label
                style={{
                  fontSize: 10.5,
                  color: "var(--ink-4)",
                  display: "block",
                  marginBottom: 3,
                }}
              >
                Timezone
              </label>
              <select
                value={groupForm.default_timezone}
                onChange={(e) =>
                  setGroupForm((f) => ({
                    ...f,
                    default_timezone: e.target.value,
                  }))
                }
                style={{
                  width: "100%",
                  fontSize: 12,
                  padding: "6px 8px",
                  border: "1px solid var(--line)",
                  borderRadius: 6,
                  background: "var(--surface)",
                  color: "var(--ink-1)",
                }}
              >
                <option value="">–</option>
                {[
                  "Europe/London",
                  "Europe/Dublin",
                  "Europe/Paris",
                  "Europe/Berlin",
                  "Asia/Kolkata",
                  "America/New_York",
                  "America/Los_Angeles",
                ].map((tz) => (
                  <option key={tz} value={tz}>
                    {tz.replace(/_/g, " ")}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label
                style={{
                  fontSize: 10.5,
                  color: "var(--ink-4)",
                  display: "block",
                  marginBottom: 3,
                }}
              >
                Rhythm
              </label>
              <select
                value={groupForm.default_rhythm}
                onChange={(e) =>
                  setGroupForm((f) => ({
                    ...f,
                    default_rhythm: e.target.value,
                  }))
                }
                style={{
                  width: "100%",
                  fontSize: 12,
                  padding: "6px 8px",
                  border: "1px solid var(--line)",
                  borderRadius: 6,
                  background: "var(--surface)",
                  color: "var(--ink-1)",
                }}
              >
                <option value="">–</option>
                <option value="daily">Daily</option>
                <option value="3x">3x per week</option>
                <option value="weekly">Weekly</option>
              </select>
            </div>
          </div>
          <div style={{ marginBottom: 12 }}>
            <label
              style={{
                fontSize: 10.5,
                color: "var(--ink-4)",
                display: "block",
                marginBottom: 3,
              }}
            >
              Default Squads
            </label>
            <div
              style={{
                maxHeight: 100,
                overflowY: "auto",
                border: "1px solid var(--line)",
                borderRadius: 6,
                padding: "4px 8px",
                background: "var(--surface)",
              }}
            >
              {squads.map((s) => (
                <label
                  key={s.id}
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 6,
                    padding: "2px 0",
                    fontSize: 11.5,
                    cursor: "pointer",
                    color: "var(--ink-1)",
                  }}
                >
                  <input
                    type="checkbox"
                    checked={groupForm.default_squad_ids.includes(s.id)}
                    onChange={() =>
                      setGroupForm((f) => ({
                        ...f,
                        default_squad_ids: f.default_squad_ids.includes(s.id)
                          ? f.default_squad_ids.filter((x) => x !== s.id)
                          : [...f.default_squad_ids, s.id],
                      }))
                    }
                    style={{ accentColor: "var(--accent)" }}
                  />
                  {s.name}
                </label>
              ))}
            </div>
          </div>
          <button
            className="btn accent"
            style={{ fontSize: 12 }}
            onClick={handleAddGroup}
            disabled={savingGroup || !groupForm.name.trim()}
          >
            {savingGroup ? "Creating..." : "Create group"}
          </button>
        </div>
      )}

      {accessGroupsLoading ? (
        <div
          style={{
            textAlign: "center",
            padding: 40,
            color: "var(--ink-3)",
            fontSize: 13,
          }}
        >
          Loading...
        </div>
      ) : accessGroups.length === 0 ? (
        <div
          style={{
            textAlign: "center",
            padding: 40,
            color: "var(--ink-3)",
            fontSize: 13,
            background: "var(--bg)",
            borderRadius: 10,
            border: "1px solid var(--line)",
          }}
        >
          No access groups yet. Create one to manage permissions for sets of
          users.
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {accessGroups.map((g) => {
            const isExpanded = expandedGroup === g.id;
            const members = groupMembers[g.id] || [];
            const p = g.permissions || {};
            return (
              <div
                key={g.id}
                style={{
                  background: "var(--surface)",
                  border: "1px solid var(--line)",
                  borderRadius: 10,
                  overflow: "hidden",
                }}
              >
                <div
                  style={{
                    padding: "14px 16px",
                    display: "flex",
                    alignItems: "center",
                    gap: 12,
                    cursor: "pointer",
                  }}
                  onClick={() => {
                    if (isExpanded) {
                      setExpandedGroup(null);
                    } else {
                      setExpandedGroup(g.id);
                      loadGroupMembers(g.id);
                    }
                  }}
                >
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div
                      style={{
                        display: "flex",
                        alignItems: "center",
                        gap: 8,
                        marginBottom: 2,
                      }}
                    >
                      <span style={{ fontSize: 13, fontWeight: 600 }}>
                        {g.name}
                      </span>
                      <span
                        style={{
                          fontSize: 11,
                          background: "var(--accent-soft)",
                          color: "var(--accent)",
                          padding: "1px 8px",
                          borderRadius: 99,
                          fontWeight: 500,
                        }}
                      >
                        {g.member_count} member{g.member_count !== 1 ? "s" : ""}
                      </span>
                      {g.is_default && (
                        <span
                          style={{
                            fontSize: 11,
                            background: "var(--ok-soft)",
                            color: "var(--ok)",
                            padding: "1px 8px",
                            borderRadius: 99,
                            fontWeight: 500,
                          }}
                        >
                          Default
                        </span>
                      )}
                    </div>
                    <div style={{ fontSize: 11, color: "var(--ink-3)" }}>
                      Read:{" "}
                      {SCOPE_LABELS[p.read_scope] || p.read_scope || "Business"}{" "}
                      · Write:{" "}
                      {SCOPE_LABELS[p.checkin_scope] ||
                        p.checkin_scope ||
                        "Business"}
                      {p.todos !== false && " · Todos"}
                      {p.wiki_read !== false && " · Wiki"}
                      {p.wiki_write !== false && " (rw)"}
                    </div>
                  </div>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      startEditGroup(g);
                    }}
                    style={{
                      border: 0,
                      background: "transparent",
                      color: "var(--ink-4)",
                      cursor: "pointer",
                      padding: 4,
                      fontSize: 13,
                      lineHeight: 1,
                    }}
                    title="Edit group"
                  >
                    ✎
                  </button>
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      handleDeleteGroup(g.id);
                    }}
                    style={{
                      border: 0,
                      background: "transparent",
                      color: "var(--ink-4)",
                      cursor: "pointer",
                      padding: 4,
                      fontSize: 16,
                      lineHeight: 1,
                    }}
                    title="Delete group"
                  >
                    ×
                  </button>
                  <span
                    style={{
                      fontSize: 18,
                      color: "var(--ink-3)",
                      transform: isExpanded ? "rotate(180deg)" : "rotate(0)",
                      transition: "transform 150ms",
                      display: "inline-block",
                    }}
                  >
                    ▾
                  </span>
                </div>

                {editingGroup === g.id && editGroupForm && (
                  <div
                    style={{
                      padding: "14px 16px",
                      borderTop: "1px solid var(--line)",
                      background: "var(--bg)",
                    }}
                  >
                    <div style={{ marginBottom: 10 }}>
                      <label
                        style={{
                          fontSize: 10.5,
                          fontWeight: 600,
                          color: "var(--ink-4)",
                          display: "block",
                          marginBottom: 3,
                        }}
                      >
                        Group Name
                      </label>
                      <input
                        value={editGroupForm.name}
                        onChange={(e) =>
                          setEditGroupForm((f) => ({
                            ...f,
                            name: e.target.value,
                          }))
                        }
                        style={{
                          width: "100%",
                          fontSize: 12.5,
                          padding: "7px 10px",
                          border: "1px solid var(--line)",
                          borderRadius: 6,
                          background: "var(--surface)",
                        }}
                      />
                    </div>
                    <div
                      style={{
                        fontSize: 11,
                        fontWeight: 600,
                        color: "var(--ink-4)",
                        marginBottom: 6,
                      }}
                    >
                      Permissions
                    </div>
                    <div
                      style={{
                        display: "grid",
                        gridTemplateColumns: "1fr 1fr",
                        gap: 8,
                        marginBottom: 12,
                      }}
                    >
                      <div>
                        <label
                          style={{ fontSize: 10.5, color: "var(--ink-4)" }}
                        >
                          Check-in read scope
                        </label>
                        <select
                          value={editGroupForm.permissions.read_scope}
                          onChange={(e) =>
                            setEditGroupForm((f) => ({
                              ...f,
                              permissions: {
                                ...f.permissions,
                                read_scope: e.target.value,
                              },
                            }))
                          }
                          style={{
                            width: "100%",
                            fontSize: 12,
                            padding: "5px 8px",
                            border: "1px solid var(--line)",
                            borderRadius: 6,
                            background: "var(--surface)",
                          }}
                        >
                          {SCOPE_OPTIONS.map((s) => (
                            <option key={s} value={s}>
                              {SCOPE_LABELS[s]}
                            </option>
                          ))}
                        </select>
                      </div>
                      <div>
                        <label
                          style={{ fontSize: 10.5, color: "var(--ink-4)" }}
                        >
                          Check-in write scope
                        </label>
                        <select
                          value={editGroupForm.permissions.checkin_scope}
                          onChange={(e) =>
                            setEditGroupForm((f) => ({
                              ...f,
                              permissions: {
                                ...f.permissions,
                                checkin_scope: e.target.value,
                              },
                            }))
                          }
                          style={{
                            width: "100%",
                            fontSize: 12,
                            padding: "5px 8px",
                            border: "1px solid var(--line)",
                            borderRadius: 6,
                            background: "var(--surface)",
                          }}
                        >
                          {SCOPE_OPTIONS.map((s) => (
                            <option key={s} value={s}>
                              {SCOPE_LABELS[s]}
                            </option>
                          ))}
                        </select>
                      </div>
                    </div>
                    <div style={{ display: "flex", gap: 12, marginBottom: 12 }}>
                      <label
                        style={{
                          fontSize: 12,
                          display: "flex",
                          alignItems: "center",
                          gap: 4,
                          cursor: "pointer",
                        }}
                      >
                        <input
                          type="checkbox"
                          checked={editGroupForm.permissions.todos !== false}
                          onChange={(e) =>
                            setEditGroupForm((f) => ({
                              ...f,
                              permissions: {
                                ...f.permissions,
                                todos: e.target.checked,
                              },
                            }))
                          }
                          style={{ accentColor: "var(--accent)" }}
                        />{" "}
                        Todos
                      </label>
                      <label
                        style={{
                          fontSize: 12,
                          display: "flex",
                          alignItems: "center",
                          gap: 4,
                          cursor: "pointer",
                        }}
                      >
                        <input
                          type="checkbox"
                          checked={
                            editGroupForm.permissions.wiki_read !== false
                          }
                          onChange={(e) =>
                            setEditGroupForm((f) => ({
                              ...f,
                              permissions: {
                                ...f.permissions,
                                wiki_read: e.target.checked,
                              },
                            }))
                          }
                          style={{ accentColor: "var(--accent)" }}
                        />{" "}
                        Wiki (read)
                      </label>
                      <label
                        style={{
                          fontSize: 12,
                          display: "flex",
                          alignItems: "center",
                          gap: 4,
                          cursor: "pointer",
                        }}
                      >
                        <input
                          type="checkbox"
                          checked={
                            editGroupForm.permissions.wiki_write !== false
                          }
                          onChange={(e) =>
                            setEditGroupForm((f) => ({
                              ...f,
                              permissions: {
                                ...f.permissions,
                                wiki_write: e.target.checked,
                              },
                            }))
                          }
                          style={{ accentColor: "var(--accent)" }}
                        />{" "}
                        Wiki (write)
                      </label>
                    </div>
                    <label
                      style={{
                        fontSize: 12,
                        display: "flex",
                        alignItems: "center",
                        gap: 4,
                        cursor: "pointer",
                        marginBottom: 12,
                      }}
                    >
                      <input
                        type="checkbox"
                        checked={!!editGroupForm.is_default}
                        onChange={(e) =>
                          setEditGroupForm((f) => ({
                            ...f,
                            is_default: e.target.checked,
                          }))
                        }
                        style={{ accentColor: "var(--accent)" }}
                      />
                      Default group{" "}
                      <span style={{ color: "var(--ink-4)" }}>
                        — new self-registered users join this group
                      </span>
                    </label>
                    <div
                      style={{
                        fontSize: 11,
                        fontWeight: 600,
                        color: "var(--ink-4)",
                        marginBottom: 6,
                      }}
                    >
                      Defaults
                    </div>
                    <div
                      style={{
                        display: "grid",
                        gridTemplateColumns: "1fr 1fr 1fr",
                        gap: 8,
                        marginBottom: 12,
                      }}
                    >
                      <div>
                        <label
                          style={{ fontSize: 10.5, color: "var(--ink-4)" }}
                        >
                          Job title
                        </label>
                        <input
                          value={editGroupForm.default_role}
                          onChange={(e) =>
                            setEditGroupForm((f) => ({
                              ...f,
                              default_role: e.target.value,
                            }))
                          }
                          placeholder="e.g. Engineer"
                          style={{
                            width: "100%",
                            fontSize: 12,
                            padding: "5px 8px",
                            border: "1px solid var(--line)",
                            borderRadius: 6,
                            background: "var(--surface)",
                          }}
                        />
                      </div>
                      <div>
                        <label
                          style={{ fontSize: 10.5, color: "var(--ink-4)" }}
                        >
                          Timezone
                        </label>
                        <select
                          value={editGroupForm.default_timezone}
                          onChange={(e) =>
                            setEditGroupForm((f) => ({
                              ...f,
                              default_timezone: e.target.value,
                            }))
                          }
                          style={{
                            width: "100%",
                            fontSize: 12,
                            padding: "5px 8px",
                            border: "1px solid var(--line)",
                            borderRadius: 6,
                            background: "var(--surface)",
                          }}
                        >
                          <option value="">–</option>
                          {[
                            "Europe/London",
                            "Europe/Dublin",
                            "Europe/Paris",
                            "Europe/Berlin",
                            "Asia/Kolkata",
                            "America/New_York",
                            "America/Los_Angeles",
                          ].map((tz) => (
                            <option key={tz} value={tz}>
                              {tz.replace(/_/g, " ")}
                            </option>
                          ))}
                        </select>
                      </div>
                      <div>
                        <label
                          style={{ fontSize: 10.5, color: "var(--ink-4)" }}
                        >
                          Rhythm
                        </label>
                        <select
                          value={editGroupForm.default_rhythm}
                          onChange={(e) =>
                            setEditGroupForm((f) => ({
                              ...f,
                              default_rhythm: e.target.value,
                            }))
                          }
                          style={{
                            width: "100%",
                            fontSize: 12,
                            padding: "5px 8px",
                            border: "1px solid var(--line)",
                            borderRadius: 6,
                            background: "var(--surface)",
                          }}
                        >
                          <option value="">–</option>
                          <option value="daily">Daily</option>
                          <option value="3x">3x per week</option>
                          <option value="weekly">Weekly</option>
                        </select>
                      </div>
                    </div>
                    <div style={{ display: "flex", gap: 8 }}>
                      <button
                        className="btn accent"
                        style={{ fontSize: 12 }}
                        onClick={() => handleSaveGroup(g.id)}
                      >
                        Save changes
                      </button>
                      <button
                        className="btn"
                        style={{ fontSize: 12 }}
                        onClick={() => {
                          setEditingGroup(null);
                          setEditGroupForm(null);
                        }}
                      >
                        Cancel
                      </button>
                    </div>
                  </div>
                )}

                {isExpanded && editingGroup !== g.id && (
                  <div
                    style={{
                      padding: "0 16px 14px",
                      borderTop: "1px solid var(--line)",
                    }}
                  >
                    <div
                      style={{
                        fontSize: 11,
                        fontWeight: 600,
                        color: "var(--ink-4)",
                        marginTop: 12,
                        marginBottom: 8,
                      }}
                    >
                      MEMBERS
                    </div>
                    {members.length === 0 ? (
                      <div
                        style={{
                          fontSize: 12,
                          color: "var(--ink-3)",
                          fontStyle: "italic",
                          marginBottom: 8,
                        }}
                      >
                        No members yet
                      </div>
                    ) : (
                      <div
                        style={{
                          display: "flex",
                          flexDirection: "column",
                          gap: 4,
                          marginBottom: 8,
                        }}
                      >
                        {members.map((m) => (
                          <div
                            key={m.id}
                            style={{
                              display: "flex",
                              alignItems: "center",
                              gap: 8,
                              fontSize: 12,
                            }}
                          >
                            <span style={{ flex: 1 }}>
                              {m.name}{" "}
                              <span style={{ color: "var(--ink-4)" }}>
                                ({m.email})
                              </span>
                            </span>
                            <button
                              onClick={() =>
                                handleRemoveMemberFromGroup(g.id, m.id)
                              }
                              style={{
                                border: 0,
                                background: "transparent",
                                color: "var(--ink-4)",
                                cursor: "pointer",
                                fontSize: 14,
                                lineHeight: 1,
                              }}
                            >
                              ×
                            </button>
                          </div>
                        ))}
                      </div>
                    )}
                    <div
                      style={{
                        fontSize: 11,
                        fontWeight: 600,
                        color: "var(--ink-4)",
                        marginBottom: 6,
                      }}
                    >
                      ADD MEMBER
                    </div>
                    <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
                      {users
                        .filter((u) => !members.find((m) => m.id === u.id))
                        .slice(0, 20)
                        .map((u) => (
                          <button
                            key={u.id}
                            onClick={() => handleAddMemberToGroup(g.id, u.id)}
                            style={{
                              fontSize: 11,
                              padding: "3px 8px",
                              borderRadius: 99,
                              border: "1px solid var(--line)",
                              background: "var(--bg)",
                              color: "var(--ink-2)",
                              cursor: "pointer",
                            }}
                          >
                            {u.name || u.email.split("@")[0]}
                          </button>
                        ))}
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </>
  );

  return (
    <div style={{ maxWidth: 720, margin: "0 auto", padding: "24px 0" }}>
      <div
        style={{
          display: "flex",
          gap: 0,
          borderBottom: "1px solid var(--line)",
          marginBottom: 20,
        }}
      >
        <button
          onClick={() => setAdminTab("users")}
          style={{
            padding: "10px 20px",
            fontSize: 13,
            fontWeight: adminTab === "users" ? 600 : 400,
            color: adminTab === "users" ? "var(--accent)" : "var(--ink-3)",
            background: "transparent",
            border: 0,
            borderBottom:
              adminTab === "users"
                ? "2px solid var(--accent)"
                : "2px solid transparent",
            cursor: "pointer",
            marginBottom: -1,
          }}
        >
          Users
        </button>
        <button
          onClick={() => setAdminTab("groups")}
          style={{
            padding: "10px 20px",
            fontSize: 13,
            fontWeight: adminTab === "groups" ? 600 : 400,
            color: adminTab === "groups" ? "var(--accent)" : "var(--ink-3)",
            background: "transparent",
            border: 0,
            borderBottom:
              adminTab === "groups"
                ? "2px solid var(--accent)"
                : "2px solid transparent",
            cursor: "pointer",
            marginBottom: -1,
          }}
        >
          Access Groups
        </button>
        <button
          onClick={() => setAdminTab("mappings")}
          style={{
            padding: "10px 20px",
            fontSize: 13,
            fontWeight: adminTab === "mappings" ? 600 : 400,
            color: adminTab === "mappings" ? "var(--accent)" : "var(--ink-3)",
            background: "transparent",
            border: 0,
            borderBottom:
              adminTab === "mappings"
                ? "2px solid var(--accent)"
                : "2px solid transparent",
            cursor: "pointer",
            marginBottom: -1,
          }}
        >
          SSO Mappings
        </button>
        <button
          onClick={() => setAdminTab("vocabulary")}
          style={{
            padding: "10px 20px",
            fontSize: 13,
            fontWeight: adminTab === "vocabulary" ? 600 : 400,
            color: adminTab === "vocabulary" ? "var(--accent)" : "var(--ink-3)",
            background: "transparent",
            border: 0,
            borderBottom:
              adminTab === "vocabulary"
                ? "2px solid var(--accent)"
                : "2px solid transparent",
            cursor: "pointer",
            marginBottom: -1,
          }}
        >
          Vocabulary
        </button>
        <button
          onClick={() => setAdminTab("todoboard")}
          style={{
            padding: "10px 20px",
            fontSize: 13,
            fontWeight: adminTab === "todoboard" ? 600 : 400,
            color: adminTab === "todoboard" ? "var(--accent)" : "var(--ink-3)",
            background: "transparent",
            border: 0,
            borderBottom:
              adminTab === "todoboard"
                ? "2px solid var(--accent)"
                : "2px solid transparent",
            cursor: "pointer",
            marginBottom: -1,
          }}
        >
          To do Board
        </button>
      </div>
      {adminTab === "users"
        ? renderUsersTab()
        : adminTab === "groups"
          ? renderGroupsTab()
          : adminTab === "vocabulary"
            ? renderVocabTab()
            : adminTab === "todoboard"
              ? renderTodoBoardTab()
              : renderMappingsTab()}
    </div>
  );
}

window.WikiView = WikiView;
window.PersonView = PersonView;
window.HistoryView = HistoryView;
window.AdminView = AdminView;
