// Recommender side: inbox + drafting workspace
(function () {
const { useState, useRef, useMemo, useEffect } = React;

function Recommender() {
  const store = window.useLAStore();
  const [openId, setOpenId] = useState(null);
  const submission = store.submissions().find((s) => s.id === openId);

  if (!openId || !submission?.evidence) {
    return <Inbox onOpen={setOpenId} />;
  }
  return <Drafting key={openId} submission={submission} onBack={() => setOpenId(null)} />;
}

/* ============================================================
   INBOX
   ============================================================ */
function Inbox({ onOpen }) {
  const statusLabel = { new: "New", drafting: "Drafting", sent: "Sent", declined: "Declined" };
  const statusDot = { new: "var(--accent)", drafting: "var(--warn)", sent: "var(--good)", declined: "var(--muted)" };
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [inviteOpen, setInviteOpen] = useState(false);
  const [copiedCode, setCopiedCode] = useState(null);
  const store = window.useLAStore();
  const subs = store.submissions();
  const pol = store.policy;
  const setPol = (patch) => window.LAStore.setPolicy(patch);
  return (
    <div className="page-wrap">
      <header style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 28 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Letter Queue · Fall 2026</div>
          <h1 style={{ fontSize: 36, letterSpacing: "-0.015em" }}>Requests for your letter</h1>
          <p style={{ color: "var(--ink-3)", fontSize: 15, marginTop: 8 }}>Each request is a structured evidence packet from the student.</p>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button className={"btn" + (settingsOpen ? " btn-primary" : "")} onClick={() => { setSettingsOpen((v) => !v); setInviteOpen(false); }}>Settings</button>
          <button className={"btn btn-primary"} onClick={() => { setInviteOpen((v) => !v); setSettingsOpen(false); }}>+ Invite a student</button>
        </div>
      </header>

      {inviteOpen && (
        <div className="card" style={{ padding: "20px 24px", marginBottom: 20 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 6 }}>
            <div className="label" style={{ marginBottom: 0 }}>Invite codes</div>
            <button className="btn btn-sm btn-accent" onClick={() => window.LAStore.addInvite()}>+ New code</button>
          </div>
          <div className="help" style={{ marginBottom: 14 }}>Students need a code (or the link that carries it) to open the request form. Revoke a code to stop new requests from it — packets already sent are unaffected.</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {store.invites.map((inv) => {
              const link = location.origin + location.pathname + "?invite=" + inv.code;
              return (
                <div key={inv.code} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 12px", background: "var(--surface-3)", border: "1px solid var(--line)", borderRadius: "var(--r)" }}>
                  <span style={{ fontFamily: "var(--mono)", fontSize: 14, letterSpacing: "0.1em", color: "var(--ink)" }}>{inv.code}</span>
                  {inv.note && <span style={{ fontSize: 12, color: "var(--muted)" }}>{inv.note}</span>}
                  <span style={{ fontSize: 11.5, color: "var(--subtle)", marginLeft: "auto" }}>created {inv.created}</span>
                  <button className="btn btn-sm" onClick={async () => { try { await navigator.clipboard.writeText(link); } catch {} setCopiedCode(inv.code); setTimeout(() => setCopiedCode(null), 1600); }}>{copiedCode === inv.code ? "Copied ✓" : "Copy link"}</button>
                  <button className="btn btn-ghost btn-sm" onClick={() => window.LAStore.revokeInvite(inv.code)} style={{ color: "var(--muted)" }}>Revoke</button>
                </div>
              );
            })}
            {store.invites.length === 0 && <div style={{ padding: "14px 4px", color: "var(--muted)", fontSize: 13 }}>No active codes — create one to invite students.</div>}
          </div>
        </div>
      )}

      {settingsOpen && (
        <div className="card" style={{ padding: "20px 24px", marginBottom: 20, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 28 }}>
          <div>
            <div className="label" style={{ marginBottom: 6 }}>Submission window</div>
            <div style={{ fontSize: 13.5, color: "var(--ink-2)", display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
              Students must submit their packet at least
              <input className="input" type="number" min="1" max="120" style={{ width: 64, padding: "4px 8px", fontSize: 13 }} value={pol.amount} onChange={(e) => setPol({ amount: Math.max(1, Number(e.target.value) || 1) })} />
              <select className="input" style={{ width: "auto", padding: "4px 8px", fontSize: 13 }} value={pol.unit} onChange={(e) => setPol({ unit: e.target.value })}>
                <option value="days">days</option>
                <option value="weeks">weeks</option>
              </select>
              before the application deadline.
            </div>
            <div className="help" style={{ marginTop: 6 }}>Requests arriving inside the window are flagged as late — you decide whether to draft anyway or decline. Students see the cutoff before they send.</div>
          </div>
          <div>
            <div className="label" style={{ marginBottom: 6 }}>Reminders</div>
            <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13.5, color: "var(--ink-2)", cursor: "pointer" }}>
              <input type="checkbox" checked={pol.remindNew} onChange={(e) => setPol({ remindNew: e.target.checked })} />
              Email me when a new packet arrives
            </label>
            <div style={{ fontSize: 13.5, color: "var(--ink-2)", display: "flex", alignItems: "center", gap: 8, marginTop: 8, flexWrap: "wrap" }}>
              Remind me
              <select className="input" style={{ width: "auto", padding: "4px 8px", fontSize: 13 }} value={pol.remindDays} onChange={(e) => setPol({ remindDays: Number(e.target.value) })}>
                {[3, 5, 7, 14].map((d) => <option key={d} value={d}>{d} days</option>)}
              </select>
              before each unsent letter's deadline.
            </div>
          </div>
        </div>
      )}

      <div className="card" style={{ overflow: "hidden" }}>
        <div className="inbox-grid" style={{ padding: "12px 20px", borderBottom: "1px solid var(--line)", background: "var(--bg)", fontSize: 11, fontWeight: 500, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--muted)" }}>
          <div>Student</div>
          <div>Letter for</div>
          <div className="inbox-hide-md">Deadline</div>
          <div className="inbox-hide-md">Status</div>
          <div></div>
        </div>
        {subs.map((s, i) => (
          <button
            key={s.id}
            onClick={() => onOpen(s.id)}
            disabled={!s.evidence}
            className="inbox-grid"
            style={{
              padding: "16px 20px",
              borderBottom: i < subs.length - 1 ? "1px solid var(--line-soft)" : "none",
              cursor: s.evidence ? "pointer" : "default",
              transition: "background 0.1s",
            }}
            onMouseEnter={(e) => s.evidence && (e.currentTarget.style.background = "var(--bg)")}
            onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}
          >
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <div style={{ width: 34, height: 34, borderRadius: "50%", background: "var(--accent-tint)", color: "var(--accent)", display: "grid", placeItems: "center", fontFamily: "var(--serif)", fontSize: 13, fontWeight: 500 }}>{s.headshot}</div>
              <div>
                <div style={{ fontFamily: "var(--serif)", fontSize: 16 }}>{s.student}</div>
              </div>
            </div>
            <div style={{ fontSize: 13.5, color: "var(--ink-2)" }}>{s.purpose}</div>
            <div className="inbox-hide-md" style={{ fontSize: 13, color: "var(--ink-3)", display: "flex", alignItems: "center", gap: 8 }}>{s.deadline}{s.status !== "sent" && s.status !== "declined" && window.LAStore.isLate(s.deadlineISO || s.deadline) && <span className="tag-late">inside window</span>}</div>
            <div className="inbox-hide-md" style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, color: "var(--ink-2)" }}>
              <span style={{ width: 7, height: 7, borderRadius: "50%", background: statusDot[s.status] }} />
              {statusLabel[s.status]}
            </div>
            <div style={{ textAlign: "right", color: "var(--muted)", fontSize: 14 }}>
              {s.evidence ? "→" : ""}
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

/* ============================================================
   DRAFTING WORKSPACE
   ============================================================ */
function Drafting({ submission, onBack }) {
  const [hoverIds, setHoverIds] = useState([]); // array of evidence ids currently highlighted
  const [aiLevel, setAiLevel] = useState("full"); // full | outline | bullets | none
  const [draftState, setDraftState] = useState(submission.draft || null);
  const [notes, setNotesState] = useState(submission.notes || []);
  const [showAll, setShowAll] = useState(true);
  const [regeneratingId, setRegeneratingId] = useState(null);
  const [regenError, setRegenError] = useState(null);
  const [generating, setGenerating] = useState(false);
  const [copied, setCopied] = useState(false);
  const [resumeOpen, setResumeOpen] = useState(false);
  const [pinnedExtracts, setPinnedExtractsState] = useState(submission.pinnedExtracts || (submission.id === "maya" ? ["r-anthropic", "r-prize"] : []));
  const saveDraft = (d) => { setDraftState(d); window.LAStore.patch(submission.id, { draft: d }); };
  const setNotes = (n) => { setNotesState(n); window.LAStore.patch(submission.id, { notes: n }); };
  const setPinnedExtracts = (v) => setPinnedExtractsState((prev) => { const next = typeof v === "function" ? v(prev) : v; window.LAStore.patch(submission.id, { pinnedExtracts: next }); return next; });
  const [activePane, setActivePane] = useState("draft"); // for mobile tab nav
  const [detailsOpen, setDetailsOpen] = useState(false);

  // Pieces of evidence used in the draft (for the "used" indicator + filter)
  const usedIds = useMemo(() => {
    const set = new Set();
    if (draftState) draftState.paragraphs.forEach((p) => p.sentences.forEach((s) => (s.cites || []).forEach((c) => set.add(c))));
    return set;
  }, [draftState]);

  const allEvidence = submission.evidence;
  const totalCount = Object.values(allEvidence).reduce((n, arr) => n + arr.length, 0);

  const evidenceById = useMemo(() => {
    const m = {};
    Object.values(allEvidence).forEach((arr) => arr.forEach((e) => (m[e.id] = e)));
    return m;
  }, [allEvidence]);

  useEffect(() => { window.__evidenceById = { ...(window.__evidenceById || {}), ...evidenceById }; }, [evidenceById]);

  const setHover = (ids) => setHoverIds(ids);
  const isHl = (id) => hoverIds.includes(id);

  const buildEvidenceList = () => {
    const evidenceList = [];
    Object.entries(allEvidence).forEach(([section, items]) => {
      items.forEach((it) => evidenceList.push({ id: it.id, section, label: it.label, text: it.text }));
    });
    if (submission.resumeContent) {
      submission.resumeContent.extracts
        .filter((e) => pinnedExtracts.includes(e.id))
        .forEach((e) => evidenceList.push({ id: e.id, section: "resume", label: e.label, text: e.snippet }));
    }
    notes.forEach((n) => evidenceList.push({ id: "note-" + n.id, section: "private_note", label: "Recommender's private note", text: n.text }));
    return evidenceList;
  };

  const letterText = () => {
    if (!draftState) return "";
    return [
      "Amelia Hart\nDepartment of Computer Science\n" + new Date().toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" }),
      draftState.salutation,
      ...draftState.paragraphs.map((p) => p.sentences.map((s) => s.text).join(" ")),
      draftState.sign,
    ].join("\n\n");
  };
  const copyLetter = async () => {
    try { await navigator.clipboard.writeText(letterText()); } catch {
      const ta = document.createElement("textarea"); ta.value = letterText(); document.body.appendChild(ta); ta.select(); document.execCommand("copy"); ta.remove();
    }
    setCopied(true); setTimeout(() => setCopied(false), 1800);
  };
  const downloadTxt = () => {
    const blob = new Blob([letterText()], { type: "text/plain" });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = "Letter — " + submission.student + ".txt";
    a.click();
    setTimeout(() => URL.revokeObjectURL(a.href), 2000);
  };
  const toggleReview = (pid, idx) => {
    if (!draftState) return;
    saveDraft({ ...draftState, paragraphs: draftState.paragraphs.map((p) => p.id !== pid ? p : { ...p, sentences: p.sentences.map((s, i) => i !== idx ? s : { ...s, reviewed: !s.reviewed }) }) });
  };
  const uncitedCount = draftState ? draftState.paragraphs.reduce((n, p) => n + p.sentences.filter((s) => !(s.cites || []).length && !s.reviewed).length, 0) : 0;

  const generateLetter = async () => {
    setGenerating(true); setRegenError(null);
    try {
      const evidenceList = buildEvidenceList();
      if (!evidenceList.length) throw new Error("This packet has no evidence to draft from.");
      const prompt = [
        "You are drafting a complete recommendation letter on behalf of Prof. Amelia Hart (Department of Computer Science).",
        "",
        "STUDENT: " + submission.student + (submission.pronouns ? " (" + submission.pronouns + ")" : ""),
        "PURPOSE: " + submission.purpose + (submission.otherDescription ? " — " + submission.otherDescription : ""),
        submission.targets && submission.targets.length ? "APPLYING TO: " + submission.targets.join("; ") : "",
        submission.relationship ? "RELATIONSHIP: " + submission.relationship : "",
        "",
        "EVIDENCE — every factual claim must come from this list, identified by id:",
        JSON.stringify(evidenceList, null, 2),
        "",
        "Return ONLY valid JSON (no markdown fences, no commentary) in this schema:",
        '{ "salutation": "...", "paragraphs": [ { "id": "<short_slug>", "title": "<2-3 word paragraph label>", "beat": "<one sentence: what this paragraph does>", "sentences": [ { "text": "<one complete sentence>", "cites": ["<evidence_id>"] } ] } ], "sign": "Sincerely,\\nProf. Amelia Hart\\nDepartment of Computer Science" }',
        "",
        "Rules:",
        "- 4 to 6 paragraphs. Each item in \"sentences\" is exactly ONE complete sentence.",
        "- \"cites\" lists IDs from EVIDENCE whose facts support that sentence. Use [] only for purely stylistic sentences.",
        "- ONLY use IDs that appear in EVIDENCE. Never invent IDs or facts.",
        "- Voice: warm but considered, first-person professor, lightly formal academic.",
      ].join("\n");
      const raw = await window.claude.complete({ messages: [{ role: "user", content: prompt }], max_tokens: 6000 });
      const parsed = parseRegenResponse(raw);
      if (!parsed || !Array.isArray(parsed.paragraphs) || !parsed.paragraphs.length) throw new Error("Couldn't parse the model's response.");
      const validIds = new Set(evidenceList.map((e) => e.id));
      const paragraphs = parsed.paragraphs.map((p, i) => ({
        id: p.id || "p" + (i + 1),
        title: p.title || "Paragraph " + (i + 1),
        beat: p.beat || "",
        sentences: (p.sentences || []).filter((s) => s && typeof s.text === "string" && s.text.trim()).map((s) => ({ text: s.text.trim(), cites: Array.isArray(s.cites) ? s.cites.filter((c) => validIds.has(c)) : [] })),
      })).filter((p) => p.sentences.length);
      if (!paragraphs.length) throw new Error("Model returned no usable paragraphs.");
      saveDraft({ salutation: parsed.salutation || "Dear Members of the Selection Committee,", paragraphs, sign: parsed.sign || "Sincerely,\nProf. Amelia Hart\nDepartment of Computer Science" });
      if (submission.status === "new") window.LAStore.patch(submission.id, { status: "drafting" });
    } catch (e) {
      setRegenError({ pid: null, message: e.message || String(e) });
    } finally { setGenerating(false); }
  };

  const regenerateParagraph = async (pid) => {
    setRegeneratingId(pid);
    setRegenError(null);
    try {
      const evidenceList = buildEvidenceList();

      const targetPara = draftState.paragraphs.find((p) => p.id === pid);
      const targetText = targetPara.sentences.map((s) => s.text).join(" ");
      const fullDraft = draftState.paragraphs.map((p) => p.sentences.map((s) => s.text).join(" ")).join("\n\n");

      const prompt = [
        "You are helping a professor revise one paragraph of a recommendation letter.",
        "",
        "STUDENT: " + submission.student + " (" + submission.pronouns + ")",
        "PURPOSE: " + submission.purpose,
        "",
        "EVIDENCE — every factual claim must come from this list, identified by id:",
        JSON.stringify(evidenceList, null, 2),
        "",
        "FULL CURRENT LETTER (for voice & continuity, do not rewrite):",
        fullDraft,
        "",
        "TASK: Rewrite ONLY the paragraph titled \"" + (targetPara.title || paragraphTitle(pid)) + "\".",
        "Intent of this paragraph: " + (targetPara.beat || paragraphBeat(pid)),
        "Current version of this paragraph:",
        targetText,
        "",
        "Return ONLY valid JSON (no markdown fences, no commentary) in this schema:",
        '{ "sentences": [ { "text": "<one complete sentence ending in . ! or ?>", "cites": ["<evidence_id>", ...] } ] }',
        "",
        "Rules:",
        "- Each item in \"sentences\" is exactly ONE complete sentence.",
        "- \"cites\" lists IDs from EVIDENCE above whose facts support that sentence. Use [] for purely stylistic sentences.",
        "- ONLY use IDs that appear in EVIDENCE. Never invent IDs.",
        "- Voice: warm but considered, first-person professor, lightly formal academic.",
        "- 3–5 sentences for body paragraphs; 2–4 for opening or closing.",
        "- Never invent facts that aren't in the evidence.",
      ].join("\n");

      const raw = await window.claude.complete(prompt);
      const parsed = parseRegenResponse(raw);
      if (!parsed || !Array.isArray(parsed.sentences) || !parsed.sentences.length) {
        throw new Error("Couldn't parse the model's response.");
      }

      const validIds = new Set(evidenceList.map((e) => e.id));
      const sentences = parsed.sentences
        .filter((s) => s && typeof s.text === "string" && s.text.trim())
        .map((s) => ({
          text: s.text.trim(),
          cites: Array.isArray(s.cites) ? s.cites.filter((c) => validIds.has(c)) : [],
        }));
      if (!sentences.length) throw new Error("Model returned no usable sentences.");

      saveDraft({ ...draftState, paragraphs: draftState.paragraphs.map((p) => (p.id === pid ? { ...p, sentences } : p)) });
    } catch (e) {
      setRegenError({ pid, message: e.message || String(e) });
      setTimeout(() => setRegenError(null), 5000);
    } finally {
      setRegeneratingId(null);
    }
  };

  return (
    <>
      <div className="workspace-tabs">
        <button className={"workspace-tab" + (activePane === "evidence" ? " active" : "")} onClick={() => setActivePane("evidence")}>Evidence</button>
        <button className={"workspace-tab" + (activePane === "draft" ? " active" : "")} onClick={() => setActivePane("draft")}>Draft</button>
        <button className={"workspace-tab" + (activePane === "notes" ? " active" : "")} onClick={() => setActivePane("notes")}>Notes & AI</button>
      </div>
      <div className="workspace-grid" style={{ display: "grid", gridTemplateColumns: "var(--side) minmax(640px, 1fr) var(--notes)", height: "calc(100vh - 56px)", overflow: "hidden" }}>
      {/* ---------------- Evidence panel ---------------- */}
      <aside className={"workspace-pane scroll" + (activePane !== "evidence" ? " is-hidden" : "")} style={{ borderRight: "1px solid var(--line)", background: "var(--surface)", padding: "20px 22px 32px", overflow: "auto" }}>
        <button className="btn btn-ghost btn-sm" onClick={onBack} style={{ marginBottom: 14, marginLeft: -10 }}>← All requests</button>

        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 6 }}>
          <div style={{ width: 40, height: 40, borderRadius: "50%", background: "var(--accent-tint)", color: "var(--accent)", display: "grid", placeItems: "center", fontFamily: "var(--serif)", fontSize: 14, fontWeight: 500 }}>{submission.headshot}</div>
          <div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 18, lineHeight: 1.1 }}>{submission.student}</div>
            <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 2 }}>{submission.purpose}</div>
          </div>
        </div>

        <button className="btn btn-ghost btn-sm" onClick={() => setDetailsOpen((v) => !v)} style={{ marginBottom: detailsOpen ? 10 : 18, marginLeft: -10, color: "var(--muted)" }}>
          {detailsOpen ? "▾" : "▸"} Request details
        </button>

        {detailsOpen && (<div style={{ marginBottom: 8 }}>
        <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginBottom: 14, padding: "10px 12px", background: "var(--bg)", borderRadius: "var(--r)", borderLeft: "2px solid var(--accent-soft)" }}>
          <div className="eyebrow" style={{ fontSize: 10, marginBottom: 4 }}>Applying to</div>
          <div style={{ color: "var(--ink)", fontSize: 12.5 }}>{submission.targets?.join(" · ")}</div>
          <div style={{ marginTop: 6, color: "var(--muted)", fontSize: 11.5 }}>{submission.pronouns} · submitted {submission.submitted}</div>
        </div>

        <div style={{ fontSize: 12, color: "var(--muted)", marginBottom: 8 }}>How you know each other</div>
        <div style={{ fontSize: 12.5, color: "var(--ink-2)", marginBottom: 16, lineHeight: 1.5 }}>{submission.relationship}</div>
        </div>)}

        {/* Attachments (résumé, etc.) */}
        {submission.attachments?.length > 0 && (
          <div style={{ marginBottom: 22 }}>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {submission.attachments.map((a) => (
                <button
                  key={a.id}
                  onClick={() => setResumeOpen(true)}
                  style={{
                    all: "unset", cursor: "pointer",
                    display: "flex", alignItems: "center", gap: 10,
                    padding: "10px 12px",
                    background: "var(--surface-3)",
                    border: "1px solid var(--line)",
                    borderRadius: "var(--r)",
                  }}
                >
                  <div style={{ width: 30, height: 38, borderRadius: 3, background: "var(--accent-tint)", border: "1px solid var(--accent-tint-border)", display: "grid", placeItems: "center", fontFamily: "var(--serif)", fontSize: 9.5, fontWeight: 500, color: "var(--accent)", letterSpacing: "0.05em", flexShrink: 0 }}>
                    PDF
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontFamily: "var(--serif)", fontSize: 13, color: "var(--ink)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{a.name}</div>
                    <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>
                      {a.pages} {a.pages === 1 ? "page" : "pages"} · {(a.size / 1024).toFixed(0)} KB · {pinnedExtracts.length} items pinned
                    </div>
                  </div>
                  <span style={{ color: "var(--accent)", fontSize: 11, fontFamily: "var(--mono)", letterSpacing: "0.05em" }}>OPEN ↗</span>
                </button>
              ))}
            </div>
          </div>
        )}

        {/* used / unused filter */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12, paddingBottom: 12, borderBottom: "1px solid var(--line-soft)" }}>
          <div className="eyebrow">Submitted evidence</div>
          <div style={{ display: "flex", gap: 4 }}>
            <button className="chip" style={{ background: showAll ? "var(--ink)" : "var(--surface-2)", color: showAll ? "var(--surface)" : "var(--ink-2)", borderColor: showAll ? "var(--ink)" : "var(--line)" }} onClick={() => setShowAll(true)}>All {totalCount}</button>
            <button className="chip" style={{ background: !showAll ? "var(--ink)" : "var(--surface-2)", color: !showAll ? "var(--surface)" : "var(--ink-2)", borderColor: !showAll ? "var(--ink)" : "var(--line)" }} onClick={() => setShowAll(false)}>Unused {totalCount - usedIds.size}</button>
          </div>
        </div>

        {Object.entries(allEvidence).map(([sectionKey, items]) => {
          const visible = items.filter((it) => showAll || !usedIds.has(it.id));
          if (!visible.length) return null;
          return (
            <div key={sectionKey} style={{ marginBottom: 22 }}>
              <h3 style={{ fontFamily: "var(--sans)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--muted)", fontWeight: 500, marginBottom: 10 }}>
                {sectionTitle(sectionKey)}
              </h3>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {visible.map((it) => (
                  <div
                    key={it.id}
                    className={"evidence-item" + (isHl(it.id) ? " hl" : "")}
                    onMouseEnter={() => setHover([it.id])}
                    onMouseLeave={() => setHover([])}
                    style={{
                      padding: "10px 12px",
                      background: "var(--surface-3)",
                      border: "1px solid var(--line)",
                      borderRadius: "var(--r)",
                      transition: "background 0.15s, border-color 0.15s, box-shadow 0.15s",
                      cursor: "default",
                    }}
                  >
                    <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 4 }}>
                      <div style={{ fontFamily: "var(--serif)", fontSize: 12.5, color: "var(--ink)", fontWeight: 500 }}>{it.label}</div>
                      {usedIds.has(it.id) ? (
                        <span style={{ fontSize: 9.5, color: "var(--accent)", fontFamily: "var(--mono)" }}>USED</span>
                      ) : (
                        <span style={{ fontSize: 9.5, color: "var(--muted)", fontFamily: "var(--mono)" }}>—</span>
                      )}
                    </div>
                    <div style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.5 }}>{it.text}</div>
                  </div>
                ))}
              </div>
            </div>
          );
        })}

        {/* Pinned résumé extracts */}
        {pinnedExtracts.length > 0 && submission.resumeContent && (
          <div style={{ marginBottom: 22 }}>
            <h3 style={{ fontFamily: "var(--sans)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--muted)", fontWeight: 500, marginBottom: 10, display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ color: "var(--accent)" }}>★</span> From the résumé
            </h3>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {pinnedExtracts.map((eid) => {
                const ex = submission.resumeContent.extracts.find((x) => x.id === eid);
                if (!ex) return null;
                return (
                  <div
                    key={ex.id}
                    className={"evidence-item" + (isHl(ex.id) ? " hl" : "")}
                    onMouseEnter={() => setHover([ex.id])}
                    onMouseLeave={() => setHover([])}
                    style={{
                      padding: "10px 12px",
                      background: "var(--surface-3)",
                      border: "1px solid var(--line)",
                      borderRadius: "var(--r)",
                      transition: "background 0.15s, border-color 0.15s, box-shadow 0.15s",
                      cursor: "default",
                      position: "relative",
                    }}
                  >
                    <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 4, gap: 8 }}>
                      <div style={{ fontFamily: "var(--serif)", fontSize: 12.5, color: "var(--ink)", fontWeight: 500 }}>{ex.label}</div>
                      <button
                        onClick={() => setPinnedExtracts(pinnedExtracts.filter((id) => id !== ex.id))}
                        title="Unpin from evidence"
                        style={{ all: "unset", cursor: "pointer", fontSize: 9.5, color: "var(--muted)", fontFamily: "var(--mono)", letterSpacing: "0.05em" }}
                      >
                        UNPIN
                      </button>
                    </div>
                    <div style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.5 }}>{ex.snippet}</div>
                  </div>
                );
              })}
            </div>
            <button className="btn btn-ghost btn-sm" onClick={() => setResumeOpen(true)} style={{ marginTop: 8, color: "var(--accent)" }}>
              + Pull more from the résumé
            </button>
          </div>
        )}
      </aside>

      {/* ---------------- Draft panel ---------------- */}
      <main className={"workspace-pane scroll" + (activePane !== "draft" ? " is-hidden" : "")} style={{ background: "var(--bg-page)", overflow: "auto", padding: "32px 36px 80px" }}>
        <div className="no-print" style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 18 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 6 }}>Letter draft · {submission.student}</div>
            <h2 style={{ fontSize: 22, letterSpacing: "-0.01em" }}>{submission.purpose}</h2>
          </div>
          <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
            <select className="input" title="Status" value={submission.status} onChange={(e) => window.LAStore.patch(submission.id, { status: e.target.value })} style={{ width: "auto", padding: "6px 10px", fontSize: 12.5 }}>
              <option value="new">New</option>
              <option value="drafting">Drafting</option>
              <option value="sent">Sent</option>
              <option value="declined">Declined</option>
            </select>
            <button className="btn btn-sm" onClick={copyLetter} disabled={!draftState}>{copied ? "Copied ✓" : "Copy"}</button>
            <button className="btn btn-sm" onClick={downloadTxt} disabled={!draftState}>.txt</button>
            <button className="btn btn-sm btn-accent" onClick={() => window.print()} disabled={!draftState}>Print / PDF</button>
          </div>
        </div>

        <div style={{ maxWidth: 760, margin: "0 auto" }}>
          {submission.late && submission.status === "new" && (
            <div className="no-print" style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14, padding: "10px 14px", background: "#FFFBEB", border: "1px solid #FDE68A", borderRadius: "var(--r)", fontSize: 12.5, color: "#92400E" }}>
              <span style={{ flex: 1 }}>This packet arrived <strong>inside your {window.LAStore.policy.amount}-{window.LAStore.policy.unit.replace(/s$/, "")} window</strong>. You decide whether to draft it.</span>
              <button className="btn btn-sm" onClick={() => window.LAStore.patch(submission.id, { status: "drafting" })}>Draft anyway</button>
              <button className="btn btn-ghost btn-sm" onClick={() => { window.LAStore.patch(submission.id, { status: "declined" }); onBack(); }} style={{ color: "#92400E" }}>Decline</button>
            </div>
          )}
          {draftState && uncitedCount > 0 && aiLevel === "full" && (
            <div className="no-print" style={{ marginBottom: 14, padding: "8px 14px", background: "#FFFBEB", border: "1px solid #FDE68A", borderRadius: "var(--r)", fontSize: 12.5, color: "#92400E" }}>
              ⚑ {uncitedCount} sentence{uncitedCount > 1 ? "s have" : " has"} no citation — flagged for your review. Click a flagged sentence to mark it reviewed.
            </div>
          )}
          {!draftState && aiLevel !== "none" && (
            <div className="card" style={{ padding: "44px 40px", textAlign: "center" }}>
              <h2 style={{ fontSize: 22, marginBottom: 10 }}>No draft yet</h2>
              <p style={{ color: "var(--ink-3)", fontSize: 14, maxWidth: 460, margin: "0 auto 20px", lineHeight: 1.55 }}>
                Generate a first draft from {submission.student.split(" ")[0]}'s evidence — every sentence will cite its source — or switch AI to “Off” for a blank page.
              </p>
              <button className="btn btn-accent" onClick={generateLetter} disabled={generating}>
                {generating ? <span className="pulse">Drafting…</span> : "Generate first draft"}
              </button>
              {regenError && <div style={{ marginTop: 14, fontSize: 12.5, color: "#991B1B" }}>{regenError.message} — try again.</div>}
            </div>
          )}
          {(draftState || aiLevel === "none") && (<>
          {/* The "paper" */}
          <article className="letter-article" style={{ background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: "var(--r-md)", padding: "52px 56px 56px", boxShadow: "var(--shadow-2)", fontFamily: "var(--serif)", fontSize: 16, lineHeight: 1.7, color: "var(--ink)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 32, fontSize: 13.5, color: "var(--ink-3)" }}>
              <div>
                <div>Amelia Hart</div>
                <div>Department of Computer Science</div>
              </div>
              <div style={{ textAlign: "right" }}>
                <div>November 21, 2026</div>
              </div>
            </div>

            <div style={{ marginBottom: 20 }}>{draftState?.salutation || "Dear Members of the Selection Committee,"}</div>

            {aiLevel === "none" ? (
              <div contentEditable suppressContentEditableWarning data-placeholder="Start writing…" className="blank-page" style={{ minHeight: 320, outline: "none", whiteSpace: "pre-wrap" }}></div>
            ) : draftState.paragraphs.map((p) => (
              <Paragraph
                key={p.id}
                paragraph={p}
                hoverIds={hoverIds}
                setHover={setHover}
                aiLevel={aiLevel}
                regenerating={regeneratingId === p.id}
                onRegenerate={() => regenerateParagraph(p.id)}
                onToggleReview={(idx) => toggleReview(p.id, idx)}
              />
            ))}

            <div style={{ whiteSpace: "pre-wrap", marginTop: 24, color: "var(--ink-2)" }}>{draftState?.sign || "Sincerely,\nProf. Amelia Hart\nDepartment of Computer Science"}</div>
          </article>

          {/* Footer toolbar */}
          <div className="no-print" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 16, color: "var(--muted)", fontSize: 12 }}>
            <div>{usedIds.size} of {totalCount} evidence pieces used · hover any sentence to see its source.</div>
            <div>Saved</div>
          </div>
          </>)}

          {regenError && (
            <div style={{ marginTop: 12, padding: "10px 14px", background: "#FEF2F2", border: "1px solid #FCA5A5", color: "#991B1B", borderRadius: "var(--r)", fontSize: 12.5 }}>
              <strong>Couldn't regenerate.</strong> {regenError.message} — please try again.
            </div>
          )}
        </div>
      </main>

      {/* ---------------- Notes + AI panel ---------------- */}
      <aside className={"workspace-pane scroll" + (activePane !== "notes" ? " is-hidden" : "")} style={{ borderLeft: "1px solid var(--line)", background: "var(--surface)", padding: "20px 22px 32px", overflow: "auto" }}>
        <AISection level={aiLevel} setLevel={setAiLevel} />
        <NotesSection notes={notes} setNotes={setNotes} hoverIds={hoverIds} setHover={setHover} />
      </aside>

      {/* ---------------- Resume overlay ---------------- */}
      {resumeOpen && submission.resumeContent && (
        <ResumeOverlay
          submission={submission}
          pinned={pinnedExtracts}
          onPin={(id) => setPinnedExtracts((p) => (p.includes(id) ? p.filter((x) => x !== id) : [...p, id]))}
          onClose={() => setResumeOpen(false)}
        />
      )}
      </div>
    </>
  );
}

