/* global React, Icon, Button, Chip, ScreenHeader, Panel, SectionLabel, AgentNote, DocToolbar, Segmented, StepRail, Provenance, ProvBadge, FitBadge, Pill, TONES, TARGET_JOB, RESUME_DIFF, COVER, CUSTOM_QA, CANDIDATE */
const { useState: useTl } = React;

const TL_STEPS = [
  { key: "input", label: "Job" },
  { key: "resume", label: "Résumé" },
  { key: "cover", label: "Cover letter" },
  { key: "questions", label: "Questions" },
  { key: "apply", label: "Apply" },
];

function ScrTailor() {
  const [si, setSi] = useTl(1); // start at résumé to show the signature view first; input is step 0
  const [analyzed, setAnalyzed] = useTl(true);
  const [filling, setFilling] = useTl(false);
  const step = TL_STEPS[si].key;

  return (
    <div style={{ maxWidth: 1080, margin: "0 auto", padding: "8px 0 40px" }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 20, marginBottom: 18 }}>
        <div>
          <div className="cd-eyebrow" style={{ marginBottom: 7 }}>Tailor &amp; apply</div>
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 500, fontSize: 30, letterSpacing: "-0.02em", margin: 0 }}>{TARGET_JOB.title}</h2>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 8, fontSize: 13.5, color: "var(--fg-2)" }}>
            <span style={{ fontWeight: 500, color: "var(--fg-1)" }}>{TARGET_JOB.company}</span><span>·</span>
            <span>{TARGET_JOB.location}</span><span>·</span><span>{TARGET_JOB.comp}</span>
            <FitBadge value={TARGET_JOB.fit} size="sm"/>
          </div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <Button variant="ghost" size="sm" icon="link">Open posting</Button>
          <Button variant="primary" size="sm" icon="send" onClick={() => setFilling(true)}>Apply now</Button>
        </div>
      </div>

      <Panel pad={14} style={{ marginBottom: 16 }}>
        <StepRail steps={TL_STEPS} current={si} onJump={setSi}/>
      </Panel>

      {step === "input" && <JobInput analyzed={analyzed} setAnalyzed={setAnalyzed} onNext={() => setSi(1)}/>}
      {step === "resume" && <ResumeDiff onBack={() => setSi(0)} onNext={() => setSi(2)}/>}
      {step === "cover" && <CoverLetter onBack={() => setSi(1)} onNext={() => setSi(3)}/>}
      {step === "questions" && <CustomQA onBack={() => setSi(2)} onNext={() => setSi(4)}/>}
      {step === "apply" && <ApplyStep onBack={() => setSi(3)} onFill={() => setFilling(true)}/>}

      {filling && <FormFillOverlay onClose={() => setFilling(false)}/>}
    </div>
  );
}

