// Recipient picker — inline in compose, also standalone screen
function RecipientPicker({ selectedMats, setSelectedMats, scope, standalone }) {
  const [query, setQuery] = React.useState("");
  const [region, setRegion] = React.useState("All");
  const [showOnlyVerified, setShowOnlyVerified] = React.useState(false);
  const [sizeFilter, setSizeFilter] = React.useState("any"); // any | small | mid | large

  const filtered = window.MATS.filter((m) => {
    if (query && !`${m.name} ${m.town} ${m.uid}`.toLowerCase().includes(query.toLowerCase())) return false;
    if (region !== "All" && m.region !== region) return false;
    if (showOnlyVerified && !m.verified) return false;
    if (sizeFilter === "small" && m.schools > 5) return false;
    if (sizeFilter === "mid" && (m.schools < 6 || m.schools > 14)) return false;
    if (sizeFilter === "large" && m.schools < 15) return false;
    return true;
  });

  const toggle = (uid) => {
    if (selectedMats.includes(uid)) setSelectedMats(selectedMats.filter((x) => x !== uid));
    else setSelectedMats([...selectedMats, uid]);
  };
  const allFiltered = filtered.every((m) => selectedMats.includes(m.uid));
  const toggleAll = () => {
    if (allFiltered) setSelectedMats(selectedMats.filter((x) => !filtered.find((m) => m.uid === x)));
    else setSelectedMats(Array.from(new Set([...selectedMats, ...filtered.map((m) => m.uid)])));
  };

  return (
    <Card pad={0}>
      <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--rule)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
          <div>
            <div style={{ fontWeight: 600, fontSize: 14 }}>Recipient picker</div>
            <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>Pulled from <span style={{ fontFamily: "var(--font-mono)" }}>get-information-schools.service.gov.uk</span> · contacts scraped from each trust website</div>
          </div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--muted)" }}>
            <span style={{ color: "var(--text)", fontWeight: 600 }}>{selectedMats.length}</span> / {window.MATS.length} selected
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr auto", gap: 8 }}>
          <div style={{ position: "relative" }}>
            <div style={{ position: "absolute", left: 10, top: 0, bottom: 0, display: "flex", alignItems: "center", color: "var(--muted)" }}><Ico.Search/></div>
            <input
              type="text"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Search by name, town or TR-ID"
              style={{ width: "100%", padding: "8px 10px 8px 32px", fontSize: 13, fontFamily: "inherit", border: "1px solid var(--rule)", background: "var(--surface)", borderRadius: 2, outline: "none" }}
            />
          </div>
          <Select value={region} onChange={setRegion}>
            <option>All</option>
            {window.REGIONS.map((r) => <option key={r}>{r}</option>)}
          </Select>
          <Select value={sizeFilter} onChange={setSizeFilter}>
            <option value="any">Any size</option>
            <option value="small">Small (1–5 schools)</option>
            <option value="mid">Mid (6–14 schools)</option>
            <option value="large">Large (15+ schools)</option>
          </Select>
          <button onClick={() => setShowOnlyVerified(!showOnlyVerified)} style={{
            padding: "0 12px", border: "1px solid var(--rule)",
            background: showOnlyVerified ? "var(--accent)" : "var(--surface)",
            color: showOnlyVerified ? "#fff" : "var(--text)",
            fontSize: 12, cursor: "pointer", fontFamily: "inherit", fontWeight: 500, borderRadius: 2,
            whiteSpace: "nowrap"
          }}>Verified only</button>
        </div>
      </div>

      <div style={{ maxHeight: 460, overflow: "auto" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
          <thead style={{ background: "var(--surface-2)", position: "sticky", top: 0, zIndex: 1 }}>
            <tr>
              <th style={{ width: 32, padding: "8px 12px", textAlign: "left", borderBottom: "1px solid var(--rule)" }}>
                <input type="checkbox" checked={allFiltered && filtered.length > 0} onChange={toggleAll} style={{ accentColor: "var(--accent)" }} />
              </th>
              <Th>Trust</Th>
              <Th width={90}>Region</Th>
              <Th width={70} num>Schools</Th>
              <Th>Contact</Th>
              <Th width={120}>Source</Th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((m) => {
              const sel = selectedMats.includes(m.uid);
              return (
                <tr key={m.uid}
                    onClick={() => toggle(m.uid)}
                    style={{ cursor: "pointer", borderBottom: "1px solid var(--rule)", background: sel ? "var(--nav-active-bg)" : "transparent" }}>
                  <td style={{ padding: "10px 12px" }}>
                    <input type="checkbox" checked={sel} readOnly style={{ accentColor: "var(--accent)" }} />
                  </td>
                  <td style={{ padding: "10px 12px" }}>
                    <div style={{ fontWeight: 500, color: "var(--text)" }}>{m.name}</div>
                    <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2, fontFamily: "var(--font-mono)" }}>{m.uid} · {m.town}</div>
                  </td>
                  <td style={{ padding: "10px 12px", color: "var(--muted)", fontSize: 12 }}>{m.region}</td>
                  <td style={{ padding: "10px 12px", textAlign: "right", fontVariantNumeric: "tabular-nums", color: "var(--text)" }}>{m.schools}</td>
                  <td style={{ padding: "10px 12px" }}>
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text)" }}>{m.contact}</div>
                    <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>{m.contactName} · {m.contactRole}</div>
                  </td>
                  <td style={{ padding: "10px 12px" }}>
                    {m.verified
                      ? <Pill tone="ok">Verified</Pill>
                      : <Pill tone="warn">Scraped</Pill>
                    }
                    <div style={{ fontSize: 10.5, color: "var(--muted)", marginTop: 4, fontFamily: "var(--font-mono)" }}>{m.source}</div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {filtered.length === 0 && (
          <div style={{ padding: 40, textAlign: "center", color: "var(--muted)", fontSize: 13 }}>
            No trusts match your filters.
          </div>
        )}
      </div>
    </Card>
  );
}