function sectionTitle(key) {
  return {
    goals: "Goals & purpose",
    courses: "Courses & contact",
    projects: "Projects",
    skills: "Skills + evidence",
    anecdotes: "Specific moments",
    growth: "Growth",
    extras: "Anything else",
  }[key] || key;
}

/* ---------------- Paragraph with hover citations ---------------- */
function Paragraph({ paragraph, hoverIds, setHover, aiLevel, regenerating, onRegenerate, onToggleReview }) {
  const [hovered, setHovered] = useState(false);

  // Build a summary if aiLevel === bullets / outline
  if (aiLevel === "bullets") {
    const bullets = uniqueCites(paragraph).map((id) => id);
    return (
      <div style={{ marginBottom: 22, position: "relative" }} onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)}>
        <ParaToolbar visible={hovered} onRegenerate={onRegenerate} regenerating={regenerating} />
        <div style={{ fontFamily: "var(--sans)", fontSize: 12, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--accent)", marginBottom: 8 }}>
          {paragraph.title || paragraphTitle(paragraph.id)}
        </div>
        <ul style={{ paddingLeft: 18, margin: 0, fontFamily: "var(--sans)", fontSize: 14, color: "var(--ink-2)", lineHeight: 1.55 }}>
          {bullets.map((id) => (
            <li key={id} onMouseEnter={() => setHover([id])} onMouseLeave={() => setHover([])} style={{ marginBottom: 4, padding: "2px 4px", borderRadius: 3, background: hoverIds.includes(id) ? "var(--hl)" : "transparent" }}>
              Use: <span style={{ fontStyle: "italic" }}>{shorten(window.__evidenceById?.[id]?.text || id, 90)}</span>
            </li>
          ))}
        </ul>
      </div>
    );
  }

  if (aiLevel === "outline") {
    return (
      <div style={{ marginBottom: 22, position: "relative" }} onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)}>
        <ParaToolbar visible={hovered} onRegenerate={onRegenerate} regenerating={regenerating} />
        <div style={{ fontFamily: "var(--sans)", fontSize: 12, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--accent)", marginBottom: 6 }}>
          {paragraph.title || paragraphTitle(paragraph.id)}
        </div>
        <div style={{ fontFamily: "var(--sans)", fontSize: 13.5, color: "var(--ink-3)", fontStyle: "italic", lineHeight: 1.55 }}>
          {paragraph.beat || paragraphBeat(paragraph.id)}
        </div>
      </div>
    );
  }

  // Full draft mode — render sentences with cite markers
  return (
    <div
      style={{ marginBottom: 18, position: "relative", padding: "2px 8px", marginLeft: -8, marginRight: -8, borderRadius: 4, transition: "background 0.15s" }}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      <ParaToolbar visible={hovered} onRegenerate={onRegenerate} regenerating={regenerating} />
      <p style={{ margin: 0, opacity: regenerating ? 0.35 : 1, transition: "opacity 0.2s" }}>
        {paragraph.sentences.map((s, i) => (
          <Sentence key={i} sentence={s} hoverIds={hoverIds} setHover={setHover} onToggleReview={() => onToggleReview && onToggleReview(i)} />
        ))}
      </p>
      {regenerating && (
        <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", pointerEvents: "none" }}>
          <div style={{ fontFamily: "var(--sans)", fontSize: 12, color: "var(--accent)", letterSpacing: "0.1em", textTransform: "uppercase" }}>
            <span className="pulse">Regenerating…</span>
          </div>
        </div>
      )}
    </div>
  );
}