// ---------- Step 0: job input ----------
function JobInput({ analyzed, setAnalyzed, onNext }) {
  const [mode, setMode] = useTl("paste");
  return (
    <div className="cad-rise" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <Panel pad={18}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
          <SectionLabel>Add the job</SectionLabel>
          <Segmented value={mode} onChange={setMode} options={[{ value: "paste", label: "Paste description" }, { value: "url", label: "Paste link" }]}/>
        </div>
        {mode === "paste" ? (
          <textarea defaultValue={TARGET_JOB.jd.join("\n\n")} rows={6} style={taStyle}/>
        ) : (
          <div style={{ display: "flex", gap: 8 }}>
            <input defaultValue="https://stripe.com/jobs/senior-pm-payments" style={{ ...taStyle, flex: 1, height: 42, padding: "0 12px" }}/>
            <Button variant="secondary" size="md" icon="globe">Fetch</Button>
          </div>
        )}
        <div style={{ fontSize: 11.5, color: "var(--fg-2)", marginTop: 8 }}>Links are fetched from your browser, so they work even behind a login.</div>
      </Panel>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <SourceCard icon="grid" title="From your job board" sub="High-match roles Offerroom already found"/>
        <SourceCard icon="puzzle" title="From the Chrome extension" sub="Saved while browsing, queued to apply"/>
      </div>

      {analyzed && (
        <Panel pad={18} accent={TONES.sage.color} className="cad-fade">
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
            <Icon name="check" size={16} style={{ color: "#5A7150" }}/>
            <span style={{ fontWeight: 600, fontSize: 14 }}>Analyzed · strong fit ({TARGET_JOB.fit.toFixed(2)})</span>
          </div>
          <div style={{ fontSize: 13, color: "var(--fg-2)", lineHeight: 1.5 }}>The posting leads with checkout experimentation and conversion. You have direct, quantified evidence for both. I'll surface it.</div>
        </Panel>
      )}

      {analyzed && (
        <Panel pad={16} className="cad-fade" style={{ display: "flex", alignItems: "center", gap: 14, background: "var(--paper)", borderStyle: "dashed" }}>
          <span style={{ width: 34, height: 34, borderRadius: 8, background: "var(--slate-tint)", color: "#2A3744", display: "grid", placeItems: "center", flexShrink: 0 }}><Icon name="copy" size={16}/></span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13.5, fontWeight: 600 }}>This is 88% the same as your Linear résumé</div>
            <div style={{ fontSize: 12, color: "var(--fg-2)", marginTop: 1, lineHeight: 1.45 }}>I found it by semantic match. I'll edit over that tailored version instead of starting from your base — faster, and it keeps what already worked.</div>
          </div>
          <div style={{ display: "flex", gap: 7, flexShrink: 0 }}>
            <Button variant="ghost" size="sm">Start from base</Button>
            <Button variant="secondary" size="sm" icon="check">Reuse it</Button>
          </div>
        </Panel>
      )}

      <div style={{ display: "flex", justifyContent: "flex-end" }}>
        <Button variant="primary" size="md" icon="arrow" onClick={onNext}>Tailor my résumé</Button>
      </div>
    </div>
  );
}

const SourceCard = ({ icon, title, sub }) => (
  <Panel pad={14} style={{ display: "flex", alignItems: "center", gap: 12, cursor: "pointer" }}>
    <span style={{ width: 38, height: 38, borderRadius: 8, background: "var(--paper-sunken)", color: "var(--fg-1)", display: "grid", placeItems: "center", flexShrink: 0 }}><Icon name={icon} size={18}/></span>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 13.5, fontWeight: 500 }}>{title}</div>
      <div style={{ fontSize: 12, color: "var(--fg-2)" }}>{sub}</div>
    </div>
    <Icon name="chevron" size={15} style={{ color: "var(--fg-3)" }}/>
  </Panel>
);

// ---------- Step 1: résumé diff (signature) ----------
function ResumeDiff({ onBack, onNext }) {
  const [editing, setEditing] = useTl(false);
  const [saved, setSaved] = useTl("saved");
  const onEditChange = () => { setSaved("saving"); clearTimeout(window.__cadSave); window.__cadSave = setTimeout(() => setSaved("saved"), 700); };

  return (
    <div className="cad-rise" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <AgentNote time="just now">
        Your base résumé is customised for this role. <b>Hover any highlighted line</b> to see exactly where it came from, your work history, the story graph, and how it was phrased. Edit anything inline, it autosaves.
      </AgentNote>

      <Panel pad={0}>
        <DocToolbar
          left={<>
            <Icon name="fileText" size={15} style={{ color: "var(--fg-2)" }}/>
            <span style={{ fontSize: 13, fontWeight: 500 }}>Résumé · Stripe — Senior PM, Payments</span>
            <SaveState state={saved}/>
          </>}
          right={<>
            <LegendDots/>
            <span style={{ width: 1, height: 18, background: "var(--ink-100)" }}/>
            <Button variant={editing ? "primary" : "ghost"} size="sm" icon="edit" onClick={() => setEditing(e => !e)}>{editing ? "Done editing" : "Edit"}</Button>
          </>}/>
        <div style={{ background: "var(--paper-sunken)", padding: 22, display: "grid", placeItems: "center" }}>
          <div style={{ width: 620, background: "#fff", boxShadow: "0 8px 24px rgba(31,27,22,0.10)", padding: "34px 38px" }}>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 24, fontWeight: 500, letterSpacing: "-0.01em" }}>{CANDIDATE.fullName}</div>
            <div style={{ fontSize: 11.5, color: "var(--fg-2)", marginTop: 3, borderBottom: "2px solid #8C1515", paddingBottom: 12 }}>{CANDIDATE.location} · {CANDIDATE.email}</div>

            {RESUME_DIFF.map((sec, i) => (
              <div key={i} style={{ marginTop: 18 }}>
                <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--cardinal)", marginBottom: 10 }}>{sec.section}</div>
                <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 12 }}>
                  {sec.bullets.map((b, j) => <DiffBullet key={j} b={b} editing={editing} onEditChange={onEditChange}/>)}
                </ul>
              </div>
            ))}
          </div>
        </div>
      </Panel>

      <div style={{ display: "flex", justifyContent: "space-between" }}>
        <Button variant="ghost" size="md" onClick={onBack}>← Job</Button>
        <Button variant="primary" size="md" icon="arrow" onClick={onNext}>Looks good · cover letter</Button>
      </div>
    </div>
  );
}

