// screen-agent.jsx — agent / ICP configuration + uploaded context
const { useState: useStateA } = React;

function ChipList({ items, onRemove, accent }) {
  return (
    <div className="row gap-8" style={{ flexWrap: "wrap" }}>
      {items.map((it, i) => (
        <span key={i} className={"chip " + (accent ? "chip-accent" : "")}>
          {it}
          <span className="x" onClick={() => onRemove(i)}><Icon name="x" size={12} /></span>
        </span>
      ))}
      <button className="chip" style={{ borderStyle: "dashed", cursor: "pointer", color: "var(--gray-500)" }}><Icon name="plus" size={12} />Add</button>
    </div>
  );
}

function AgentScreen({ toast }) {
  const [tab, setTab] = useStateA("icp");
  const [icp, setIcp] = useStateA(window.ICP);
  const [tone, setTone] = useStateA(window.ICP.tone);
  const rm = (key) => (i) => setIcp(p => ({ ...p, [key]: p[key].filter((_, j) => j !== i) }));

  return (
    <div className="page">
      <div className="page-head row" style={{ justifyContent: "space-between", alignItems: "flex-start" }}>
        <div>
          <h2>Agent configuration</h2>
          <p>Tune what the agent looks for and how it speaks. "Training" here means configuration plus retrieval over your uploaded context — no model fine-tuning.</p>
        </div>
        <button className="btn btn-primary" onClick={() => toast("Agent configuration saved")}><Icon name="check" size={15} />Save changes</button>
      </div>

      <div className="tabs">
        {[["icp","Ideal customer profile"],["voice","Brand & tone"],["sources","Source preferences"]].map(([k,l]) => (
          <button key={k} className={"tab " + (tab===k?"active":"")} onClick={()=>setTab(k)}>{l}</button>
        ))}
      </div>

      {tab === "icp" && (
        <div className="grid-2" style={{ alignItems: "start" }}>
          <div className="card card-pad">
            <div className="field">
              <label>Services offered</label>
              <ChipList items={icp.services} onRemove={rm("services")} accent />
            </div>
            <div className="field">
              <label>Target segments</label>
              <div className="hint" style={{ marginTop: 0, marginBottom: 8 }}>Verticals the agent prioritizes when scoring fit.</div>
              <ChipList items={icp.segments} onRemove={rm("segments")} />
            </div>
            <div className="field">
              <label>Target geographies</label>
              <ChipList items={icp.geos} onRemove={rm("geos")} />
            </div>
            <div className="grid-2">
              <div className="field"><label>Min. employees</label><input className="input" defaultValue={icp.sizeMin} /></div>
              <div className="field"><label>Max. employees</label><input className="input" defaultValue={icp.sizeMax} /></div>
            </div>
          </div>
          <div className="col gap-16">
            <div className="card card-pad">
              <div className="field" style={{ marginBottom: 0 }}>
                <label className="row gap-6"><Icon name="bolt" size={14} color="var(--amber)" />Buying signals to watch</label>
                <div className="hint" style={{ marginTop: 0, marginBottom: 8 }}>The agent boosts scores when it finds evidence of these.</div>
                <ChipList items={icp.signals} onRemove={rm("signals")} accent />
              </div>
            </div>
            <div className="card card-pad">
              <div className="field" style={{ marginBottom: 0 }}>
                <label className="row gap-6"><Icon name="x" size={14} color="var(--red)" />Exclusion rules</label>
                <div className="hint" style={{ marginTop: 0, marginBottom: 8 }}>Companies matching these are filtered out or down-scored.</div>
                <ChipList items={icp.exclusions} onRemove={rm("exclusions")} />
              </div>
            </div>
            <div className="card card-pad" style={{ background: "var(--accent-50)", borderColor: "var(--accent-200)" }}>
              <div className="row gap-8" style={{ alignItems: "flex-start" }}>
                <Icon name="info" size={16} color="var(--accent)" />
                <div style={{ fontSize: 13, color: "var(--gray-700)", lineHeight: 1.5 }}>
                  Changes apply to the <strong>next agent run</strong>. Already-scored leads keep their original score and evidence for auditability.
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {tab === "voice" && (
        <div className="grid-2" style={{ alignItems: "start" }}>
          <div className="card card-pad">
            <div className="field">
              <label>Tone & voice guidance</label>
              <div className="hint" style={{ marginTop: 0, marginBottom: 8 }}>Shapes how the agent writes rationale and recommended next actions.</div>
              <textarea className="textarea" value={tone} onChange={e => setTone(e.target.value)} style={{ minHeight: 110 }} />
            </div>
            <div className="field">
              <label>Company one-liner</label>
              <input className="input" defaultValue="ABC B2B Company keeps Carolina healthcare, legal & finance teams secure, compliant, and running — without an in-house IT department." />
            </div>
            <div className="field" style={{ marginBottom: 0 }}>
              <label>Words & phrases to avoid</label>
              <ChipList items={["synergy","cutting-edge","best-in-class","leverage (as verb)"]} onRemove={()=>{}} />
            </div>
          </div>
          <div className="card card-pad">
            <div className="section-title">Preview — generated outreach angle</div>
            <div className="evidence" style={{ background: "var(--gray-50)" }}>
              <div className="src"><Icon name="sparkle" size={13} color="var(--accent)" />Sample for Riverside Surgical Center</div>
              <div className="quote" style={{ color: "var(--gray-700)" }}>
                "Hi Joel — surgical centers can't afford downtime, and the recent ransomware activity around Charlotte makes patient-data protection urgent. We help ASCs your size hit uptime SLAs and stay HIPAA-ready without hiring an IT team. Open to a same-week risk review?"
              </div>
            </div>
            <div className="hint">Tone applied: consultative, low-jargon, risk-led. Regenerates when you edit the guidance.</div>
          </div>
        </div>
      )}

      {tab === "sources" && (
        <div className="card">
          <div className="card-head"><Icon name="db" size={16} color="var(--gray-500)" /><h3>Source priority & weighting</h3><span className="sub">Higher weight = the agent trusts and draws more from that source</span></div>
          <div className="card-pad col gap-16">
            {window.CONNECTORS.sources.filter(s=>s.status==="connected").map((s,i) => (
              <div key={i} className="row gap-12">
                <span className="intg-logo" style={{ background: s.color, width: 34, height: 34, fontSize: 12 }}>{s.short}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: 13.5 }}>{s.name}</div>
                  <div className="muted" style={{ fontSize: 12 }}>{s.kind}</div>
                </div>
                <input type="range" min="0" max="100" defaultValue={[90,70,95,60][i] || 50} style={{ width: 180, accentColor: "var(--accent)" }} />
                <span className="badge b-approved"><span className="dot" style={{ background: "var(--green)" }} />Active</span>
              </div>
            ))}
            <div className="hint">The agent always cites which source produced each field, and stores a timestamp so you can audit freshness.</div>
          </div>
        </div>
      )}
    </div>
  );
}