function Th({ children, width, num }) {
  return <th style={{ width, padding: "8px 12px", textAlign: num ? "right" : "left", fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--muted)", fontWeight: 600, borderBottom: "1px solid var(--rule)" }}>{children}</th>;
}

function RecipientsScreen() {
  const [sel, setSel] = React.useState(window.MATS.filter((m) => m.verified).map((m) => m.uid));
  return (
    <div>
      <SectionTitle sub="Trust contacts auto-scraped from each MAT's published website. Re-scrape weekly." action={
        <div style={{ display: "flex", gap: 8 }}>
          <Button variant="secondary" icon={<Ico.Doc/>}>Import CSV</Button>
          <Button icon={<Ico.Check/>}>Re-scrape now</Button>
        </div>
      }>Recipients</SectionTitle>

      <Card style={{ marginBottom: 16 }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 0 }}>
          {[
            { label: "MATs in GIAS", v: "1,247", sub: "Last sync 04:00 UTC" },
            { label: "Contacts verified", v: "892", sub: "Confidence ≥ 0.85" },
            { label: "Contacts scraped", v: "267", sub: "0.5 ≤ conf < 0.85" },
            { label: "Bounces (30d)", v: "11", sub: "Pending re-scrape" }
          ].map((s, i) => (
            <div key={i} style={{ padding: 16, borderRight: i < 3 ? "1px solid var(--rule)" : "none" }}>
              <div style={{ fontSize: 11, textTransform: "uppercase", color: "var(--muted)", letterSpacing: "0.06em", fontWeight: 600 }}>{s.label}</div>
              <div style={{ fontSize: 26, fontWeight: 700, color: "var(--text)", marginTop: 4, letterSpacing: "-0.01em", fontVariantNumeric: "tabular-nums" }}>{s.v}</div>
              <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>{s.sub}</div>
            </div>
          ))}
        </div>
      </Card>

      <RecipientPicker selectedMats={sel} setSelectedMats={setSel} scope="mat" standalone />
    </div>
  );
}

Object.assign(window, { RecipientPicker, RecipientsScreen });