const DiffBullet = ({ b, editing, onEditChange }) => {
  const isRewrite = b.status === "rewritten";
  return (
    <li style={{ position: "relative", paddingLeft: 16 }}>
      <span style={{ position: "absolute", left: 0, top: 7, width: 5, height: 5, borderRadius: 999, background: isRewrite ? "#8C1515" : "var(--ink-300)" }}/>
      {isRewrite && b.old && (
        <div style={{ fontSize: 11.5, lineHeight: 1.5, color: "var(--ink-300)", textDecoration: "line-through", marginBottom: 3 }}>{b.old}</div>
      )}
      {editing ? (
        <textarea defaultValue={b.new} onChange={onEditChange} rows={2} style={{ ...taStyle, fontSize: 12.5, padding: "6px 9px", width: "100%" }}/>
      ) : (
        <div style={{ fontSize: 12.5, lineHeight: 1.55, color: "var(--ink-700)" }}>
          {isRewrite ? (
            <Provenance trail={b.prov}>
              <span style={{ background: "rgba(74,88,104,0.08)", borderRadius: 3, padding: "0 2px" }}>{b.new}</span>
            </Provenance>
          ) : b.new}
        </div>
      )}
      <div style={{ display: "flex", alignItems: "center", gap: 7, marginTop: 4 }}>
        {isRewrite ? <Chip tone="info" dot={true}>Rewritten</Chip> : <Chip tone="neutral" dot={false}>Kept</Chip>}
        <span style={{ fontSize: 11, color: "var(--fg-2)", lineHeight: 1.4 }}>{b.why}</span>
      </div>
    </li>
  );
};

const LegendDots = () => (
  <div style={{ display: "flex", gap: 12, fontSize: 11, color: "var(--fg-2)" }}>
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><span style={{ width: 6, height: 6, borderRadius: 999, background: "#8C1515" }}/>Rewritten</span>
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--ink-300)" }}/>Kept</span>
  </div>
);

const SaveState = ({ state }) => (
  <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11.5, color: state === "saving" ? "var(--ochre-text)" : "var(--sage-text)" }}>
    {state === "saving" ? <><span className="cad-pulse-dot" style={{ background: "#B08A3E" }}/>Saving…</> : <><Icon name="check" size={12}/>Autosaved</>}
  </span>
);

