// Compose screen — multi-step: scope -> recipients -> draft -> preview
const TEMPLATE_BODY = `Dear FOI Officer,

Under the Freedom of Information Act 2000, I am writing to request the following information for the academic years 2022–23, 2023–24 and 2024–25:

1. The total number of employees (including the Accounting Officer / CEO) earning a gross annual salary of £100,000 or more, broken down by £5,000 band.

2. The total value of expense claims made by those employees in each year, broken down by category (travel, subsistence, hospitality, other).

3. Any policies governing executive remuneration, performance-related pay, and severance.

I would prefer to receive the response in a machine-readable format (CSV or XLSX) where applicable.

If any part of this request is unclear, or if you believe the cost of compliance would exceed the appropriate limit under section 12, please contact me so that we may refine the scope.

Yours faithfully,

R. Davies
National Education Union — Research
`;

function Compose({ go }) {
  const [step, setStep] = React.useState(0);
  const [title, setTitle] = React.useState("CEO and executive pay across MATs");
  const [body, setBody] = React.useState(TEMPLATE_BODY);
  const [scope, setScope] = React.useState("both"); // dfe | mat | both
  const [selectedMats, setSelectedMats] = React.useState(window.MATS.slice(0, 12).map(m => m.uid));
  const [tag, setTag] = React.useState("pay, executive, 2024-25");
  const [redact, setRedact] = React.useState(true);
  const [sentRef, setSentRef] = React.useState(null);

  const matCount = selectedMats.length;
  const dfeIncluded = scope === "dfe" || scope === "both";
  const matIncluded = scope === "mat" || scope === "both";
  const totalRecipients = (dfeIncluded ? 1 : 0) + (matIncluded ? matCount : 0);

  const steps = ["Scope", "Recipients", "Draft", "Review & send"];

  if (sentRef) return <Dispatched ref={sentRef} go={go} reset={() => { setSentRef(null); setStep(0); }} />;

  return (
    <div>
      <SectionTitle sub="Draft once · send to DfE via WhatDoTheyKnow and to MATs via email">Compose request</SectionTitle>

      <div style={{ display: "flex", gap: 4, marginBottom: 20, padding: 4, background: "var(--surface-2)", border: "1px solid var(--rule)", borderRadius: 2, width: "fit-content" }}>
        {steps.map((s, i) => (
          <button key={s} onClick={() => setStep(i)} style={{
            border: "none", background: step === i ? "var(--surface)" : "transparent",
            padding: "6px 14px", fontSize: 13, fontWeight: step === i ? 600 : 500,
            color: step === i ? "var(--text)" : "var(--muted)",
            cursor: "pointer", fontFamily: "inherit",
            borderRadius: 2,
            boxShadow: step === i ? "0 1px 2px rgba(0,0,0,0.06)" : "none"
          }}>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, marginRight: 6, opacity: 0.6 }}>{String(i+1).padStart(2,'0')}</span>{s}
          </button>
        ))}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 16 }}>
        <div>
          {step === 0 && (
            <Card>
              <Field label="Request title" hint="Internal — also used as the email subject prefix">
                <TextInput value={title} onChange={setTitle} />
              </Field>
              <Field label="Topic tags" hint="Comma-separated; used for analytics rollups">
                <TextInput value={tag} onChange={setTag} mono />
              </Field>
              <Field label="Who is this addressed to?">
                <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 8 }}>
                  {[
                    { id: "dfe", title: "DfE only", sub: "Via WhatDoTheyKnow API" },
                    { id: "mat", title: "MATs only", sub: "Via email (SMTP)" },
                    { id: "both", title: "DfE + MATs", sub: "Both channels in parallel" }
                  ].map((o) => (
                    <button key={o.id} onClick={() => setScope(o.id)} style={{
                      border: scope === o.id ? "2px solid var(--accent)" : "1px solid var(--rule)",
                      background: scope === o.id ? "var(--nav-active-bg)" : "var(--surface)",
                      padding: 14, textAlign: "left", cursor: "pointer", fontFamily: "inherit",
                      borderRadius: 2, margin: scope === o.id ? 0 : 1
                    }}>
                      <div style={{ fontWeight: 600, fontSize: 14, color: "var(--text)" }}>{o.title}</div>
                      <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>{o.sub}</div>
                    </button>
                  ))}
                </div>
              </Field>
              <div style={{ display: "flex", justifyContent: "flex-end", gap: 8 }}>
                <Button onClick={() => setStep(1)} icon={<Ico.Arrow/>}>Continue</Button>
              </div>
            </Card>
          )}

          {step === 1 && (
            <RecipientPicker selectedMats={selectedMats} setSelectedMats={setSelectedMats} scope={scope} />
          )}

          {step === 1 && (
            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 12 }}>
              <Button variant="secondary" onClick={() => setStep(0)}>← Back</Button>
              <Button onClick={() => setStep(2)} icon={<Ico.Arrow/>}>Continue to draft</Button>
            </div>
          )}

          {step === 2 && (
            <Card>
              <Field label="Request body" hint="Will be wrapped with a per-MAT salutation and your signature on send">
                <TextArea value={body} onChange={setBody} rows={18} />
              </Field>
              <div style={{ display: "flex", gap: 12, alignItems: "center", padding: 12, background: "var(--surface-2)", border: "1px solid var(--rule)", borderRadius: 2, marginBottom: 12 }}>
                <input type="checkbox" checked={redact} onChange={(e) => setRedact(e.target.checked)} style={{ accentColor: "var(--accent)" }} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>Run GDPR redaction pass before sending</div>
                  <div style={{ fontSize: 12, color: "var(--muted)" }}>Strip personal data from any forwarded attachments and warn on named-individual references in the body.</div>
                </div>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <Button variant="secondary" onClick={() => setStep(1)}>← Back</Button>
                <Button onClick={() => setStep(3)} icon={<Ico.Eye/>}>Review &amp; send</Button>
              </div>
            </Card>
          )}

          {step === 3 && (
            <Card>
              <div style={{ borderLeft: "3px solid var(--accent)", padding: "8px 14px", marginBottom: 16, background: "var(--nav-active-bg)" }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>Ready to send</div>
                <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>
                  {dfeIncluded && <>1 request to DfE via WhatDoTheyKnow API.</>} {matIncluded && <>{matCount} emails to MATs (rate-limited to 8/min).</>}
                </div>
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: "8px 14px", fontSize: 13, marginBottom: 18 }}>
                <span style={{ color: "var(--muted)" }}>Subject</span><span><span style={{ fontFamily: "var(--font-mono)", color: "var(--muted)" }}>[FOI]</span> {title}</span>
                <span style={{ color: "var(--muted)" }}>Channels</span><span>{dfeIncluded && "WhatDoTheyKnow API"}{dfeIncluded && matIncluded && " · "}{matIncluded && "SMTP (postmaster@neu.org.uk)"}</span>
                <span style={{ color: "var(--muted)" }}>Recipients</span><span style={{ fontVariantNumeric: "tabular-nums" }}>{totalRecipients}</span>
                <span style={{ color: "var(--muted)" }}>Tracking</span><span>Per-recipient thread ID · auto-link replies to <span style={{ fontFamily: "var(--font-mono)" }}>FOI-2026-0130</span></span>
                <span style={{ color: "var(--muted)" }}>Compliance</span><span>20-working-day clock starts on dispatch · ICO escalation drafted on day 21</span>
                <span style={{ color: "var(--muted)" }}>Redaction</span><span>{redact ? "Enabled" : "Disabled"}</span>
              </div>

              <div style={{ border: "1px solid var(--rule)", padding: 16, background: "var(--surface-2)", maxHeight: 280, overflow: "auto", marginBottom: 16, fontFamily: "var(--font-mono)", fontSize: 12.5, lineHeight: 1.6, color: "var(--text)", whiteSpace: "pre-wrap" }}>
                {body}
              </div>

              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <Button variant="secondary" onClick={() => setStep(2)}>← Edit draft</Button>
                <div style={{ display: "flex", gap: 8 }}>
                  <Button variant="secondary">Save as draft</Button>
                  <Button onClick={() => setSentRef({ count: totalRecipients, mat: matCount, dfe: dfeIncluded, id: "FOI-2026-0130" })} icon={<Ico.Send/>}>Dispatch to {totalRecipients}</Button>
                </div>
              </div>
            </Card>
          )}
        </div>

        {/* Right-rail summary */}
        <div>
          <Card pad={0}>
            <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--rule)", fontSize: 13, fontWeight: 600 }}>Summary</div>
            <div style={{ padding: 16, fontSize: 13, lineHeight: 1.7 }}>
              <div style={{ marginBottom: 14 }}>
                <div style={{ fontSize: 11, textTransform: "uppercase", color: "var(--muted)", letterSpacing: "0.06em", fontWeight: 600 }}>Title</div>
                <div style={{ color: "var(--text)" }}>{title || <span style={{ color: "var(--muted)" }}>—</span>}</div>
              </div>
              <div style={{ marginBottom: 14 }}>
                <div style={{ fontSize: 11, textTransform: "uppercase", color: "var(--muted)", letterSpacing: "0.06em", fontWeight: 600 }}>Channels</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 4 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, opacity: dfeIncluded ? 1 : 0.35 }}>
                    <div style={{ width: 18, height: 18, background: "var(--accent)", color: "#fff", fontSize: 10, fontFamily: "var(--font-mono)", fontWeight: 700, display: "grid", placeItems: "center", borderRadius: 2 }}>W</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13 }}>WhatDoTheyKnow → DfE</div>
                      <div style={{ fontSize: 11, color: "var(--muted)", fontFamily: "var(--font-mono)" }}>api.whatdotheyknow.com/v2</div>
                    </div>
                    {dfeIncluded && <Pill tone="ok">1</Pill>}
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, opacity: matIncluded ? 1 : 0.35 }}>
                    <div style={{ width: 18, height: 18, background: "#3a2f1f", color: "#fff", fontSize: 10, fontFamily: "var(--font-mono)", fontWeight: 700, display: "grid", placeItems: "center", borderRadius: 2 }}>@</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13 }}>Email → MATs</div>
                      <div style={{ fontSize: 11, color: "var(--muted)", fontFamily: "var(--font-mono)" }}>SMTP · BCC research@neu.org.uk</div>
                    </div>
                    {matIncluded && <Pill tone="ok">{matCount}</Pill>}
                  </div>
                </div>
              </div>

              <div style={{ marginBottom: 14 }}>
                <div style={{ fontSize: 11, textTransform: "uppercase", color: "var(--muted)", letterSpacing: "0.06em", fontWeight: 600 }}>Compliance</div>
                <ul style={{ paddingLeft: 18, margin: "4px 0 0", color: "var(--text)" }}>
                  <li>FOIA 2000 · 20-working-day deadline</li>
                  <li>Cost limit check (s.12) on send</li>
                  <li>Audit-logged with thread IDs</li>
                </ul>
              </div>

              <div>
                <div style={{ fontSize: 11, textTransform: "uppercase", color: "var(--muted)", letterSpacing: "0.06em", fontWeight: 600 }}>Estimated cost</div>
                <div style={{ fontFamily: "var(--font-mono)", color: "var(--text)", marginTop: 2 }}>£{(totalRecipients * 0.0042).toFixed(4)}</div>
                <div style={{ fontSize: 11, color: "var(--muted)" }}>SMTP relay + LLM extraction on reply</div>
              </div>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

