/* ============================================================
   Agents — every AI tool running the engine, fully configurable.
   Click an agent to open its rules drawer.
   ============================================================ */
function agentList() {
  const W = window.WTC;
  const drafts = W.threads.filter((t) => t.hasDraft).length;
  const needsAttn = W.threads.filter((t) => t.triage === "needs_attention").length;
  const needsEnrich = W.contacts.filter((c) => !c.verified).length;
  return [
    { id: "prospector", name: "Prospector", icon: "radar", status: "active", model: "Claude + web",
      desc: "Sources new targets from event rosters, win-lookalikes and agency unlocks.",
      stat: W.scouting.length, statLbl: "sourced", now: "Mapping the F1 Vegas sponsor roster", last: "12m ago", to: "scouting",
      config: [
        { type: "chips", key: "lanes", label: "Lanes to scout", options: ["Brands", "Agencies", "Events", "Travel"], default: ["Brands", "Agencies", "Events", "Travel"] },
        { type: "slider", key: "perDay", label: "New prospects per day", min: 1, max: 20, default: 8 },
        { type: "slider", key: "minFit", label: "Minimum fit score", min: 50, max: 95, default: 75, unit: "" },
        { type: "toggle", key: "autoAdd", label: "Auto-add prospects scoring ≥ 90", default: false },
        { type: "select", key: "refresh", label: "Refresh cadence", options: ["Hourly", "Daily", "Weekly"], default: "Daily" },
        { type: "text", key: "extra", label: "Extra instruction to Claude", placeholder: "e.g. prioritize brands with Super Bowl history" },
      ] },
    { id: "researcher", name: "Researcher", icon: "search", status: "active", model: "Claude",
      desc: "Pulls company + contact intel before every send so each note is personalized.",
      stat: W.contacts.length, statLbl: "profiles", now: "Enriching pitch intel for 3 contacts", last: "4m ago", to: "contacts",
      config: [
        { type: "select", key: "depth", label: "Research depth", options: ["Light", "Standard", "Deep"], default: "Standard" },
        { type: "chips", key: "collect", label: "Always collect", options: ["Why-now signal", "Decision-maker", "Past activations", "Recent news", "Socials"], default: ["Why-now signal", "Decision-maker", "Past activations"] },
        { type: "toggle", key: "blockNoEmail", label: "Block sends with no verified email", default: true },
      ] },
    { id: "drafter", name: "Drafter", icon: "sparkles", status: "active", model: "Claude",
      desc: "Writes every outreach and reply in your voice — your marquee credits, the per-lane angle, the prior thread.",
      stat: drafts, statLbl: "drafts ready", now: "Drafting replies to today's responders", last: "just now", to: "inbox",
      config: [
        { type: "select", key: "tone", label: "Default tone", options: ["Warm", "Direct", "Punchy", "Formal"], default: "Warm" },
        { type: "slider", key: "maxWords", label: "Max length", min: 60, max: 180, default: 110, unit: " words" },
        { type: "chips", key: "credits", label: "Credits to weave in", options: ["Rocket SB", "Invisalign SB", "Vita Coco", "Red Bull"], default: ["Rocket SB", "Invisalign SB", "Vita Coco"] },
        { type: "radio", key: "mode", label: "Default send mode", options: ["Manual approve", "Auto-send"], default: "Manual approve" },
        { type: "toggle", key: "thread", label: "Reply in-thread to prior messages", default: true },
      ] },
    { id: "triage", name: "Reply Triage", icon: "reply", status: "active", model: "Claude",
      desc: "Reads inbound, pauses the cadence, and routes replies to Interested / Not now / Pass.",
      stat: needsAttn, statLbl: "need attention", now: "Watching 3 inboxes for replies", last: "2m ago", to: "inbox",
      config: [
        { type: "toggle", key: "pause", label: "Pause cadence the moment they reply", default: true },
        { type: "toggle", key: "autoClassify", label: "Auto-classify replies", default: true },
        { type: "select", key: "attnRule", label: "Flag 'needs attention' on", options: ["Any reply", "Questions only", "Negative / objection"], default: "Any reply" },
        { type: "toggle", key: "notify", label: "Push notify on a hot reply", default: true },
      ] },
    { id: "cadence", name: "Cadence Engine", icon: "sequence", status: "active", model: "Rules + Claude",
      desc: "Schedules every follow-up and resurfaces it as a ready draft — you never track dates.",
      stat: W.kpis.dueToday, statLbl: "due today", now: "Queued today's follow-ups", last: "6m ago", to: "campaigns",
      config: [
        { type: "slider", key: "cap", label: "Daily send cap (per inbox)", min: 5, max: 100, default: 30 },
        { type: "select", key: "window", label: "Send window", options: ["Mornings", "Business hours", "Anytime"], default: "Business hours" },
        { type: "toggle", key: "skipWeekend", label: "Skip weekends", default: true },
        { type: "select", key: "tz", label: "Timezone", options: ["PT", "MT", "CT", "ET"], default: "PT" },
      ] },
    { id: "deliver", name: "Deliverability Monitor", icon: "shield", status: W.deliverability.healthScore < 70 ? "warn" : "active", model: "Claude",
      desc: "Watches inbox health across domains and warns on spam, bounces and DNS issues.",
      stat: W.deliverability.healthScore, statLbl: "health score", now: "Flagged spam on wtc-studio.io", last: "1h ago", to: "inboxes",
      config: [
        { type: "slider", key: "spam", label: "Spam-rate alert threshold", min: 1, max: 30, default: 15, unit: "%" },
        { type: "slider", key: "bounce", label: "Bounce alert threshold", min: 1, max: 10, default: 3, unit: "%" },
        { type: "toggle", key: "autoPause", label: "Auto-pause an inbox over threshold", default: true },
        { type: "toggle", key: "dns", label: "Daily SPF / DKIM / DMARC checks", default: true },
      ] },
    { id: "enrich", name: "Enrichment (Clay)", icon: "upload", status: needsEnrich > 0 ? "warn" : "idle", model: "Clay round-trip",
      desc: "Exports unverified contacts to Clay for emails, then re-ingests the enriched rows.",
      stat: needsEnrich, statLbl: "need emails", now: needsEnrich > 0 ? `${needsEnrich} contacts queued for enrichment` : "Up to date", last: "today", to: "contacts",
      config: [
        { type: "select", key: "provider", label: "Provider", options: ["Clay", "Apollo", "Manual only"], default: "Clay" },
        { type: "chips", key: "fields", label: "Fields to enrich", options: ["Email", "Phone", "LinkedIn", "Title", "Company size"], default: ["Email", "LinkedIn", "Title"] },
        { type: "slider", key: "batch", label: "Batch size", min: 10, max: 500, default: 100 },
        { type: "toggle", key: "autoExport", label: "Auto-export unverified daily", default: true },
      ] },
  ];
}
const AGENT_STAT = { active: { label: "Active", color: "var(--green)" }, warn: { label: "Needs attention", color: "var(--amber)" }, idle: { label: "Idle", color: "var(--text-3)" } };