// ---------- Step 2: cover letter ----------
function CoverLetter({ onBack, onNext }) {
  const coverText = [
    COVER.greeting,
    ...COVER.paras.map(p => p.map(s => s.t).join("")),
    "Warmly,\n" + COVER.signoff,
  ].join("\n\n");
  const [editing, setEditing] = useTl(false);
  const [saved, setSaved] = useTl("saved");
  const onEditChange = () => { setSaved("saving"); clearTimeout(window.__cadCoverSave); window.__cadCoverSave = setTimeout(() => setSaved("saved"), 700); };

  return (
    <div className="cad-rise" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <AgentNote time="just now">
        This is researched against Stripe and written to connect as a person, not a candidate. Nothing here repeats your résumé. Highlighted parts show where each detail came from.
      </AgentNote>
      <Panel pad={0}>
        <DocToolbar
          left={<><Icon name="message" size={15} style={{ color: "var(--fg-2)" }}/><span style={{ fontSize: 13, fontWeight: 500 }}>Cover letter · Stripe</span>{editing ? <SaveState state={saved}/> : <Pill tone="sage"><Icon name="globe" size={11}/> Researched</Pill>}</>}
          right={<><Button variant={editing ? "primary" : "ghost"} size="sm" icon="edit" onClick={() => setEditing(e => !e)}>{editing ? "Done editing" : "Edit"}</Button><Button variant="ghost" size="sm" icon="copy">Copy</Button></>}/>
        <div style={{ background: "var(--paper-sunken)", padding: 22, display: "grid", placeItems: "center" }}>
          <div style={{ width: 600, background: "#fff", boxShadow: "0 8px 24px rgba(31,27,22,0.10)", padding: "38px 44px", fontFamily: "var(--font-sans)", fontSize: 13.5, lineHeight: 1.7, color: "var(--ink-700)" }}>
            {editing ? (
              <textarea defaultValue={coverText} onChange={onEditChange} rows={16} style={{ ...taStyle, fontSize: 13.5, lineHeight: 1.7, padding: "4px 2px", border: "none", resize: "vertical" }}/>
            ) : (
              <>
                <div style={{ marginBottom: 16 }}>{COVER.greeting}</div>
                {COVER.paras.map((p, i) => (
                  <p key={i} style={{ margin: "0 0 14px" }}>
                    {p.map((seg, j) => seg.prov
                      ? <Provenance key={j} trail={[seg.prov]}><span style={{ background: TONES[seg.prov.db === "Web" ? "sage" : seg.prov.db === "Vault" ? "slate" : "cardinal"].tint, borderRadius: 3, padding: "1px 3px" }}>{seg.t}</span></Provenance>
                      : <span key={j}>{seg.t}</span>)}
                  </p>
                ))}
                <div style={{ marginTop: 18 }}>Warmly,<br/>{COVER.signoff}</div>
              </>
            )}
          </div>
        </div>
      </Panel>
      <div style={{ display: "flex", justifyContent: "space-between" }}>
        <Button variant="ghost" size="md" onClick={onBack}>← Résumé</Button>
        <Button variant="primary" size="md" icon="arrow" onClick={onNext}>Next · custom questions</Button>
      </div>
    </div>
  );
}

// ---------- Step 3: custom Q&A ----------
function CustomQA({ onBack, onNext }) {
  return (
    <div className="cad-rise" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <AgentNote time="just now">
        This application has 2 custom questions. Answers are drafted from your memory. Anything that sounds a little too polished is flagged, putting it in your own words keeps it from reading like AI.
      </AgentNote>
      {CUSTOM_QA.map((qa, i) => <QACard key={i} qa={qa} n={i + 1}/>)}
      <AddQuestion startN={CUSTOM_QA.length + 1}/>
      <div style={{ display: "flex", justifyContent: "space-between" }}>
        <Button variant="ghost" size="md" onClick={onBack}>← Cover letter</Button>
        <Button variant="primary" size="md" icon="arrow" onClick={onNext}>Ready to apply</Button>
      </div>
    </div>
  );
}