function Sentence({ sentence, hoverIds, setHover, onToggleReview }) {
  const cites = sentence.cites || [];
  const hl = cites.some((c) => hoverIds.includes(c));
  const uncited = cites.length === 0;
  return (
    <span
      onMouseEnter={() => cites.length && setHover(cites)}
      onMouseLeave={() => setHover([])}
      onClick={() => uncited && onToggleReview && onToggleReview()}
      className={"cited" + (hl ? " hl" : "") + (uncited ? (sentence.reviewed ? " uncited ok" : " uncited") : "")}
      title={uncited ? (sentence.reviewed ? "No citation — marked reviewed. Click to re-flag." : "No citation — click to mark reviewed.") : undefined}
      style={{ cursor: cites.length ? "help" : "pointer" }}
    >
      {sentence.text}
      {cites.length > 0 && (
        <span className={"cite-mark" + (hl ? " active" : "")} title={`Cites: ${cites.join(", ")}`}>
          {cites.join(",")}
        </span>
      )}
      {uncited && <span className={"flag-mark" + (sentence.reviewed ? " ok" : "")}>{sentence.reviewed ? "✓" : "⚑"}</span>}
      {" "}
    </span>
  );
}

function ParaToolbar({ visible, onRegenerate, regenerating }) {
  return (
    <div
      style={{
        position: "absolute", right: -54, top: 0,
        opacity: visible && !regenerating ? 1 : 0,
        transition: "opacity 0.15s",
        display: "flex", flexDirection: "column", gap: 4,
        pointerEvents: visible ? "auto" : "none",
      }}
    >
      <button className="btn btn-ghost btn-icon" title="Regenerate this paragraph" onClick={onRegenerate} style={{ background: "var(--surface)", border: "1px solid var(--line)" }}>↻</button>
      <button className="btn btn-ghost btn-icon" title="Tighten" style={{ background: "var(--surface)", border: "1px solid var(--line)" }}>−</button>
      <button className="btn btn-ghost btn-icon" title="Expand" style={{ background: "var(--surface)", border: "1px solid var(--line)" }}>+</button>
    </div>
  );
}

