/* Wellpaged Admin — Outreach (outreach.jsx)
   Our own creator outreach, sent through lemlist. Server rules live in
   functions/lib/outreach.js; this view only drives /api/admin/outreach.
   Runs inside an IIFE: components.jsx already declares useState/useEffect at the
   top level of the shared script scope, and a second const would be a SyntaxError
   that blanks the whole dashboard. Exported as window.OutreachView. */
(function () {
  const { useState, useEffect, useMemo } = React;
  const API = "/api/admin/outreach";
  const STATUS = ["new", "queued", "sent", "opened", "replied", "bounced", "unsubscribed", "suppressed", "converted"];
  const ST_CLASS = { new: "draft", queued: "building", sent: "pitch", opened: "staged", replied: "signed", converted: "live", bounced: "failed", unsubscribed: "failed", suppressed: "failed" };

  const getJSON = (q) => fetch(API + (q || ""), { credentials: "same-origin", headers: { Accept: "application/json" } })
    .then((r) => r.json().then((d) => ({ ok: r.ok && d && d.ok, d })).catch(() => ({ ok: false, d: {} })))
    .catch(() => ({ ok: false, d: { error: "Couldn’t reach the API." } }));
  const post = (body) => fetch(API, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })
    .then((r) => r.json().then((d) => ({ ok: r.ok && d && d.ok, d })).catch(() => ({ ok: false, d: {} })))
    .catch(() => ({ ok: false, d: { error: "Couldn’t reach the API." } }));
  const fmtN = (n) => (n == null ? "—" : n >= 1e6 ? (n / 1e6).toFixed(n >= 1e7 ? 0 : 1) + "M" : n >= 1e3 ? (n / 1e3).toFixed(n >= 1e4 ? 0 : 1) + "K" : String(n));
  const when = (t) => (t ? new Date(t).toLocaleString() : "—");
  const chunks = (arr, n) => { const out = []; for (let i = 0; i < arr.length; i += n) out.push(arr.slice(i, i + n)); return out; };
  const srcLabel = (s) => (s === "csv" ? "CSV" : s === "creator_marketplace" ? "Creator Marketplace" : s === "url" ? "their page" : s && s.indexOf("https://") === 0 ? (() => { try { return new URL(s).hostname; } catch (e) { return s; } })() : s || "");
  const csvCell = (v) => { let s = String(v == null ? "" : v); if (/^[=+\-@\t\r]/.test(s)) s = "'" + s; return /[",\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; };
  const download = (name, text) => { const a = document.createElement("a"); a.href = URL.createObjectURL(new Blob([text], { type: "text/csv" })); a.download = name; document.body.appendChild(a); a.click(); setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 500); };
  const readFile = (file) => new Promise((res, rej) => { const r = new FileReader(); r.onload = () => res(String(r.result || "")); r.onerror = rej; r.readAsText(file); });

  function Sticker({ s }) { return <span className={"st " + (ST_CLASS[s] || "draft")}><span className="dot"></span>{s}</span>; }

  function OutreachView({ role }) {
    const canEdit = role === "master" || role === "billing";
    const [tab, setTab] = useState("prospects");
    const [cfg, setCfg] = useState(null);
    const [list, setList] = useState(null);
    const [err, setErr] = useState(null);
    const [note, setNote] = useState(null);
    const [busy, setBusy] = useState(false);
    const [sel, setSel] = useState({});
    const [open, setOpen] = useState(null);
    const [campaigns, setCampaigns] = useState(null);
    const [camp, setCamp] = useState("");
    const [verify, setVerify] = useState(false);
    const [f, setF] = useState({ q: "", status: "", country: "", email: "", niche: "", tag: "", min: "", max: "" });

    const load = () => getJSON("").then(({ ok, d }) => {
      if (!ok) { setErr(d.error || "Couldn’t load outreach."); return; }
      setErr(null); setCfg(d.config); setList(d.prospects || []);
    });
    useEffect(() => { load(); }, []);
    // Writes answer with the summaries they touched; KV's list is eventually
    // consistent, so merge those rather than re-listing straight away.
    const merge = (rows) => { if (!rows || !rows.length) return; setList((cur) => { const by = {}; rows.forEach((r) => { by[r.id] = r; }); const seen = {}; const next = (cur || []).map((r) => { if (by[r.id]) { seen[r.id] = 1; return by[r.id]; } return r; }); rows.forEach((r) => { if (!seen[r.id]) next.unshift(r); }); return next; }); };
    const loadCampaigns = () => getJSON("?view=campaigns").then(({ ok, d }) => {
      if (!ok) { setNote({ err: true, msg: d.error || "Couldn’t load lemlist campaigns." }); setCampaigns([]); return; }
      setCampaigns(d.campaigns || []); if (!camp && d.campaigns && d.campaigns[0]) setCamp(d.campaigns[0].id);
    });

    const rows = useMemo(() => (list || []).filter((p) => {
      if (f.q) { const q = f.q.toLowerCase(); if (!((p.handle || "") + " " + (p.name || "") + " " + (p.email || "")).toLowerCase().includes(q)) return false; }
      if (f.status && p.status !== f.status) return false;
      if (f.country === "?" ? !!p.country : f.country === "other" ? (!p.country || p.country === "US" || p.country === "CA") : f.country && p.country !== f.country) return false;
      if (f.email === "yes" && !p.email) return false;
      if (f.email === "no" && p.email) return false;
      if (f.niche && !(p.niche || "").toLowerCase().includes(f.niche.toLowerCase())) return false;
      if (f.tag && !(p.tags || []).includes(f.tag.toLowerCase().trim())) return false;
      if (f.min !== "" && !(p.followers >= Number(f.min))) return false;
      if (f.max !== "" && !(p.followers <= Number(f.max))) return false;
      return true;
    }), [list, f]);
    const selIds = Object.keys(sel).filter((k) => sel[k]);
    const allOn = rows.length > 0 && rows.every((p) => sel[p.id]);
    const toggleAll = () => { const n = { ...sel }; rows.forEach((p) => { n[p.id] = !allOn; }); setSel(n); };

    // Runs a list through an action in server-sized chunks, collecting results.
    const run = async (label, ids, size, body, onEach) => {
      setBusy(true); setNote({ msg: label + "…" });
      const out = { ok: 0, fail: [] };
      const parts = chunks(ids, size);
      for (let i = 0; i < parts.length; i++) {
        setNote({ msg: label + "… " + Math.min((i + 1) * size, ids.length) + " / " + ids.length });
        const { ok, d } = await post(body(parts[i]));
        if (!ok) { out.fail.push(d.error || "failed"); if (d.code === "not_configured" || d.code === "no_postal_address") break; continue; }
        merge(d.prospects);
        if (onEach) onEach(d, out);
      }
      setBusy(false);
      return out;
    };

    const lookup = async (ids, url) => {
      const notes = [];
      const r = await run("Looking up", ids, 5, (part) => ({ action: "lookup", ids: part, url: url || undefined }), (d) => {
        (d.results || []).forEach((x) => { (x.notes || []).forEach((n) => notes.push((list.find((p) => p.id === x.id) || { handle: x.id }).handle + ": " + n)); });
      });
      setNote(r.fail.length ? { err: true, msg: r.fail.join("; ") } : { msg: "Lookup done." + (notes.length ? " " + notes.slice(0, 8).join(" · ") + (notes.length > 8 ? " …" : "") : "") });
      if (open && ids.includes(open.id)) openOne(open.id);
    };
    const bulk = async (fields, label) => {
      const r = await run(label, selIds, 100, (part) => ({ action: "bulk", ids: part, fields }));
      setNote(r.fail.length ? { err: true, msg: r.fail.join("; ") } : { msg: label + ": done." });
    };
    const build = async () => {
      if (!window.confirm("Build a spec page for " + selIds.length + " prospect(s)?\n\nEach is a real build on the runner (about 5 minutes, queued one after another). The pages are PRIVATE drafts — the prospect can’t open them from a plain link until they are launched, so nothing about them is put into lemlist.")) return;
      const done = [], failed = [];
      setBusy(true);
      for (let i = 0; i < selIds.length; i++) {
        setNote({ msg: "Starting builds… " + (i + 1) + " / " + selIds.length });
        const { ok, d } = await post({ action: "build", id: selIds[i] });
        if (ok) { merge(d.prospects); done.push(d.slug); } else failed.push(selIds[i] + " — " + (d.error || "failed"));
      }
      setBusy(false);
      setNote(failed.length ? { err: true, msg: (done.length ? "Started: " + done.join(", ") + ". " : "") + "Couldn’t start: " + failed.join("; ") } : { msg: done.length + " build(s) queued. Watch Builds." });
    };
    const push = async () => {
      if (!camp) { setNote({ err: true, msg: "Pick a lemlist campaign first." }); return; }
      if (!window.confirm("Push " + selIds.length + " prospect(s) to lemlist campaign " + ((campaigns || []).find((c) => c.id === camp) || { name: camp }).name + "?\n\nOnly US/Canada prospects with a sourced email who aren’t suppressed or already customers go; the rest come back with the reason." + (verify ? "\n\nEmail verification costs one lemlist credit per lead." : ""))) return;
      const refused = [];
      let pushed = 0;
      const r = await run("Pushing to lemlist", selIds, 15, (part) => ({ action: "push", ids: part, campaignId: camp, verifyEmail: verify }), (d) => {
        pushed += d.pushed || 0;
        (d.results || []).filter((x) => !x.ok).forEach((x) => refused.push(((list.find((p) => p.id === x.id) || {}).handle || x.id) + ": " + x.reason));
      });
      setNote({ err: !!(r.fail.length || refused.length), msg: pushed + " pushed." + (refused.length ? " Not pushed — " + refused.slice(0, 12).join(" · ") + (refused.length > 12 ? " … (" + refused.length + ")" : "") : "") + (r.fail.length ? " " + r.fail.join("; ") : "") });
    };
    const remove = async () => {
      if (!window.confirm("Delete " + selIds.length + " prospect record(s)? This doesn’t touch lemlist or the suppression list.")) return;
      setBusy(true);
      for (const part of chunks(selIds, 200)) await post({ action: "remove", ids: part });
      setBusy(false); setSel({}); setList((cur) => cur.filter((p) => !selIds.includes(p.id))); setNote({ msg: "Deleted." });
    };
    const sync = async () => {
      if (!camp) { setNote({ err: true, msg: "Pick a lemlist campaign first." }); return; }
      setBusy(true);
      let offset = 0, seen = 0, changed = 0, sup = 0, errs = [];
      for (let i = 0; i < 20 && offset !== null; i++) {
        setNote({ msg: "Syncing from lemlist… " + seen + " activities" });
        const { ok, d } = await post({ action: "sync", campaignId: camp, offset });
        if (!ok) { errs.push(d.error || "failed"); break; }
        merge(d.prospects); seen += d.seen; changed += d.changed; sup += d.suppressed; errs = errs.concat(d.errors || []);
        offset = d.next;
      }
      setBusy(false);
      setNote({ err: errs.length > 0, msg: "Sync: " + seen + " activities, " + changed + " status change(s), " + sup + " newly suppressed." + (errs.length ? " " + errs.join("; ") : "") });
    };
    const registerHook = async () => {
      if (!window.confirm("Register the webhook with lemlist?\n\n" + (cfg && cfg.hookUrl) + "\n\nlemlist will post every activity (sent, opened, replied, bounced, unsubscribed) there. Registering twice makes duplicate hooks — check lemlist’s settings first if unsure.")) return;
      setBusy(true);
      const { ok, d } = await post({ action: "registerHook", campaignId: camp || undefined });
      setBusy(false);
      setNote(ok ? { msg: "Webhook registered (" + (d.hookId || "ok") + ")." } : { err: true, msg: d.error || "Couldn’t register it." });
    };

    const openOne = (id) => getJSON("?id=" + encodeURIComponent(id)).then(({ ok, d }) => { if (ok) setOpen({ id, ...d }); else setNote({ err: true, msg: d.error || "Couldn’t open it." }); });

    if (err && !list) return <div className="panel"><div className="panel-head"><h2>Outreach</h2></div><div className="panel-body"><div className="tpl-err">{err}</div></div></div>;
    if (!list || !cfg) return <div className="panel"><div className="panel-head"><h2>Outreach</h2></div><div className="panel-body">Loading…</div></div>;

    return (
      <React.Fragment>
        <div className="otr-tabs">
          {[["prospects", "Prospects"], ["suppression", "Suppression list"], ["log", "Log"]].map(([k, l]) => (
            <button key={k} type="button" className={"btn " + (tab === k ? "primary" : "ghost")} onClick={() => setTab(k)}>{l}</button>
          ))}
        </div>
        <ConfigPanel cfg={cfg} />
        {note && <div className={note.err ? "tpl-err otr-note" : "d flat otr-note"}>{note.msg}</div>}
        {tab === "suppression" ? <SuppressionPanel canEdit={canEdit} cfg={cfg} />
          : tab === "log" ? <LogPanel />
          : (
          <React.Fragment>
            {canEdit && <AddPanel busy={busy} setBusy={setBusy} setNote={setNote} merge={merge} />}
            {canEdit && cfg.marketplace && <MarketplacePanel busy={busy} setBusy={setBusy} setNote={setNote} merge={merge} />}
            {canEdit && (
              <div className="panel"><div className="panel-head"><h2>lemlist</h2>
                <span className="tpl-hint" style={{ marginLeft: "auto" }}>{cfg.lemlist ? "Connected" : "Not configured: set LEMLIST_API_KEY"}</span></div>
                <div className="panel-body otr-row">
                  <button type="button" className="btn ghost" disabled={busy || !cfg.lemlist} onClick={loadCampaigns}>{campaigns ? "Reload campaigns" : "Load running campaigns"}</button>
                  {campaigns && (
                    <select value={camp} onChange={(e) => setCamp(e.target.value)} className="otr-in">
                      {!campaigns.length && <option value="">No running campaigns</option>}
                      {campaigns.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
                    </select>
                  )}
                  <label className="otr-check"><input type="checkbox" checked={verify} onChange={(e) => setVerify(e.target.checked)} /> Verify emails (1 lemlist credit each)</label>
                  <button type="button" className="btn ghost" disabled={busy || !camp} onClick={sync}>Sync from lemlist</button>
                  <button type="button" className="btn ghost" disabled={busy || !cfg.lemlist || !cfg.webhookSecret} title={cfg.webhookSecret ? "" : "Set LEMLIST_WEBHOOK_SECRET first"} onClick={registerHook}>Register webhook</button>
                </div>
              </div>
            )}
            <div className="panel">
              <div className="panel-head"><h2>Prospects <span className="muted-n">{rows.length}{rows.length !== list.length ? " of " + list.length : ""}</span></h2>
                <button type="button" className="btn ghost" style={{ marginLeft: "auto" }} disabled={busy} onClick={load}>Refresh</button></div>
              <div className="panel-body">
                <div className="otr-filters">
                  <input className="otr-in" placeholder="Search handle, name, email" value={f.q} onChange={(e) => setF({ ...f, q: e.target.value })} />
                  <select className="otr-in" value={f.status} onChange={(e) => setF({ ...f, status: e.target.value })}><option value="">Any status</option>{STATUS.map((s) => <option key={s} value={s}>{s}</option>)}</select>
                  <select className="otr-in" value={f.country} onChange={(e) => setF({ ...f, country: e.target.value })}><option value="">Any country</option><option value="US">US</option><option value="CA">CA</option><option value="?">Unknown</option><option value="other">Other</option></select>
                  <select className="otr-in" value={f.email} onChange={(e) => setF({ ...f, email: e.target.value })}><option value="">Email: any</option><option value="yes">Has email</option><option value="no">No email</option></select>
                  <input className="otr-in sm" placeholder="Niche" value={f.niche} onChange={(e) => setF({ ...f, niche: e.target.value })} />
                  <input className="otr-in sm" placeholder="Tag" value={f.tag} onChange={(e) => setF({ ...f, tag: e.target.value })} />
                  <input className="otr-in sm" type="number" min="0" placeholder="Min followers" value={f.min} onChange={(e) => setF({ ...f, min: e.target.value })} />
                  <input className="otr-in sm" type="number" min="0" placeholder="Max followers" value={f.max} onChange={(e) => setF({ ...f, max: e.target.value })} />
                </div>
                {canEdit && selIds.length > 0 && (
                  <div className="otr-bulk">
                    <strong>{selIds.length} selected</strong>
                    <button type="button" className="btn ghost" disabled={busy} onClick={() => lookup(selIds)}>Look up</button>
                    <select className="otr-in" value="" disabled={busy} onChange={(e) => { const v = e.target.value; if (v) bulk({ country: v === "-" ? "" : v }, "Setting country"); }}>
                      <option value="">Set country…</option><option value="US">US</option><option value="CA">CA</option><option value="GB">GB</option><option value="AU">AU</option><option value="-">Unknown</option>
                    </select>
                    <button type="button" className="btn ghost" disabled={busy} onClick={() => { const t = window.prompt("Tag(s) to add, comma-separated"); if (t) bulk({ addTags: t }, "Tagging"); }}>Add tag</button>
                    <button type="button" className="btn ghost" disabled={busy} onClick={build}>Build spec page</button>
                    <button type="button" className="btn primary" disabled={busy || !camp} title={camp ? "" : "Load lemlist campaigns and pick one first"} onClick={push}>Push to lemlist</button>
                    <button type="button" className="btn ghost tpl-danger" disabled={busy} onClick={remove}>Delete</button>
                    <button type="button" className="btn ghost" disabled={busy} onClick={() => setSel({})}>Clear</button>
                  </div>
                )}
                <div className="otr-scroll">
                  <table className="agy-table otr-table">
                    <thead><tr>
                      {canEdit && <th><input type="checkbox" checked={allOn} onChange={toggleAll} aria-label="Select all shown" /></th>}
                      <th>Creator</th><th>Followers</th><th>Country</th><th>Email</th><th>Niche · tags</th><th>Status</th><th>Spec page</th>
                    </tr></thead>
                    <tbody>
                      {rows.slice(0, 500).map((p) => (
                        <tr key={p.id} onClick={() => openOne(p.id)}>
                          {canEdit && <td onClick={(e) => e.stopPropagation()}><input type="checkbox" checked={!!sel[p.id]} onChange={(e) => setSel({ ...sel, [p.id]: e.target.checked })} aria-label={"Select " + (p.handle || p.email)} /></td>}
                          <td><div className="otr-who">{p.handle ? "@" + p.handle : <span className="muted">no handle</span>}</div><div className="agy-sub">{p.name}</div></td>
                          <td className="col-num">{fmtN(p.followers)}</td>
                          <td>{p.country || <span className="tpl-chip sunshine">set</span>}</td>
                          <td>{p.email ? <React.Fragment><div>{p.email}</div><div className="agy-sub">from {srcLabel(p.emailSource)}</div></React.Fragment> : <span className="muted">—</span>}</td>
                          <td>{p.niche}{p.tags && p.tags.length ? <div className="agy-sub">{p.tags.join(", ")}</div> : null}</td>
                          <td><Sticker s={p.status} /></td>
                          <td>{p.previewSlug ? <span className="agy-sub">{p.previewSlug} (draft)</span> : ""}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                  {rows.length > 500 && <div className="tpl-hint" style={{ marginTop: 8 }}>Showing the first 500 — narrow the filters to see the rest (selection works on what’s shown).</div>}
                  {!rows.length && <div className="tpl-hint" style={{ marginTop: 8 }}>No prospects{list.length ? " match these filters" : " yet — add some above"}.</div>}
                </div>
              </div>
            </div>
          </React.Fragment>
        )}
        {open && <Detail p={open} canEdit={canEdit} busy={busy} onClose={() => setOpen(null)} onLookup={(url) => lookup([open.id], url)}
          onSaved={(d) => { merge(d.prospects); openOne(open.id); }} setNote={setNote} />}
      </React.Fragment>
    );
  }

  function ConfigPanel({ cfg }) {
    return (
      <div className="panel"><div className="panel-head"><h2>Before you send</h2></div>
        <div className="panel-body otr-cfg">
          {cfg.missing.length > 0 && (
            <ul className="otr-missing">
              {cfg.missing.map((m) => <li key={m.set}><strong>{m.feature}</strong> — not configured: set <code>{m.set}</code></li>)}
            </ul>
          )}
          <p><strong>Postal address:</strong> {cfg.postalAddress || <span className="tpl-err">missing — pushing is blocked until OUTREACH_POSTAL_ADDRESS is set.</span>}</p>
          <p className="tpl-hint">The lemlist template must print this address and an unsubscribe link in every email — we can’t edit lemlist templates from here, so check the campaign before pushing. Only US and Canada prospects can be pushed; set the country on anyone marked “set”.</p>
          <p className="tpl-hint">Instagram data comes only from Meta’s Graph API (Business Discovery: public numbers, never an email). Emails come only from the creator’s own published page, a CSV you upload, or Creator Marketplace. <strong>TikTok creators are contacted through TikTok One’s own invites</strong> — nothing here reads TikTok.</p>
          <p className="tpl-hint">Spec pages are private drafts until the creator launches them, so <code>{"{{previewUrl}}"}</code> is empty for them — don’t make the template depend on it.</p>
        </div>
      </div>
    );
  }

  function AddPanel({ busy, setBusy, setNote, merge }) {
    const [handles, setHandles] = useState("");
    const [d, setD] = useState({ country: "", niche: "", tags: "" });
    const send = async (payload, label) => {
      setBusy(true);
      let offset = 0, added = 0, updated = 0, skipped = [];
      for (let i = 0; i < 40 && offset !== null; i++) {
        setNote({ msg: label + "… " + (added + updated) + " so far" });
        const { ok, d: r } = await post({ action: "import", ...payload, ...d, offset });
        if (!ok) { setBusy(false); setNote({ err: true, msg: r.error || "Import failed." }); return false; }
        merge(r.prospects); added += r.added; updated += r.updated; skipped = skipped.concat(r.skipped || []); offset = r.next;
      }
      setBusy(false);
      setNote({ err: skipped.length > 0, msg: added + " added, " + updated + " updated." + (skipped.length ? " Skipped: " + skipped.slice(0, 8).map((s) => "row " + s.row + " (" + s.reason + ")").join(", ") + (skipped.length > 8 ? " …" : "") : "") });
      return true;
    };
    return (
      <div className="panel"><div className="panel-head"><h2>Add prospects</h2></div>
        <div className="panel-body">
          <div className="tpl-new" style={{ marginBottom: 0 }}>
            <div className="tpl-new-row">
              <label><span>Instagram handles, one per line</span><textarea rows={4} value={handles} placeholder={"@jade.runs\nkai_cooks"} onChange={(e) => setHandles(e.target.value)} /></label>
              <div className="otr-col">
                <label><span>Country for these (US, CA, …) — blank = unknown</span><input value={d.country} maxLength={40} onChange={(e) => setD({ ...d, country: e.target.value })} /></label>
                <label><span>Niche</span><input value={d.niche} maxLength={40} onChange={(e) => setD({ ...d, niche: e.target.value })} /></label>
                <label><span>Tags (comma-separated)</span><input value={d.tags} maxLength={120} onChange={(e) => setD({ ...d, tags: e.target.value })} /></label>
              </div>
            </div>
            <div className="tpl-new-foot">
              <span className="tpl-hint">CSV columns (any order, loose names): handle, name, email, country, niche, tags, followers, website. A CSV email is recorded with source “CSV”. Same handle or email = the same prospect.</span>
              <span className="otr-row">
                <label className="btn ghost" style={{ cursor: busy ? "default" : "pointer" }}>Upload CSV<input type="file" accept=".csv,text/csv" hidden disabled={busy} onChange={(e) => { const file = e.target.files && e.target.files[0]; e.target.value = ""; if (file) readFile(file).then((csv) => send({ csv }, "Importing CSV")); }} /></label>
                <button type="button" className="btn primary" disabled={busy || !handles.trim()} onClick={() => send({ handles }, "Adding handles").then((ok) => { if (ok) setHandles(""); })}>Add handles</button>
              </span>
            </div>
          </div>
        </div>
      </div>
    );
  }

  function MarketplacePanel({ busy, setBusy, setNote, merge }) {
    const [q, setQ] = useState({ country: "US", minFollowers: "", maxFollowers: "", interests: "", keyword: "", hasEmail: true });
    const [res, setRes] = useState(null);
    const go = async (save) => {
      setBusy(true);
      const { ok, d } = await post({ action: "marketplace", filters: q, save });
      setBusy(false);
      if (!ok) { setNote({ err: true, msg: d.error || "Search failed." }); return; }
      setRes(d.creators || []);
      if (save) { merge(d.prospects); setNote({ msg: d.saved + " saved as prospects (email source: Creator Marketplace)." }); }
    };
    return (
      <div className="panel"><div className="panel-head"><h2>Creator Marketplace search</h2><span className="tpl-chip sunshine" style={{ marginLeft: "auto" }}>requires Meta approval</span></div>
        <div className="panel-body">
          <div className="otr-filters">
            <input className="otr-in sm" placeholder="Country" value={q.country} onChange={(e) => setQ({ ...q, country: e.target.value })} />
            <input className="otr-in sm" type="number" placeholder="Min followers" value={q.minFollowers} onChange={(e) => setQ({ ...q, minFollowers: e.target.value })} />
            <input className="otr-in sm" type="number" placeholder="Max followers" value={q.maxFollowers} onChange={(e) => setQ({ ...q, maxFollowers: e.target.value })} />
            <input className="otr-in" placeholder="Interests (comma-separated)" value={q.interests} onChange={(e) => setQ({ ...q, interests: e.target.value })} />
            <input className="otr-in" placeholder="Keyword" value={q.keyword} onChange={(e) => setQ({ ...q, keyword: e.target.value })} />
            <label className="otr-check"><input type="checkbox" checked={q.hasEmail} onChange={(e) => setQ({ ...q, hasEmail: e.target.checked })} /> Has public email</label>
            <button type="button" className="btn ghost" disabled={busy} onClick={() => go(false)}>Search</button>
            <button type="button" className="btn primary" disabled={busy || !res || !res.length} onClick={() => go(true)}>Save results</button>
          </div>
          {res && <div className="tpl-hint">{res.length ? res.map((c) => "@" + c.handle + " (" + fmtN(c.followers) + (c.email ? ", email" : "") + ")").join(" · ") : "No creators matched."}</div>}
        </div>
      </div>
    );
  }

  function Detail({ p, canEdit, busy, onClose, onLookup, onSaved, setNote }) {
    const r = p.prospect;
    const [e, setE] = useState({ name: r.name || "", country: r.country || "", niche: r.niche || "", tags: (r.tags || []).join(", "), website: r.website || "", notes: r.notes || "", handle: r.handle || "" });
    const [url, setUrl] = useState("");
    const [saving, setSaving] = useState(false);
    useEffect(() => { setE({ name: r.name || "", country: r.country || "", niche: r.niche || "", tags: (r.tags || []).join(", "), website: r.website || "", notes: r.notes || "", handle: r.handle || "" }); }, [p]);
    const save = async (fields) => {
      setSaving(true);
      const { ok, d } = await post({ action: "update", id: r.id, fields });
      setSaving(false);
      if (!ok) { setNote({ err: true, msg: d.error || "Couldn’t save." }); return; }
      onSaved(d);
    };
    const lead = async (op) => {
      if (op === "remove" && !window.confirm("Remove this lead from the lemlist campaign? lemlist marks a removed lead as unsubscribed from that campaign.")) return;
      setSaving(true);
      const { ok, d } = await post({ action: "lead", id: r.id, op });
      setSaving(false);
      if (!ok) { setNote({ err: true, msg: d.error || "lemlist refused it." }); return; }
      onSaved(d);
    };
    const fields = { name: e.name, country: e.country, niche: e.niche, tags: e.tags, website: e.website, notes: e.notes };
    if (r.id.charAt(0) === "~") fields.handle = e.handle;
    return (
      <div className="otr-scrim" onClick={onClose}>
        <aside className="otr-drawer" onClick={(ev) => ev.stopPropagation()} role="dialog" aria-label="Prospect">
          <div className="agy-head"><div><div className="agy-name">{r.handle ? "@" + r.handle : r.name || r.email}</div><div className="agy-sub">{r.name} · <Sticker s={r.status} /></div></div>
            <button type="button" className="btn ghost" onClick={onClose}>Close</button></div>
          <div className="otr-sec">
            <div><strong>Email:</strong> {r.email || "—"}{r.email && <span className="agy-sub"> · from {srcLabel(r.emailSource)} · {when(r.emailFoundAt)}</span>}{p.suppressed && <span className="tpl-chip coral" style={{ marginLeft: 6 }}>suppressed</span>}</div>
            {r.emailSource && r.emailSource.indexOf("https://") === 0 && <div className="agy-sub">Source page: {r.emailSource}</div>}
            {(r.emailCandidates || []).length > 0 && (
              <div className="agy-sub">Also found: {r.emailCandidates.map((c) => (
                <span key={c.email} style={{ marginRight: 8 }}>{c.email} ({srcLabel(c.source)}){canEdit && <button type="button" className="btn ghost otr-mini" disabled={saving} onClick={() => save({ email: c.email })}>use</button>}</span>
              ))}</div>
            )}
            {canEdit && r.email && <button type="button" className="btn ghost otr-mini" disabled={saving} onClick={() => { if (window.confirm("Clear this email? It can only come back from their page, a CSV, or Creator Marketplace.")) save({ email: "" }); }}>Clear email</button>}
            <div className="agy-sub">Followers {fmtN(r.followers)} · website {r.website || "—"} · looked up {when(r.lookedUpAt)}</div>
            {r.bio && <div className="agy-sub">{r.bio}</div>}
          </div>
          {canEdit && (
            <div className="otr-sec">
              <div className="otr-row">
                <input className="otr-in" style={{ flex: 1 }} placeholder="Or paste their link-in-bio / website URL" value={url} onChange={(ev) => setUrl(ev.target.value)} />
                <button type="button" className="btn ghost" disabled={busy || saving} onClick={() => onLookup(url.trim())}>{url.trim() ? "Read this page" : "Look up"}</button>
              </div>
              <div className="tpl-hint">Look up = Business Discovery for the public numbers, then their website for emails they publish there.</div>
            </div>
          )}
          {canEdit ? (
            <form className="tpl-edit" onSubmit={(ev) => { ev.preventDefault(); save(fields); }}>
              <div className="tpl-new-row">
                <label><span>Name</span><input value={e.name} maxLength={80} onChange={(ev) => setE({ ...e, name: ev.target.value })} /></label>
                <label><span>Country (US, CA, …)</span><input value={e.country} maxLength={40} onChange={(ev) => setE({ ...e, country: ev.target.value })} /></label>
                <label><span>Niche</span><input value={e.niche} maxLength={40} onChange={(ev) => setE({ ...e, niche: ev.target.value })} /></label>
                {r.id.charAt(0) === "~" && <label><span>Instagram handle</span><input value={e.handle} maxLength={40} onChange={(ev) => setE({ ...e, handle: ev.target.value })} /></label>}
              </div>
              <label><span>Tags</span><input value={e.tags} maxLength={200} onChange={(ev) => setE({ ...e, tags: ev.target.value })} /></label>
              <label><span>Website</span><input value={e.website} maxLength={300} onChange={(ev) => setE({ ...e, website: ev.target.value })} /></label>
              <label><span>Notes (operators only)</span><textarea rows={3} value={e.notes} maxLength={2000} onChange={(ev) => setE({ ...e, notes: ev.target.value })} /></label>
              <button className="btn primary" disabled={saving}>{saving ? "Saving…" : "Save"}</button>
            </form>
          ) : null}
          <div className="otr-sec">
            <div><strong>lemlist:</strong> {r.lemlist ? r.lemlist.campaignId + (r.lemlist.leadId ? " · lead " + r.lemlist.leadId : " · lead id pending (Sync)") + (r.lemlist.paused ? " · paused" : "") : "not pushed"}</div>
            {canEdit && r.lemlist && r.lemlist.leadId && (
              <div className="otr-row">
                <button type="button" className="btn ghost otr-mini" disabled={saving} onClick={() => lead(r.lemlist.paused ? "resume" : "pause")}>{r.lemlist.paused ? "Resume" : "Pause"}</button>
                <button type="button" className="btn ghost otr-mini tpl-danger" disabled={saving} onClick={() => lead("remove")}>Remove from campaign</button>
              </div>
            )}
            <div><strong>Spec page:</strong> {r.previewSlug ? <React.Fragment><a href={"https://wellpaged.com/" + r.previewSlug + "/"} target="_blank" rel="noopener">{r.previewSlug}</a> <span className="agy-sub">(private draft — opens for operators; the creator can’t see it from a plain link until it launches)</span></React.Fragment> : "—"}</div>
          </div>
          <div className="otr-sec">
            <strong>History</strong>
            <ul className="otr-events">{(r.events || []).slice().reverse().map((ev, i) => <li key={i}><span className="agy-sub">{when(ev.at)}</span> {ev.type}{ev.detail ? " — " + ev.detail : ""}{ev.by ? <span className="agy-sub"> · {ev.by}</span> : null}</li>)}</ul>
          </div>
        </aside>
      </div>
    );
  }

  function SuppressionPanel({ canEdit, cfg }) {
    const [rows, setRows] = useState(null);
    const [q, setQ] = useState("");
    const [add, setAdd] = useState("");
    const [reason, setReason] = useState("asked not to be contacted");
    const [msg, setMsg] = useState(null);
    const [busy, setBusy] = useState(false);
    const load = () => getJSON("?view=suppression").then(({ ok, d }) => { if (ok) setRows(d.suppression || []); else setMsg({ err: true, msg: d.error || "Couldn’t load it." }); });
    useEffect(() => { load(); }, []);
    const addMany = async (emails) => {
      setBusy(true);
      const { ok, d } = await post({ action: "suppress", emails, reason });
      setBusy(false);
      if (!ok) { setMsg({ err: true, msg: d.error || "Couldn’t add them." }); return; }
      setMsg({ err: !!d.mirrorError, msg: d.added + " added." + (d.lemlist ? (d.mirrorError ? " lemlist mirror FAILED: " + d.mirrorError : " Mirrored to lemlist’s unsubscribes.") : " (lemlist not configured — not mirrored.)") });
      setAdd(""); load();
    };
    const remove = async (email) => {
      if (!window.confirm("Remove " + email + " from the suppression list?\n\nOnly do this if they asked to hear from us again. It is logged with your name.")) return;
      const why = window.prompt("Why? (goes in the log)");
      if (!why || why.trim().length < 3) return;
      setBusy(true);
      const { ok, d } = await post({ action: "unsuppress", email, confirm: true, why });
      setBusy(false);
      setMsg(ok ? { msg: d.note } : { err: true, msg: d.error || "Couldn’t remove it." });
      load();
    };
    const exportCsv = () => download("wellpaged-suppression.csv", "email,reason,source,added\n" + (rows || []).map((s) => [s.email, s.reason, s.source, s.at ? new Date(s.at).toISOString() : ""].map(csvCell).join(",")).join("\n") + "\n");
    const shown = (rows || []).filter((s) => !q || s.email.includes(q.toLowerCase()));
    return (
      <div className="panel"><div className="panel-head"><h2>Suppression list <span className="muted-n">{rows ? rows.length : ""}</span></h2>
        <button type="button" className="btn ghost" style={{ marginLeft: "auto" }} disabled={!rows} onClick={exportCsv}>Export CSV</button></div>
        <div className="panel-body">
          <p className="tpl-hint">Checked before every push. Bounces and unsubscribes from lemlist land here automatically; additions here are mirrored to lemlist’s unsubscribe list{cfg.lemlist ? "" : " (once LEMLIST_API_KEY is set)"}.</p>
          {msg && <div className={msg.err ? "tpl-err" : "d flat"} style={{ margin: "8px 0" }}>{msg.msg}</div>}
          {canEdit && (
            <div className="otr-row" style={{ marginBottom: 12, alignItems: "flex-start" }}>
              <textarea className="otr-in" rows={2} style={{ flex: 1, minWidth: 240 }} placeholder="Emails to suppress (any separator)" value={add} onChange={(e) => setAdd(e.target.value)} />
              <input className="otr-in" value={reason} maxLength={40} onChange={(e) => setReason(e.target.value)} title="Reason" />
              <button type="button" className="btn primary" disabled={busy || !add.trim()} onClick={() => addMany(add)}>Suppress</button>
              <label className="btn ghost" style={{ cursor: "pointer" }}>Import file<input type="file" accept=".csv,.txt,text/csv,text/plain" hidden onChange={(e) => { const file = e.target.files && e.target.files[0]; e.target.value = ""; if (file) readFile(file).then((t) => addMany((t.match(/[^\s,;"'<>]+@[^\s,;"'<>]+\.[a-z]{2,24}/gi) || []).slice(0, 2000))); }} /></label>
            </div>
          )}
          <input className="otr-in" placeholder="Search" value={q} onChange={(e) => setQ(e.target.value)} style={{ marginBottom: 8 }} />
          {!rows ? <div>Loading…</div> : (
            <table className="agy-table"><thead><tr><th>Email</th><th>Reason</th><th>Source</th><th>Added</th>{canEdit && <th></th>}</tr></thead>
              <tbody>{shown.slice(0, 500).map((s) => (
                <tr key={s.email}><td>{s.email}</td><td>{s.reason}</td><td>{s.source}</td><td className="agy-sub">{when(s.at)}</td>
                  {canEdit && <td><button type="button" className="btn ghost otr-mini tpl-danger" disabled={busy} onClick={() => remove(s.email)}>Remove</button></td>}</tr>
              ))}</tbody></table>
          )}
        </div>
      </div>
    );
  }

  function LogPanel() {
    const [rows, setRows] = useState(null);
    useEffect(() => { getJSON("?view=audit").then(({ ok, d }) => setRows(ok ? d.audit || [] : [])); }, []);
    return (
      <div className="panel"><div className="panel-head"><h2>Operator log</h2></div>
        <div className="panel-body">{!rows ? "Loading…" : !rows.length ? <span className="tpl-hint">Nothing yet.</span> : (
          <table className="agy-table"><thead><tr><th>When</th><th>Who</th><th>What</th><th>Detail</th></tr></thead>
            <tbody>{rows.map((e, i) => <tr key={i}><td className="agy-sub">{when(e.at)}</td><td>{e.by || "—"}</td><td>{e.action}{e.email ? " · " + e.email : ""}{e.id ? " · " + e.id : ""}</td><td>{e.detail}</td></tr>)}</tbody></table>
        )}</div>
      </div>
    );
  }

  window.OutreachView = OutreachView;
})();