// An empty-state card that expands into a working "ask a question" composer,
// then drafts a QACard for any questions added.
function AddQuestion({ startN }) {
  const [open, setOpen] = useTl(false);
  const [q, setQ] = useTl("");
  const [added, setAdded] = useTl([]);
  const [drafting, setDrafting] = useTl(false);

  const submit = () => {
    const text = q.trim();
    if (!text) return;
    setDrafting(true);
    setTimeout(() => {
      setAdded(a => [...a, {
        q: text,
        a: "Drafted from your memory — grounded in your work history and the story graph. Review and make it yours before submitting.",
        chars: 268,
        nudge: "Drafted from your memory. Skim it once so it sounds like you.",
      }]);
      setQ("");
      setDrafting(false);
      setOpen(false);
    }, 900);
  };

  return (
    <>
      {added.map((qa, i) => <QACard key={i} qa={qa} n={startN + i}/>)}
      {open ? (
        <Panel pad={18} className="cad-fade">
          <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 10 }}>
            <span style={{ width: 28, height: 28, borderRadius: 999, background: "var(--cardinal-50)", color: "var(--cardinal)", display: "grid", placeItems: "center", flexShrink: 0 }}><Icon name="sparkles" size={14}/></span>
            <div style={{ fontSize: 13.5, fontWeight: 600 }}>What should Offerroom answer?</div>
          </div>
          <textarea
            autoFocus
            value={q}
            onChange={e => setQ(e.target.value)}
            placeholder="Paste the application question — e.g. “What draws you to Stripe specifically?”"
            rows={2}
            style={taStyle}
            onKeyDown={e => { if ((e.metaKey || e.ctrlKey) && e.key === "Enter") submit(); }}
          />
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, marginTop: 12 }}>
            <span style={{ fontSize: 11.5, color: "var(--fg-2)" }}>Drafted from your memory, you review before it's used.</span>
            <div style={{ display: "flex", gap: 7, flexShrink: 0 }}>
              <Button variant="ghost" size="sm" onClick={() => { setOpen(false); setQ(""); }}>Cancel</Button>
              <Button variant="primary" size="sm" icon={drafting ? undefined : "sparkles"} onClick={submit} disabled={!q.trim() || drafting}>{drafting ? "Drafting…" : "Draft answer"}</Button>
            </div>
          </div>
        </Panel>
      ) : (
        <button
          onClick={() => setOpen(true)}
          style={{ all: "unset", cursor: "pointer", display: "block" }}
        >
          <Panel pad={14} style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 8, color: "var(--fg-2)", fontSize: 13, borderStyle: "dashed" }}>
            <Icon name="plus" size={14}/> Add another question to answer
          </Panel>
        </button>
      )}
    </>
  );
}

const QACard = ({ qa, n }) => {
  const [edit, setEdit] = useTl(false);
  const flagged = qa.nudge.toLowerCase().includes("own words") || qa.nudge.toLowerCase().includes("polished");
  return (
    <Panel pad={18}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: "var(--fg-1)" }}><span style={{ color: "var(--fg-3)", fontFamily: "var(--font-mono)", marginRight: 8 }}>{String(n).padStart(2, "0")}</span>{qa.q}</div>
        <span style={{ fontSize: 11, color: "var(--fg-3)", fontFamily: "var(--font-mono)", flexShrink: 0, whiteSpace: "nowrap" }}>{qa.chars} chars</span>
      </div>
      {edit ? (
        <textarea defaultValue={qa.a} rows={3} style={{ ...taStyle, marginTop: 12 }}/>
      ) : (
        <div style={{ fontSize: 13.5, lineHeight: 1.6, color: "var(--ink-700)", marginTop: 10, padding: "12px 14px", background: "var(--paper)", borderRadius: 8, border: "1px solid var(--ink-50)" }}>{qa.a}</div>
      )}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, marginTop: 12 }}>
        <div style={{ display: "flex", alignItems: "flex-start", gap: 8, fontSize: 12, color: flagged ? "var(--ochre-text)" : "var(--sage-text)", flex: 1, minWidth: 0 }}>
          <Icon name={flagged ? "lightbulb" : "check"} size={14} style={{ flexShrink: 0, marginTop: 1 }}/>
          <span style={{ lineHeight: 1.45 }}>{qa.nudge}</span>
        </div>
        <div style={{ display: "flex", gap: 7, flexShrink: 0 }}>
          <Button variant="ghost" size="sm" icon="edit" onClick={() => setEdit(e => !e)}>{edit ? "Save" : "Edit"}</Button>
          <CopyButton text={`${qa.q}\n\n${qa.a}`}/>
        </div>
      </div>
    </Panel>
  );
};

