// Lightweight stubs for the other 3 agents
function ShipmentAgent({ setRoute }) {
  const d = window.DEMO_DATA;
  return (
    <div className="main wide" style={{padding: "20px 28px 80px"}}>
      <div className="page-head" style={{alignItems: "center", marginBottom: 20}}>
        <div className="row gap-md">
          <button className="btn ghost sm" onClick={() => setRoute({name: "dashboard"})}><Icon name="arrowLeft" size={14}/></button>
          <div>
            <div className="row gap-md items-center">
              <h1 style={{fontFamily: "Onest, sans-serif", fontSize: 22, fontWeight: 600, letterSpacing: "-0.025em", margin: 0}}>Shipment Tracking & Alerts</h1>
              <span className="pill crit"><span className="dot"></span>1 Critical Alert</span>
            </div>
            <div className="page-sub" style={{marginTop: 4, fontSize: 12, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--muted)"}}>Inbound visibility · Dispatch to delivery</div>
          </div>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="refresh" size={14}/> Refresh</button>
          <button className="btn primary"><Icon name="bell" size={14}/> Alert Rules</button>
        </div>
      </div>

      <div className="kpi-grid" style={{gridTemplateColumns: "repeat(4, 1fr)", marginBottom: 20}}>
        <div className="kpi"><div className="kpi-label">In Transit</div><div className="kpi-value">312</div></div>
        <div className="kpi"><div className="kpi-label">On-Time Rate</div><div className="kpi-value">94.2<span className="unit">%</span></div></div>
        <div className="kpi"><div className="kpi-label">Delayed</div><div className="kpi-value" style={{color: "var(--crit)"}}>6</div></div>
        <div className="kpi"><div className="kpi-label">Avg Transit</div><div className="kpi-value">21<span className="unit">days</span></div></div>
      </div>

      <div className="card">
        <div className="card-head"><div className="card-title">Active Shipments</div><span className="text-xs muted">Live from carrier APIs · refreshed every 15 min</span></div>
        <table className="tbl">
          <thead><tr><th>Container</th><th>Carrier</th><th>Origin → Destination</th><th>ETA</th><th>Status</th></tr></thead>
          <tbody>
            {d.shipments.map(s => (
              <tr key={s.id} className="clickable">
                <td className="mono cell-strong">{s.id}</td>
                <td>{s.vendor}</td>
                <td><span className="muted">{s.from}</span> <Icon name="arrow" size={11}/> <strong>{s.to}</strong></td>
                <td className="tabular">{s.eta} {s.days !== 0 && <span className={s.days < 0 ? "" : "muted"} style={{color: s.days < 0 ? "var(--crit)" : undefined, marginLeft: 6, fontSize: 12}}>{s.days > 0 ? `+${s.days}d early` : `${Math.abs(s.days)}d late`}</span>}</td>
                <td><span className={`pill ${s.status === "delayed" ? "crit" : s.status === "early" ? "ok" : "neutral"}`}><span className="dot"></span>{s.status === "delayed" ? "Delayed" : s.status === "early" ? "Early" : "On Time"}</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function RfqAgent({ setRoute }) {
  const d = window.DEMO_DATA;
  const rfqs = d.rfqs;
  const [tab, setTab] = React.useState("all");
  const [selected, setSelected] = React.useState(null);
  const [query, setQuery] = React.useState("");

  const filtered = rfqs.filter(r => {
    if (query && !`${r.title} ${r.id} ${r.buyer}`.toLowerCase().includes(query.toLowerCase())) return false;
    if (tab === "open") return r.status === "open";
    if (tab === "scoring") return r.status === "scoring";
    if (tab === "awarded") return r.status === "awarded";
    if (tab === "issues") return r.status === "issue";
    return true;
  });
  const counts = {
    all: rfqs.length,
    open: rfqs.filter(r => r.status === "open").length,
    scoring: rfqs.filter(r => r.status === "scoring").length,
    awarded: rfqs.filter(r => r.status === "awarded").length,
    issues: rfqs.filter(r => r.status === "issue").length,
  };
  const totalSavings = rfqs.reduce((s, r) => s + r.savings, 0);

  return (
    <div className="main wide" style={{padding: "20px 28px 80px"}}>
      <div className="page-head" style={{alignItems: "center", marginBottom: 20}}>
        <div className="row gap-md">
          <button className="btn ghost sm" onClick={() => setRoute({name: "dashboard"})}><Icon name="arrowLeft" size={14}/></button>
          <div>
            <div className="row gap-md items-center">
              <h1 style={{fontFamily: "Onest, sans-serif", fontSize: 22, fontWeight: 600, letterSpacing: "-0.025em", margin: 0}}>RFQ Analyzer</h1>
              <span className="pill ok"><span className="dot"></span>Operational</span>
            </div>
            <div className="page-sub" style={{marginTop: 4, fontSize: 12, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--muted)"}}>Quote scoring · Line normalization · Award recommendation</div>
          </div>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="refresh" size={14}/> Refresh</button>
          <button className="btn"><Icon name="upload" size={14}/> Import Quotes</button>
          <button className="btn primary"><Icon name="plus" size={14}/> New RFQ</button>
        </div>
      </div>

      <div className="kpi-grid" style={{gridTemplateColumns: "repeat(5, 1fr)", marginBottom: 20}}>
        <div className="kpi"><div className="kpi-label">Active RFQs</div><div className="kpi-value">{rfqs.length}</div></div>
        <div className="kpi"><div className="kpi-label">Quotes Scored</div><div className="kpi-value">34</div></div>
        <div className="kpi"><div className="kpi-label">Awards · MTD</div><div className="kpi-value">{counts.awarded}</div></div>
        <div className="kpi"><div className="kpi-label">Savings Identified</div><div className="kpi-value" style={{color: "var(--ok)"}}>{fmt(totalSavings, {compact: true})}<span className="unit">SAR</span></div></div>
        <div className="kpi"><div className="kpi-label">Avg Cycle</div><div className="kpi-value">3.2<span className="unit">days</span></div></div>
      </div>

      <div className="card">
        <div style={{padding: "14px 20px 0"}}>
          <div className="row between">
            <div className="tabs" style={{margin: 0, border: "none"}}>
              <button className={tab === "all" ? "active" : ""} onClick={() => setTab("all")}>All <span className="count">({counts.all})</span></button>
              <button className={tab === "open" ? "active" : ""} onClick={() => setTab("open")}>Open <span className="count">({counts.open})</span></button>
              <button className={tab === "scoring" ? "active" : ""} onClick={() => setTab("scoring")}>Scoring <span className="count">({counts.scoring})</span></button>
              <button className={tab === "awarded" ? "active" : ""} onClick={() => setTab("awarded")}>Awarded <span className="count">({counts.awarded})</span></button>
              <button className={tab === "issues" ? "active" : ""} onClick={() => setTab("issues")}>Issues <span className="count">({counts.issues})</span></button>
            </div>
            <div className="topbar-search" style={{minWidth: 240}}>
              <Icon name="search" size={13}/>
              <input placeholder="Search RFQs…" value={query} onChange={(e) => setQuery(e.target.value)} />
            </div>
          </div>
        </div>
        <table className="tbl">
          <thead>
            <tr>
              <th style={{width: "32%"}}>RFQ</th>
              <th>Buyer</th>
              <th style={{textAlign: "center"}}>Quotes</th>
              <th style={{textAlign: "right"}}>Lowest / Baseline</th>
              <th style={{textAlign: "right"}}>Savings</th>
              <th>AI Recommendation</th>
              <th style={{width: 110}}>Status</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(r => {
              const statusMap = {
                open: { cls: "neutral", label: "Open" },
                scoring: { cls: "warn", label: "AI Scoring" },
                awarded: { cls: "ok", label: "Awarded" },
                issue: { cls: "crit", label: "Issue" },
              };
              const s = statusMap[r.status];
              return (
                <tr key={r.id} className="clickable" onClick={() => setSelected(r)}>
                  <td>
                    <div className="cell-stack">
                      <div className="cell-strong">{r.title}</div>
                      <div className="cell-sub mono">{r.id} · {r.category}</div>
                    </div>
                  </td>
                  <td>
                    <div className="cell-stack">
                      <div>{r.buyer}</div>
                      <div className="cell-sub">Due {r.deadline}</div>
                    </div>
                  </td>
                  <td className="text-center tabular cell-strong">{r.quotes}</td>
                  <td className="text-right tabular">
                    <div className="cell-strong">{fmt(r.lowest)}</div>
                    <div className="cell-sub">vs {fmt(r.baseline)}</div>
                  </td>
                  <td className="text-right tabular" style={{color: r.savings > 0 ? "var(--ok)" : "var(--muted)", fontWeight: 600}}>
                    {r.savings > 0 ? `−${fmt(r.savings, {compact: true})}` : "—"}
                    <div className="cell-sub" style={{color: "var(--muted)", fontWeight: 400}}>{r.savings > 0 ? `${((r.savings/r.baseline)*100).toFixed(1)}%` : ""}</div>
                  </td>
                  <td>
                    {r.leader === "—" ? <span className="muted text-sm">Manual review needed</span> : (
                      <div className="cell-stack">
                        <div className="cell-strong">{r.leader}</div>
                        <div className="cell-sub">Confidence {r.confidence}%</div>
                      </div>
                    )}
                  </td>
                  <td><span className={`pill ${s.cls}`}><span className="dot"></span>{s.label}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <Drawer open={!!selected} onClose={() => setSelected(null)} width={760}>
        {selected && (
          <>
            <div className="drawer-head">
              <div>
                <div className="drawer-title">{selected.title}</div>
                <div className="drawer-sub mono">{selected.id} · {selected.category} · Due {selected.deadline}</div>
              </div>
              <div className="drawer-actions">
                <button className="btn sm primary"><Icon name="check" size={13}/> Award to {selected.leader.split(" ")[0]}</button>
                <button className="drawer-close" onClick={() => setSelected(null)}><Icon name="x" size={16}/></button>
              </div>
            </div>
            <div className="drawer-body">
              <div className="diff-bar mb-3">
                <span className="label">Baseline</span><span className="val tabular">{fmt(selected.baseline)} SAR</span>
                <span className="sep">·</span>
                <span className="label">Best Quote</span><span className="val tabular ok">{fmt(selected.lowest)} SAR</span>
                <span className="sep">·</span>
                <span className="label">Savings</span><span className="val tabular ok">−{fmt(selected.savings)} SAR ({((selected.savings/selected.baseline)*100).toFixed(1)}%)</span>
                <div style={{flex: 1}}></div>
                <span className="pill ok"><span className="dot"></span>{selected.confidence}% confidence</span>
              </div>
              <div className="ai-box mb-3">
                <div className="ai-icon">P</div>
                <div className="ai-body">
                  <span className="ai-label">AI Recommendation</span>
                  <strong>Award to {selected.leader}.</strong> Lowest total cost across {selected.quotes} normalized quotes, with delivery terms matching spec (FOB Dammam, 14-day lead). Historical OTD rate <strong>97.2%</strong>, no quality flags in last 18 months. Runner-up came in {fmt(Math.round(selected.savings * 0.4))} SAR higher with longer lead time.
                </div>
              </div>
              <div className="section">
                <div className="section-title mb-2">Normalized Quote Comparison · {selected.quotes} suppliers</div>
                <table className="tbl" style={{border: "1px solid var(--border)", borderRadius: 6}}>
                  <thead>
                    <tr>
                      <th>Supplier</th>
                      <th style={{textAlign: "right"}}>Total</th>
                      <th style={{textAlign: "right"}}>vs Baseline</th>
                      <th style={{textAlign: "center"}}>Lead Time</th>
                      <th style={{textAlign: "center"}}>Terms</th>
                      <th style={{textAlign: "center"}}>AI Score</th>
                    </tr>
                  </thead>
                  <tbody>
                    {[
                      { n: selected.leader, t: selected.lowest, lt: "14d", terms: "Net 60", score: selected.confidence, win: true },
                      { n: "Gulf Petro Trading", t: selected.lowest + Math.round(selected.savings * 0.4), lt: "21d", terms: "Net 45", score: 78, win: false },
                      { n: "Riyadh Industrial Co.", t: selected.lowest + Math.round(selected.savings * 0.65), lt: "18d", terms: "Net 30", score: 71, win: false },
                      { n: "Eastern Province Supply", t: selected.lowest + Math.round(selected.savings * 0.9), lt: "28d", terms: "Net 30", score: 64, win: false },
                    ].map((q, i) => (
                      <tr key={i} style={q.win ? { background: "rgba(26, 127, 79, 0.05)" } : {}}>
                        <td className="cell-strong">{q.win && <Icon name="check" size={13} className="" />} {q.n}</td>
                        <td className="text-right tabular">{fmt(q.t)}</td>
                        <td className="text-right tabular" style={{color: "var(--ok)"}}>−{(((selected.baseline - q.t)/selected.baseline)*100).toFixed(1)}%</td>
                        <td className="text-center tabular">{q.lt}</td>
                        <td className="text-center text-sm">{q.terms}</td>
                        <td className="text-center cell-strong tabular">{q.score}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </>
        )}
      </Drawer>
    </div>
  );
}

function GenericAgent({ setRoute, agentId }) {
  const d = window.DEMO_DATA;
  const a = d.agents.find(x => x.id === agentId);
  return (
    <div className="main wide" style={{padding: "20px 28px 80px"}}>
      <div className="page-head" style={{alignItems: "center", marginBottom: 20}}>
        <div className="row gap-md">
          <button className="btn ghost sm" onClick={() => setRoute({name: "dashboard"})}><Icon name="arrowLeft" size={14}/></button>
          <div>
            <div className="row gap-md items-center">
              <h1 style={{fontFamily: "Onest, sans-serif", fontSize: 22, fontWeight: 600, letterSpacing: "-0.025em", margin: 0}}>{a?.name}</h1>
              <span className="pill ok"><span className="dot"></span>Operational</span>
            </div>
            <div className="page-sub" style={{marginTop: 4, fontSize: 13, color: "var(--muted)"}}>{a?.desc}</div>
          </div>
        </div>
      </div>
      <div className="kpi-grid" style={{gridTemplateColumns: "repeat(4, 1fr)", marginBottom: 20}}>
        <div className="kpi"><div className="kpi-label">Processed Today</div><div className="kpi-value">{a?.today.processed}</div></div>
        <div className="kpi"><div className="kpi-label">Auto-Resolved</div><div className="kpi-value">{a?.today.matched}</div></div>
        <div className="kpi"><div className="kpi-label">Exceptions</div><div className="kpi-value">{a?.today.exceptions}</div></div>
        <div className="kpi"><div className="kpi-label">Accuracy</div><div className="kpi-value">{a?.accuracy}<span className="unit">%</span></div></div>
      </div>
      <div className="card" style={{padding: "60px 24px", textAlign: "center", color: "var(--muted)"}}>
        <Icon name="sparkle" size={32}/>
        <div style={{fontSize: 16, marginTop: 14, color: "var(--ink)", fontFamily: "Onest, sans-serif", fontWeight: 600, letterSpacing: "-0.015em"}}>Detailed workspace coming next iteration</div>
        <div style={{fontSize: 13, marginTop: 6}}>This agent is operational. Drill-down view is on the roadmap.</div>
      </div>
    </div>
  );
}

Object.assign(window, { ShipmentAgent, RfqAgent, GenericAgent });