function Dispatched({ ref, go, reset }) {
  const [phase, setPhase] = React.useState(0);
  React.useEffect(() => {
    const t1 = setTimeout(() => setPhase(1), 700);
    const t2 = setTimeout(() => setPhase(2), 1500);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []);
  const lines = [
    { t: "POST /api/v2/requests", to: "api.whatdotheyknow.com", ok: phase >= 1, status: phase >= 1 ? "200 OK · request id 1842988" : "…" },
    { t: "SMTP batch", to: `${ref.mat} recipients via mailgun-eu`, ok: phase >= 2, status: phase >= 2 ? `${ref.mat}/${ref.mat} accepted · 0 bounced` : "…" }
  ];
  return (
    <div>
      <SectionTitle sub="Tracking now live — replies will auto-link to this request">Request dispatched</SectionTitle>
      <Card style={{ maxWidth: 720, margin: "0 auto" }}>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", padding: "30px 0 24px" }}>
          <div style={{ width: 56, height: 56, background: "var(--ok-bg)", color: "var(--ok-fg)", display: "grid", placeItems: "center", borderRadius: "50%", border: "1px solid var(--ok-bd)", marginBottom: 14, transition: "transform 400ms ease", transform: phase >= 2 ? "scale(1)" : "scale(0.5)" }}>
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12l5 5 9-11"/></svg>
          </div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--muted)" }}>{ref.id}</div>
          <div style={{ fontSize: 18, fontWeight: 600, marginTop: 6 }}>Sent to {ref.count} recipients</div>
        </div>

        <div style={{ borderTop: "1px solid var(--rule)", padding: "16px 0" }}>
          {lines.map((l, i) => (
            <div key={i} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 12, padding: "10px 4px", alignItems: "center", fontFamily: "var(--font-mono)", fontSize: 12 }}>
              <div style={{ color: l.ok ? "var(--ok-fg)" : "var(--muted)", fontWeight: 600 }}>{l.ok ? "✓" : "↻"}</div>
              <div>
                <span style={{ color: "var(--text)", fontWeight: 600 }}>{l.t}</span> <span style={{ color: "var(--muted)" }}>→ {l.to}</span>
              </div>
              <div style={{ color: "var(--muted)" }}>{l.status}</div>
            </div>
          ))}
        </div>

        <div style={{ display: "flex", gap: 8, justifyContent: "center", marginTop: 16 }}>
          <Button variant="secondary" onClick={reset}>Compose another</Button>
          <Button onClick={() => go("tracker")} icon={<Ico.Arrow/>}>Open in Tracker</Button>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { Compose, Dispatched });