// ---------- Step 4: apply / review ----------
function ApplyStep({ onBack, onFill }) {
  const ready = [
    { icon: "fileText", label: "Tailored résumé", sub: "3 lines rewritten · ATS-safe PDF", tone: "sage", view: "resume", file: "Okonkwo — Stripe.txt", body: resumeText() },
    { icon: "message", label: "Cover letter", sub: "Researched · 3 paragraphs", tone: "sage", view: "cover", file: "Cover — Stripe.txt", body: coverDocText() },
    { icon: "list", label: "2 custom answers", sub: "1 flagged for your voice", tone: "ochre", view: "qa", file: "Custom answers — Stripe.txt", body: qaText() },
  ];
  const [preview, setPreview] = useTl(null);
  return (
    <div className="cad-rise" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <Panel pad={20}>
        <SectionLabel style={{ marginBottom: 14 }}>Everything's ready</SectionLabel>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
          {ready.map((r, i) => {
            const t = TONES[r.tone];
            return (
              <div key={i} style={{ padding: 14, borderRadius: 10, border: "1px solid var(--ink-100)", background: "var(--paper)", display: "flex", flexDirection: "column" }}>
                <span style={{ width: 32, height: 32, borderRadius: 8, background: t.tint, color: t.color, display: "grid", placeItems: "center" }}><Icon name={r.icon} size={16}/></span>
                <div style={{ fontSize: 13.5, fontWeight: 600, marginTop: 10 }}>{r.label}</div>
                <div style={{ fontSize: 11.5, color: "var(--fg-2)", marginTop: 2 }}>{r.sub}</div>
                <div style={{ display: "flex", gap: 7, marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--ink-50)" }}>
                  <Button variant="ghost" size="sm" icon="eye" onClick={() => setPreview(r)}>View</Button>
                  <DownloadButton file={r.file} body={r.body}/>
                </div>
              </div>
            );
          })}
        </div>
      </Panel>

      {preview && <DocPreviewModal item={preview} onClose={() => setPreview(null)}/>}

      <Panel pad={18} accent={TONES.cardinal.color}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <span style={{ width: 40, height: 40, borderRadius: 8, background: "var(--cardinal-50)", color: "var(--cardinal)", display: "grid", placeItems: "center", flexShrink: 0 }}><Icon name="zap" size={20}/></span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 14.5, fontWeight: 600 }}>Let the form-filling agent submit it</div>
            <div style={{ fontSize: 12.5, color: "var(--fg-2)", marginTop: 2, lineHeight: 1.45 }}>Offerroom fills Stripe's application, pulls any extra answers from your memory, uploads both documents, and logs it to your tracker. You see everything before it sends.</div>
          </div>
          <Button variant="primary" size="md" icon="zap" onClick={onFill}>Fill &amp; apply</Button>
        </div>
      </Panel>

      <div style={{ display: "flex", justifyContent: "space-between" }}>
        <Button variant="ghost" size="md" onClick={onBack}>← Questions</Button>
        <Button variant="secondary" size="md" icon="check">Save, I'll apply myself</Button>
      </div>
    </div>
  );
}

// Build the plain-text bodies for view/download from the same source data.
function resumeText() {
  const lines = [CANDIDATE.fullName, `${CANDIDATE.location} · ${CANDIDATE.email}`, "", "Tailored for Stripe — Senior PM, Payments", ""];
  RESUME_DIFF.forEach(sec => {
    lines.push(sec.section.toUpperCase());
    sec.bullets.forEach(b => lines.push(`• ${b.new}`));
    lines.push("");
  });
  return lines.join("\n").trim();
}
function coverDocText() {
  return [COVER.greeting, "", ...COVER.paras.map(p => p.map(s => s.t).join("")), "", "Warmly,", COVER.signoff].join("\n");
}
function qaText() {
  return CUSTOM_QA.map((qa, i) => `${String(i + 1).padStart(2, "0")}. ${qa.q}\n\n${qa.a}`).join("\n\n———\n\n");
}