function AgentField({ field, value, onChange }) {
  if (field.type === "toggle") return (
    <div className="ag-field ag-field--row">
      <span className="ag-flabel">{field.label}</span>
      <button className={"agent-toggle" + (value ? " on" : "")} onClick={() => onChange(!value)}><span className="agent-knob"></span></button>
    </div>
  );
  if (field.type === "slider") return (
    <div className="ag-field">
      <div className="ag-slider-head"><span className="ag-flabel">{field.label}</span><span className="num ag-sval">{value}{field.unit || ""}</span></div>
      <input type="range" className="ag-range" min={field.min} max={field.max} value={value} onChange={(e) => onChange(+e.target.value)} />
    </div>
  );
  if (field.type === "select") return (
    <div className="ag-field"><span className="ag-flabel">{field.label}</span>
      <select className="ag-select" value={value} onChange={(e) => onChange(e.target.value)}>{field.options.map((o) => <option key={o} value={o}>{o}</option>)}</select>
    </div>
  );
  if (field.type === "radio") return (
    <div className="ag-field"><span className="ag-flabel">{field.label}</span>
      <div style={{ marginTop: 7 }}><Segmented value={value} onChange={onChange} options={field.options} /></div>
    </div>
  );
  if (field.type === "chips") return (
    <div className="ag-field"><span className="ag-flabel">{field.label}</span>
      <div className="facet-chips" style={{ marginTop: 8 }}>{field.options.map((o) => <button key={o} className="facet-chip" data-on={value.includes(o) || undefined} onClick={() => onChange(value.includes(o) ? value.filter((x) => x !== o) : [...value, o])}>{o}</button>)}</div>
    </div>
  );
  if (field.type === "text") return (
    <div className="ag-field"><span className="ag-flabel">{field.label}</span>
      <textarea className="seq-template" style={{ minHeight: 60, marginTop: 7 }} value={value || ""} placeholder={field.placeholder} onChange={(e) => onChange(e.target.value)} /></div>
  );
  return null;
}