function paragraphTitle(id) {
  return { intro: "Opening", research: "Research record", lab: "Lab work", rigor: "Rigor & judgment", writing: "Writing & communication", character: "Character", close: "Closing" }[id] || id;
}
function paragraphBeat(id) {
  return {
    intro: "Establish the relationship: courses, time, role in your lab. Two sentences. End with a strong overall claim.",
    research: "State her research area in her own words. Lead with the SAE replication — independence + visible artifact + caught a bug in the original paper.",
    lab: "Lead authorship on the refusal-directions paper, her week-3 framing contribution, the disposition (results not questions). Senior thesis as forward momentum.",
    rigor: "Tell the December 5th story. Disagreement → overnight controls → revised the paper's claims. End with the takeaway: pushes back, then updates.",
    writing: "Lit review used as reading-list reference; substack with public readership. Two sentences max.",
    character: "Mentorship of the paper-reading group, especially the first-years she pulled in. Quiet labor that selection committees rarely see.",
    close: "Why a PhD specifically (slow questions). Restate your overall recommendation. Offer contact.",
  }[id] || "";
}
function uniqueCites(p) {
  const seen = new Set();
  p.sentences.forEach((s) => s.cites.forEach((c) => seen.add(c)));
  return [...seen];
}
function shorten(s, n) { return s.length > n ? s.slice(0, n) + "…" : s; }