function downloadText(file, body) {
  const blob = new Blob([body], { type: "text/plain" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url; a.download = file;
  document.body.appendChild(a); a.click(); a.remove();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

const DownloadButton = ({ file, body }) => {
  const [done, setDone] = useTl(false);
  const onClick = () => { downloadText(file, body); setDone(true); setTimeout(() => setDone(false), 1800); };
  return <Button variant="secondary" size="sm" icon={done ? "check" : "download"} onClick={onClick}>{done ? "Saved" : "Download"}</Button>;
};

// Single-click copy with confirmation feedback.
const CopyButton = ({ text }) => {
  const [done, setDone] = useTl(false);
  const onClick = () => {
    if (navigator.clipboard) navigator.clipboard.writeText(text).catch(() => {});
    setDone(true); setTimeout(() => setDone(false), 1600);
  };
  return <Button variant="ghost" size="sm" icon={done ? "check" : "copy"} onClick={onClick}>{done ? "Copied" : "Copy"}</Button>;
};

// Read-only preview of a generated document. The résumé reuses the Résumé studio's
// rendered document so its format matches everywhere; cover & Q&A render as paper.
function DocPreviewModal({ item, onClose }) {
  const tpl = (window.TEMPLATES || []).find(x => x.key === "executive") || (window.TEMPLATES || [])[0];
  const wide = item.view === "resume";
  return ReactDOM.createPortal((
    <div className="cad-fade" style={{ position: "fixed", inset: 0, zIndex: 100, background: "rgba(31,27,22,0.32)", display: "grid", placeItems: "center", padding: 24 }} onClick={onClose}>
      <div className="cad-rise" onClick={e => e.stopPropagation()} style={{ width: wide ? 660 : 620, maxHeight: "88vh", display: "flex", flexDirection: "column", background: "#fff", borderRadius: 14, boxShadow: "0 32px 64px rgba(31,27,22,0.28)" }}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--ink-100)", display: "flex", alignItems: "center", gap: 12 }}>
          <Icon name={item.icon} size={16} style={{ color: "var(--fg-2)" }}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13.5, fontWeight: 600 }}>{item.label}</div>
            <div style={{ fontSize: 11.5, color: "var(--fg-2)", fontFamily: "var(--font-mono)" }}>{item.file}</div>
          </div>
          <DownloadButton file={item.file} body={item.body}/>
          <button onClick={onClose} style={{ width: 28, height: 28, borderRadius: 6, border: "1px solid var(--ink-100)", background: "#fff", cursor: "pointer", display: "grid", placeItems: "center" }}><Icon name="close" size={14}/></button>
        </div>
        <div style={{ overflow: "auto", padding: 22, background: "var(--paper-sunken)", display: "grid", placeItems: "center" }}>
          {item.view === "resume" && window.ResumeDoc ? (
            <window.ResumeDoc t={tpl} density="comfortable" accentOn={true} tailored={true}/>
          ) : item.view === "cover" ? (
            <div style={{ width: 540, background: "#fff", boxShadow: "0 8px 24px rgba(31,27,22,0.10)", padding: "38px 44px", fontFamily: "var(--font-sans)", fontSize: 13.5, lineHeight: 1.7, color: "var(--ink-700)" }}>
              <div style={{ marginBottom: 16 }}>{COVER.greeting}</div>
              {COVER.paras.map((p, i) => <p key={i} style={{ margin: "0 0 14px" }}>{p.map(s => s.t).join("")}</p>)}
              <div style={{ marginTop: 18 }}>Warmly,<br/>{COVER.signoff}</div>
            </div>
          ) : (
            <div style={{ width: 540, display: "flex", flexDirection: "column", gap: 12 }}>
              {CUSTOM_QA.map((qa, i) => {
                const flagged = qa.nudge.toLowerCase().includes("own words") || qa.nudge.toLowerCase().includes("polished");
                return (
                  <div key={i} style={{ background: "#fff", boxShadow: "0 8px 24px rgba(31,27,22,0.10)", borderRadius: 10, padding: "18px 20px" }}>
                    <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--fg-1)" }}><span style={{ color: "var(--fg-3)", fontFamily: "var(--font-mono)", marginRight: 8 }}>{String(i + 1).padStart(2, "0")}</span>{qa.q}</div>
                      <span style={{ fontSize: 11, color: "var(--fg-3)", fontFamily: "var(--font-mono)", flexShrink: 0, whiteSpace: "nowrap" }}>{qa.chars} chars</span>
                    </div>
                    <div style={{ fontSize: 13, lineHeight: 1.6, color: "var(--ink-700)", marginTop: 10, padding: "12px 14px", background: "var(--paper)", borderRadius: 8, border: "1px solid var(--ink-50)" }}>{qa.a}</div>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, marginTop: 12 }}>
                      <div style={{ display: "flex", alignItems: "flex-start", gap: 8, fontSize: 12, color: flagged ? "var(--ochre-text)" : "var(--sage-text)", flex: 1, minWidth: 0 }}>
                        <Icon name={flagged ? "lightbulb" : "check"} size={14} style={{ flexShrink: 0, marginTop: 1 }}/>
                        <span style={{ lineHeight: 1.45 }}>{qa.nudge}</span>
                      </div>
                      <CopyButton text={`${qa.q}\n\n${qa.a}`}/>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  ), document.body);
}

// ---------- Form-filling agent overlay ----------
function FormFillOverlay({ onClose }) {
  const [i, setI] = useTl(0);
  const fields = [
    { label: "First name", value: "Maya", src: "Profile" },
    { label: "Work authorization", value: "International · work-authorized", src: "Profile" },
    { label: "Years in payments", value: "6", src: "Graph" },
    { label: "Why this role? (custom)", value: "Pulled your tailored answer", src: "Draft" },
    { label: "Résumé upload", value: "Okonkwo — Stripe.pdf", src: "Files" },
    { label: "Cover letter upload", value: "Cover — Stripe.pdf", src: "Files" },
  ];
  const [done, setDone] = useTl(false);
  React.useEffect(() => {
    if (i >= fields.length) { setTimeout(() => setDone(true), 500); return; }
    const t = setTimeout(() => setI(i + 1), 620);
    return () => clearTimeout(t);
  }, [i]);

  return (
    <div className="cad-fade" style={{ position: "fixed", inset: 0, zIndex: 100, background: "rgba(31,27,22,0.32)", display: "grid", placeItems: "center", padding: 24 }} onClick={onClose}>
      <div className="cad-rise" onClick={e => e.stopPropagation()} style={{ width: 560, maxHeight: "86vh", overflow: "auto", background: "#fff", borderRadius: 14, boxShadow: "0 32px 64px rgba(31,27,22,0.28)" }}>
        <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--ink-100)", display: "flex", alignItems: "center", gap: 12 }}>
          <span style={{ width: 36, height: 36, borderRadius: 999, background: "#8C1515", display: "grid", placeItems: "center", animation: done ? "none" : "cad-pulse-ring 1.6s ease-out infinite" }}><Icon name="zap" size={18} style={{ color: "#fff" }}/></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 500 }}>{done ? "Filled. Ready to submit." : "Filling Stripe's application…"}</div>
            <div style={{ fontSize: 12, color: "var(--fg-2)" }}>{done ? "Review below, nothing's submitted yet." : "Pulling answers from your memory as needed"}</div>
          </div>
          <button onClick={onClose} style={{ width: 28, height: 28, borderRadius: 6, border: "1px solid var(--ink-100)", background: "#fff", cursor: "pointer", display: "grid", placeItems: "center" }}><Icon name="close" size={14}/></button>
        </div>
        <div style={{ padding: "8px 22px 16px" }}>
          {fields.map((f, idx) => {
            const filled = idx < i;
            return (
              <div key={idx} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 0", borderBottom: idx < fields.length - 1 ? "1px solid var(--ink-50)" : "none", opacity: filled ? 1 : 0.4, transition: "opacity 200ms" }}>
                <span style={{ width: 18, height: 18, borderRadius: 999, flexShrink: 0, display: "grid", placeItems: "center", background: filled ? "#5A7150" : "transparent", border: filled ? "none" : "1.5px solid var(--ink-100)", color: "#fff" }}>{filled && <Icon name="check" size={11}/>}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12, color: "var(--fg-2)" }}>{f.label}</div>
                  <div style={{ fontSize: 13.5, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{f.value}</div>
                </div>
                {filled && <ProvBadge db={f.src === "Profile" || f.src === "Files" ? "Vault" : f.src} small/>}
              </div>
            );
          })}
        </div>
        {done && (
          <div className="cad-fade" style={{ padding: "0 22px 20px", display: "flex", gap: 8, justifyContent: "flex-end" }}>
            <Button variant="ghost" size="md" onClick={onClose}>Cancel</Button>
            <Button variant="secondary" size="md" icon="eye">Review on site</Button>
            <Button variant="primary" size="md" icon="send" onClick={onClose}>Submit application</Button>
          </div>
        )}
      </div>
    </div>
  );
}

const taStyle = {
  width: "100%", boxSizing: "border-box", resize: "vertical", padding: "11px 12px", borderRadius: 8,
  border: "1px solid var(--ink-100)", background: "#fff", fontFamily: "var(--font-sans)",
  fontSize: 13.5, lineHeight: 1.55, color: "var(--fg-1)", outline: "none",
};

window.ScrTailor = ScrTailor;