// ---------- Context documents ----------
function ContextScreen({ toast }) {
  const [docs, setDocs] = useStateA(window.DOCS);
  const [q, setQ] = useStateA("");
  const shown = docs.filter(d => d.name.toLowerCase().includes(q.toLowerCase()));
  function remove(id) { setDocs(p => p.filter(d => d.id !== id)); toast("Document removed from context"); }

  return (
    <div className="page">
      <div className="page-head row" style={{ justifyContent: "space-between", alignItems: "flex-start" }}>
        <div>
          <h2>Knowledge & context</h2>
          <p>Upload the material your agent retrieves over: service descriptions, case studies, messaging, qualification criteria, and target lists. Versioned and removable.</p>
        </div>
        <button className="btn btn-primary" onClick={() => toast("Upload dialog opened")}><Icon name="upload" size={15} />Upload document</button>
      </div>

      <div className="stats mb-16" style={{ gridTemplateColumns: "repeat(4,1fr)" }}>
        <Stat label="Documents" value={docs.length} icon="docs" />
        <Stat label="Indexed chunks" value={fmtNum(docs.reduce((s,d)=>s+d.chunks,0))} icon="db" />
        <Stat label="Storage used" value="6.2 MB" icon="file" />
        <Stat label="Last updated" value="2d ago" icon="clock" />
      </div>

      <div className="dropzone mb-16" onClick={() => toast("Upload dialog opened")}>
        <Icon name="upload" size={26} color="var(--gray-400)" />
        <div style={{ fontWeight: 600, color: "var(--gray-600)", marginTop: 8 }}>Drop files or click to upload</div>
        <div style={{ fontSize: 12.5 }}>PDF, DOCX, CSV, TXT · up to 25 MB · indexed automatically for retrieval</div>
      </div>

      <div className="card">
        <div className="card-head">
          <h3>Indexed documents</h3>
          <div className="spacer" />
          <div className="search" style={{ width: 220 }}><Icon name="search" size={14} /><input placeholder="Search context…" value={q} onChange={e=>setQ(e.target.value)} /></div>
        </div>
        <div className="table-wrap">
          <table className="tbl">
            <thead><tr><th>Document</th><th>Type</th><th>Version</th><th>Chunks</th><th>Size</th><th>Updated</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {shown.map(d => (
                <tr key={d.id} style={{ cursor: "default" }}>
                  <td><div className="cell-co"><span className="co-logo" style={{ background: "var(--gray-100)", color: "var(--gray-500)" }}><Icon name="file" size={15} color="var(--gray-500)" /></span><div className="co-name">{d.name}</div></div></td>
                  <td><span className="badge b-gray">{d.type}</span></td>
                  <td className="mono muted">v{d.v}</td>
                  <td className="muted">{d.chunks || "—"}</td>
                  <td className="muted">{d.size}</td>
                  <td className="muted">{d.updated}</td>
                  <td>{d.status === "indexed" ? <span className="badge b-approved"><span className="dot" style={{ background: "var(--green)" }} />Indexed</span> : <span className="badge b-reviewed"><span className="dot" style={{ background: "var(--violet)" }} />Processing</span>}</td>
                  <td onClick={e=>e.stopPropagation()}><button className="btn btn-ghost btn-sm" onClick={()=>remove(d.id)}><Icon name="trash" size={15} color="var(--gray-400)" /></button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AgentScreen, ContextScreen });