function AgentDrawer({ agent, cfg, setCfg, onClose, flash }) {
  const st = AGENT_STAT[agent.status];
  const val = (f) => (cfg[f.key] !== undefined ? cfg[f.key] : f.default);
  return (
    <div className="drawer-scrim" onClick={onClose}>
      <div className="contact-drawer" onClick={(e) => e.stopPropagation()} style={{ width: "min(440px, 94%)" }}>
        <button className="btn btn--ghost btn--icon drawer-x" onClick={onClose}><Icon name="x" size={18} /></button>
        <div className="cd-head" style={{ alignItems: "center" }}>
          <div className="agent-ico" style={{ width: 46, height: 46 }}><Icon name={agent.icon} size={20} /></div>
          <div>
            <div style={{ fontSize: 17, fontWeight: 700 }}>{agent.name}</div>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 4 }}>
              <span className="agent-status" style={{ color: st.color }}><span className="stagedot" style={{ background: st.color }}></span>{st.label}</span>
              <span className="agent-model"><Icon name="sparkles" size={11} /> {agent.model}</span>
            </div>
          </div>
        </div>
        <div style={{ fontSize: 12.5, color: "var(--text-2)", lineHeight: 1.5, margin: "14px 0 4px" }}>{agent.desc}</div>
        <div className="cd-section" style={{ borderTop: "1px solid var(--line-soft)" }}>
          <div className="cd-section-label">Rules</div>
          {agent.config.map((f) => <AgentField key={f.key} field={f} value={val(f)} onChange={(v) => setCfg(agent.id, f.key, v)} />)}
        </div>
        <button className="btn btn--primary" style={{ width: "100%", marginTop: 4 }} onClick={() => { flash(agent.name + " rules saved"); onClose(); }}><Icon name="check" size={15} /> Save rules</button>
      </div>
    </div>
  );
}

function Agents({ go }) {
  const live = !!(window.claude && window.claude.complete);
  const agents = React.useMemo(agentList, []);
  const [on, setOn] = React.useState(() => Object.fromEntries(agents.map((a) => [a.id, true])));
  const [cfg, setCfg] = React.useState({});
  const [openId, setOpenId] = React.useState(null);
  const [toast, setToast] = React.useState(null);
  const flash = (m) => { setToast(m); setTimeout(() => setToast(null), 1700); };
  const setField = (aid, key, v) => setCfg((c) => ({ ...c, [aid]: { ...(c[aid] || {}), [key]: v } }));
  const open = agents.find((a) => a.id === openId);

  return (
    <div className="surface-scroll">
      <div className="today-head">
        <div>
          <h1 className="page-title">Agents</h1>
          <p className="page-sub">The AI tools running your outbound — click any agent to fully customize its rules.</p>
        </div>
        <span className="live-tag" style={{ height: 34, padding: "0 13px" }}><span className="stagedot" style={{ background: live ? "var(--green)" : "var(--text-3)" }}></span>{live ? "Claude connected" : "Demo brain"}</span>
      </div>

      <div className="agent-grid">
        {agents.map((a) => {
          const st = AGENT_STAT[a.status];
          const active = on[a.id];
          return (
            <div key={a.id} className="agent-card lift" data-off={!active || undefined} onClick={() => setOpenId(a.id)} style={{ cursor: "pointer" }}>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
                <div className="agent-ico"><Icon name={a.icon} size={18} /></div>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{ fontSize: 14.5, fontWeight: 670 }}>{a.name}</span>
                    <span className="agent-status" style={{ color: active ? st.color : "var(--text-3)" }}><span className="stagedot" style={{ background: active ? st.color : "var(--text-3)" }}></span>{active ? st.label : "Paused"}</span>
                  </div>
                  <div className="agent-model"><Icon name="sparkles" size={11} /> {a.model}</div>
                </div>
                <button className={"agent-toggle" + (active ? " on" : "")} onClick={(e) => { e.stopPropagation(); setOn((o) => ({ ...o, [a.id]: !o[a.id] })); }} title={active ? "Pause agent" : "Resume agent"}><span className="agent-knob"></span></button>
              </div>
              <div className="agent-desc">{a.desc}</div>
              <div className="agent-now" data-muted={!active || undefined}>
                <span className="agent-pulse" style={{ background: active ? "var(--accent)" : "var(--text-3)" }}></span>
                {active ? a.now : "Paused — not running"}
              </div>
              <div className="agent-foot">
                <div><span className="num agent-stat">{a.stat}</span> <span className="agent-stat-lbl">{a.statLbl}</span></div>
                <span style={{ flex: 1 }}></span>
                <button className="btn btn--sm btn--ghost" onClick={(e) => { e.stopPropagation(); setOpenId(a.id); }}><Icon name="settings" size={13} /> Customize</button>
              </div>
            </div>
          );
        })}
      </div>
      {open && <AgentDrawer agent={open} cfg={cfg[open.id] || {}} setCfg={setField} onClose={() => setOpenId(null)} flash={flash} />}
      {toast && <div className="toast">{toast}</div>}
    </div>
  );
}
Object.assign(window, { Agents });