// Strip any markdown code fences and extract the first {...} object from the model output.
function parseRegenResponse(raw) {
  if (!raw || typeof raw !== "string") return null;
  let s = raw.trim();
  // Strip leading/trailing ```json ... ``` fences if present
  s = s.replace(/^```(?:json)?\s*/i, "").replace(/```\s*$/i, "").trim();
  // Find the first balanced-looking JSON object
  const start = s.indexOf("{");
  const end = s.lastIndexOf("}");
  if (start === -1 || end === -1 || end < start) return null;
  const candidate = s.slice(start, end + 1);
  try {
    return JSON.parse(candidate);
  } catch {
    return null;
  }
}

/* ---------------- Resume overlay ---------------- */
function ResumeOverlay({ submission, pinned, onPin, onClose }) {
  const rc = submission.resumeContent;
  const [filter, setFilter] = useState("all"); // all | suggested

  // Close on ESC
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  const visibleExtracts = filter === "suggested" ? rc.extracts.filter((e) => !pinned.includes(e.id)) : rc.extracts;

  return (
    <div
      style={{
        position: "fixed", inset: 0, zIndex: 200,
        background: "rgba(10, 37, 64, 0.55)", backdropFilter: "blur(4px)",
        display: "grid", placeItems: "center", padding: 40,
      }}
      onClick={onClose}
    >
      <div
        className="resume-modal"
        onClick={(e) => e.stopPropagation()}
        style={{
          width: "min(1180px, 100%)", height: "calc(100vh - 80px)",
          background: "var(--surface-2)", borderRadius: "var(--r-lg)",
          boxShadow: "var(--shadow-3)", border: "1px solid var(--line)",
          display: "grid", gridTemplateColumns: "1fr 380px",
          overflow: "hidden",
        }}
      >
        {/* CV preview side */}
        <div className="scroll" style={{ overflow: "auto", minHeight: 0, padding: "32px 40px 40px", background: "var(--surface-3)" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8 }}>
            <div className="eyebrow">{submission.attachments[0].name}</div>
            <div style={{ fontSize: 11.5, color: "var(--muted)" }}>{rc.sections.length} sections · {submission.attachments[0].pages} pages</div>
          </div>

          {/* Faux CV */}
          <div style={{ marginTop: 18, paddingBottom: 24, borderBottom: "1px solid var(--line)" }}>
            <h2 style={{ fontFamily: "var(--serif)", fontSize: 28, letterSpacing: "-0.01em", marginBottom: 4 }}>{rc.header.name}</h2>
            <div style={{ fontFamily: "var(--mono)", fontSize: 11.5, color: "var(--muted)" }}>{rc.header.contact}</div>
          </div>

          {rc.sections.map((sec) => (
            <section key={sec.title} style={{ marginTop: 24 }}>
              <h3 style={{ fontFamily: "var(--sans)", fontSize: 10.5, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--accent)", fontWeight: 500, marginBottom: 10, paddingBottom: 6, borderBottom: "1px solid var(--line-soft)" }}>
                {sec.title}
              </h3>
              <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                {sec.items.map((it, i) => (
                  <div key={i}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 16 }}>
                      <div style={{ fontFamily: "var(--serif)", fontSize: 14, color: "var(--ink)", fontWeight: 500 }}>{it.primary}</div>
                      <div style={{ fontFamily: "var(--sans)", fontSize: 11.5, color: "var(--muted)", whiteSpace: "nowrap" }}>{it.secondary}</div>
                    </div>
                    {it.bullets && (
                      <ul style={{ margin: "6px 0 0 0", paddingLeft: 18, fontFamily: "var(--sans)", fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.55 }}>
                        {it.bullets.map((b, j) => <li key={j} style={{ marginBottom: 2 }}>{b}</li>)}
                      </ul>
                    )}
                  </div>
                ))}
              </div>
            </section>
          ))}
        </div>

        {/* Extracts side */}
        <div className="resume-modal-extracts" style={{ display: "flex", flexDirection: "column", minHeight: 0, borderLeft: "1px solid var(--line)", background: "var(--surface)" }}>
          <div style={{ padding: "20px 22px 14px", borderBottom: "1px solid var(--line-soft)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 4 }}>
              <h3 style={{ fontFamily: "var(--serif)", fontSize: 18 }}>Pull into evidence</h3>
              <button className="btn btn-ghost btn-icon" onClick={onClose} title="Close (Esc)">×</button>
            </div>
            <p style={{ fontSize: 12.5, color: "var(--muted)", margin: "6px 0 12px", lineHeight: 1.45 }}>
              Items on the résumé that aren't in Maya's form. Pin any of them — they become citable evidence and the next regenerate can draw from them.
            </p>
            <div style={{ display: "flex", gap: 4 }}>
              <button className={"chip" + (filter === "all" ? " active" : "")} onClick={() => setFilter("all")}>All {rc.extracts.length}</button>
              <button className={"chip" + (filter === "suggested" ? " active" : "")} onClick={() => setFilter("suggested")}>Not yet pinned</button>
            </div>
          </div>

          <div className="scroll" style={{ flex: 1, overflow: "auto", padding: "14px 22px 24px" }}>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {visibleExtracts.map((ex) => {
                const isPinned = pinned.includes(ex.id);
                return (
                  <div
                    key={ex.id}
                    style={{
                      padding: "12px 14px",
                      background: isPinned ? "var(--accent-tint)" : "var(--surface-3)",
                      border: `1px solid ${isPinned ? "var(--accent-tint-border)" : "var(--line)"}`,
                      borderRadius: "var(--r)",
                    }}
                  >
                    <div style={{ fontSize: 10, fontFamily: "var(--mono)", color: "var(--muted)", letterSpacing: "0.08em", marginBottom: 4, textTransform: "uppercase" }}>{ex.category}</div>
                    <div style={{ fontFamily: "var(--serif)", fontSize: 14, color: "var(--ink)", marginBottom: 6, fontWeight: 500 }}>{ex.label}</div>
                    <div style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.5, marginBottom: 8 }}>{ex.snippet}</div>
                    <div style={{ fontSize: 11.5, color: "var(--muted)", fontStyle: "italic", lineHeight: 1.45, marginBottom: 10 }}>{ex.rationale}</div>
                    <button
                      className={"btn btn-sm " + (isPinned ? "" : "btn-accent")}
                      style={isPinned ? { background: "var(--surface-3)", borderColor: "var(--accent)", color: "var(--accent)" } : {}}
                      onClick={() => onPin(ex.id)}
                    >
                      {isPinned ? "✓ Pinned · unpin" : "+ Pin to evidence"}
                    </button>
                  </div>
                );
              })}
              {visibleExtracts.length === 0 && (
                <div style={{ padding: "32px 8px", textAlign: "center", color: "var(--muted)", fontSize: 13 }}>
                  Everything's pinned.
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------------- AI involvement section ---------------- */
function AISection({ level, setLevel }) {
  const options = [
    { id: "full", title: "Full draft", desc: "Generate the complete letter. You edit." },
    { id: "outline", title: "Outline only", desc: "Paragraph-by-paragraph beats. You write." },
    { id: "bullets", title: "Talking points", desc: "Just the evidence to use, organized." },
    { id: "none", title: "Off", desc: "Plain blank page. No suggestions." },
  ];
  const active = options.find((o) => o.id === level);
  return (
    <div style={{ marginBottom: 28 }}>
      <div className="eyebrow" style={{ marginBottom: 10 }}>AI involvement</div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
        {options.map((o) => (
          <button
            key={o.id}
            onClick={() => setLevel(o.id)}
            title={o.desc}
            style={{
              border: `1px solid ${level === o.id ? "var(--accent)" : "var(--line)"}`,
              background: level === o.id ? "var(--accent-tint)" : "var(--surface-3)",
              color: "var(--ink)", borderRadius: "var(--r)", cursor: "pointer",
              padding: "9px 10px", fontFamily: "var(--sans)", fontSize: 12.5, fontWeight: level === o.id ? 500 : 400,
            }}
          >
            {o.title}
          </button>
        ))}
      </div>
      <div style={{ marginTop: 10, fontSize: 11.5, color: "var(--muted)", lineHeight: 1.45 }}>
        {active?.desc} Hover <span style={{ fontFamily: "var(--mono)", fontSize: 10.5 }}>↻</span> beside a paragraph to regenerate it — the model cites only the evidence at left and your notes.
      </div>
    </div>
  );
}

/* ---------------- Notes section ---------------- */
function NotesSection({ notes, setNotes, hoverIds, setHover }) {
  const [composing, setComposing] = useState(false);
  const [draft, setDraft] = useState("");

  const addNote = () => {
    if (!draft.trim()) return;
    setNotes([...notes, { id: "n" + Date.now(), text: draft.trim() }]);
    setDraft("");
    setComposing(false);
  };

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
        <div className="eyebrow">Your private notes</div>
        <button className="btn btn-ghost btn-sm" onClick={() => setComposing(true)}>+ Add</button>
      </div>
      <div style={{ fontSize: 11.5, color: "var(--muted)", marginBottom: 12, lineHeight: 1.4 }}>
        Only you can see these; the AI can cite them.
      </div>

      {composing && (
        <div style={{ border: "1px solid var(--accent)", background: "var(--surface-3)", borderRadius: "var(--r)", padding: 10, marginBottom: 10 }}>
          <textarea autoFocus rows={3} className="textarea" placeholder="A correction, a memory she didn't mention, a private observation…" value={draft} onChange={(e) => setDraft(e.target.value)} style={{ border: "none", padding: 0, background: "transparent" }} />
          <div style={{ display: "flex", justifyContent: "flex-end", gap: 6, marginTop: 8 }}>
            <button className="btn btn-ghost btn-sm" onClick={() => { setDraft(""); setComposing(false); }}>Cancel</button>
            <button className="btn btn-primary btn-sm" onClick={addNote}>Save</button>
          </div>
        </div>
      )}

      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {notes.map((n) => {
          const noteId = "note-" + n.id;
          const hl = hoverIds && hoverIds.includes(noteId);
          return (
            <div
              key={n.id}
              onMouseEnter={() => setHover && setHover([noteId])}
              onMouseLeave={() => setHover && setHover([])}
              className={"evidence-item" + (hl ? " hl" : "")}
              style={{
                padding: "10px 12px",
                background: n.pinned ? "var(--accent-tint)" : "var(--surface-3)",
                border: `1px solid ${n.pinned ? "var(--accent-tint-border)" : "var(--line)"}`,
                borderRadius: "var(--r)",
                transition: "background 0.15s, border-color 0.15s, box-shadow 0.15s",
              }}
            >
              {n.pinned && <div style={{ fontSize: 9.5, fontFamily: "var(--mono)", color: "var(--accent)", marginBottom: 4, letterSpacing: "0.1em" }}>PINNED</div>}
              <div style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.5 }}>{n.text}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// expose evidenceById globally for bullets mode (lookup-only)
(function exposeEvidenceLookup() {
  const m = {};
  window.SUBMISSIONS.forEach((s) => {
    if (s.evidence) Object.values(s.evidence).forEach((arr) => arr.forEach((e) => (m[e.id] = e)));
  });
  window.__evidenceById = m;
})();

window.Recommender = Recommender;
})();
