/* global React, Ic, Chip, Sparkline, KPI, Panel, AiBand, Av */

/* AI CONSOLE — hub for every autonomous agent Keelway runs.
   This is where the brokerage owner sees what AI did today, with kill-switches. */

const AGENTS = [
  {
    id: "margin",
    name: "Margin Defender",
    tagline: "Watches every booked load. Files detention, fuel adjustments, re-rates before margin bleeds.",
    status: "active",
    autonomy: "AUTO + APPROVE",
    activity: "watching 84 loads · 4 interventions today",
    saved: "$3,240",
    actions: 18,
    recent: [
      { t: "13:08", what: "Filed 2h detention claim · KW-48210 Raley's", value: "+$240" },
      { t: "12:42", what: "Requested fuel adj $0.08/mi · KW-48214 Target", value: "+$124" },
      { t: "11:18", what: "Held carrier accountable for 4h delay · KW-48198", value: "+$880" },
      { t: "09:42", what: "Re-rated post-detour KW-48191 · Houston→Tampa", value: "+$520" },
    ],
  },
  {
    id: "fraud",
    name: "Fraud Shield",
    tagline: "Detects double-brokering, identity fraud, voice cloning, freshly-registered MC scams.",
    status: "active",
    autonomy: "BLOCK + ALERT",
    activity: "scanning 312 carriers · 2 blocks today",
    saved: "Prevented $14k loss",
    actions: 7,
    recent: [
      { t: "12:18", what: "Blocked MC-991884 · MC <60d + voice match w/ prior scammer", value: "BLOCKED" },
      { t: "10:42", what: "Quarantined inbound rate cons · suspicious email domain", value: "FLAG" },
      { t: "08:14", what: "Flagged Cypress Cargo · OOS rate spike + complaint cluster", value: "FLAG" },
    ],
  },
  {
    id: "noshow",
    name: "No-Show Predictor",
    tagline: "Predicts carrier fall-off 12h before pickup. Pre-stages a backup carrier silently.",
    status: "active",
    autonomy: "WARN + STAGE",
    activity: "tracking 64 dispatched loads · 2 predictions",
    saved: "11 rebooks prevented",
    actions: 4,
    recent: [
      { t: "11:54", what: "Predicted no-show · KW-48217 Hidalgo (4h no GPS · prior pattern)", value: "84% likely" },
      { t: "09:12", what: "Staged BluePeak as silent backup · KW-48205", value: "READY" },
      { t: "07:48", what: "Cleared earlier warning · KW-48191 driver responded", value: "RESOLVED" },
    ],
  },
  {
    id: "negotiator",
    name: "AI Negotiator",
    tagline: "Haggles carrier bids over SMS/voice using your historical win/loss data.",
    status: "active",
    autonomy: "APPROVE EACH",
    activity: "4 active negotiations · avg saves $112/load",
    saved: "$1,840",
    actions: 4,
    recent: [
      { t: "13:02", what: "Western Mtn KW-48213 · countered $2,950 → $2,820 · won", value: "-$130" },
      { t: "11:48", what: "Eastern Star KW-48209 · countered $2,200 → $1,980 · won", value: "-$220" },
      { t: "10:14", what: "Pinecone KW-48210 · countered $1,750 · walked away", value: "—" },
    ],
  },
  {
    id: "rfp",
    name: "RFP Auto-Responder",
    tagline: "Inbound RFP spreadsheet → priced response in 20 minutes. Now powering 14 customers.",
    status: "active",
    autonomy: "DRAFT + APPROVE",
    activity: "2 RFPs in progress · Costco Q3 + Walmart annual",
    saved: "23 FTE-days/qtr",
    actions: 2,
  },
  {
    id: "voice",
    name: "Voice Clone",
    tagline: "Calls carriers and shippers in Maya's actual voice with consent. Trust without robot fatigue.",
    status: "active",
    autonomy: "CONSENTED",
    activity: "trained on 14h of Maya's calls · 312 calls today",
    saved: "—",
    actions: 0,
    voiceConsent: true,
  },
  {
    id: "backhaul",
    name: "Backhaul Predictor",
    tagline: "Pre-negotiates the return load before head-haul pickup. Lifts truck utilization 22%.",
    status: "active",
    autonomy: "DRAFT OFFERS",
    activity: "found 6 backhauls today · 4 pre-booked",
    saved: "$2,140",
    actions: 6,
  },
  {
    id: "wellness",
    name: "Driver Wellness",
    tagline: "Voice tone & fatigue signals on check calls. Flags stressed drivers to dispatcher.",
    status: "active",
    autonomy: "FLAG ONLY",
    activity: "47 calls scored · 1 fatigue flag today",
    saved: "1 safety event prevented (est)",
    actions: 1,
  },
  {
    id: "coach",
    name: "Ops Coach",
    tagline: "Reviews each agent's day. Identifies coaching moments without a senior broker watching.",
    status: "active",
    autonomy: "PRIVATE FEEDBACK",
    activity: "6 agents coached · Maya: 'Quote $20 over DAT on Newark lanes'",
    saved: "—",
    actions: 6,
  },
  {
    id: "load",
    name: "Conversational Load Builder",
    tagline: "Email '3 trucks ATL→DAL Tuesday' → 3 loads created, carriers suggested, rate cons drafted.",
    status: "active",
    autonomy: "DRAFT + APPROVE",
    activity: "8 inbound emails parsed today · 6 booked",
    saved: "$0 direct · 4hr/day saved",
    actions: 8,
  },
  {
    id: "postmortem",
    name: "Loss Post-Mortems",
    tagline: "Every below-target load gets a one-paragraph plain-English explanation. Updates daily.",
    status: "active",
    autonomy: "READ-ONLY",
    activity: "12 post-mortems written this week",
    saved: "—",
    actions: 0,
  },
  {
    id: "dock",
    name: "Dock Intelligence",
    tagline: "Pools detention data across Keelway's brokerage network. Warns at quote time.",
    status: "active",
    autonomy: "ADVISE",
    activity: "2,148 receivers profiled · 18 high-risk flagged",
    saved: "—",
    actions: 0,
  },
];

function AIConsole() {
  const [sel, setSel] = React.useState(AGENTS[0]);
  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">AI Console</div>
          <div className="page-sub">12 autonomous agents · 312 actions today · $7,220 GM defended · 1,842 hours saved (30d)</div>
        </div>
        <div className="page-actions">
          <span className="chip ok"><span className="dot pulse" /> ALL AGENTS LIVE</span>
          <button className="btn ghost">Agent rules</button>
          <button className="btn danger">Pause all</button>
        </div>
      </div>

      <div className="grid cols-4 pad" style={{ paddingBottom: 0 }}>
        <KPI label="Actions Today" value="312" delta="46" spark={[20,40,60,80,100,140,180,220,260,290,310,312]} />
        <KPI label="GM Defended" value="$7,220" delta="22%" spark={[200,400,800,1200,2000,2800,3600,4400,5200,6000,6800,7220]} />
        <KPI label="Touchless Rate" value="78%" delta="4pt" spark={[60,62,65,68,70,72,73,74,75,76,77,78]} />
        <KPI label="Prevented Loss" value="$14,400" delta="2 events" spark={[0,0,0,2000,2000,4000,4000,7000,9000,11000,13000,14400]} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 420px", minHeight: 640, marginTop: 16, borderTop: "1px solid var(--line)" }}>
        {/* Agent grid */}
        <div style={{ padding: 16, overflowY: "auto" }}>
          <div className="h-rule" style={{ marginBottom: 10 }}>AGENTS · 12 ACTIVE</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            {AGENTS.map(a => (
              <AgentCard key={a.id} a={a} active={sel.id === a.id} onClick={() => setSel(a)} />
            ))}
          </div>
        </div>

        {/* Inspector */}
        <aside className="inspector">
          <div style={{ padding: 16, borderBottom: "1px solid var(--line)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <Chip kind="accent"><span className="dot pulse" /> ACTIVE</Chip>
              <span className="mono dim" style={{ fontSize: 10 }}>{sel.autonomy}</span>
            </div>
            <div style={{ marginTop: 10, fontSize: 17, fontWeight: 600 }}>{sel.name}</div>
            <div style={{ fontSize: 12, color: "var(--text-mid)", marginTop: 4, lineHeight: 1.5 }}>{sel.tagline}</div>
          </div>

          <div style={{ padding: 16, borderBottom: "1px solid var(--line)" }}>
            <div className="h-rule">TODAY</div>
            <div style={{ marginTop: 10, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
              <div><div className="kpi-label">ACTIONS</div><div className="mono" style={{ fontSize: 20 }}>{sel.actions}</div></div>
              <div><div className="kpi-label">VALUE</div><div className="mono accent" style={{ fontSize: 20, color: "var(--accent)" }}>{sel.saved}</div></div>
            </div>
            <div style={{ marginTop: 10, fontSize: 11, color: "var(--text-dim)" }}>{sel.activity}</div>
          </div>

          {sel.recent && (
            <div style={{ padding: 16, borderBottom: "1px solid var(--line)" }}>
              <div className="h-rule">RECENT ACTIONS</div>
              <div style={{ marginTop: 10, fontSize: 12, display: "flex", flexDirection: "column", gap: 8 }}>
                {sel.recent.map((r, i) => (
                  <div key={i} style={{ display: "grid", gridTemplateColumns: "50px 1fr auto", gap: 8, padding: "6px 0", borderBottom: i === sel.recent.length - 1 ? 0 : "1px solid var(--line)" }}>
                    <span className="mono dim" style={{ fontSize: 10 }}>{r.t}</span>
                    <span style={{ lineHeight: 1.4 }}>{r.what}</span>
                    <span className="mono" style={{ fontSize: 11, color: r.value.startsWith("+") ? "var(--ok)" : r.value.startsWith("-") ? "var(--accent)" : "var(--text-mid)" }}>{r.value}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          <div style={{ padding: 16 }}>
            <div className="h-rule">CONFIGURE</div>
            <div style={{ marginTop: 10, fontSize: 12, lineHeight: 2 }}>
              <ConfRow label="Autonomy" v={sel.autonomy} />
              <ConfRow label="Approval window" v="2 minutes" />
              <ConfRow label="Daily cap" v="50 actions / $5k value" />
              <ConfRow label="Escalate to" v="Maya Ortiz · Nashville" />
            </div>
            <div style={{ display: "flex", gap: 6, marginTop: 14 }}>
              <button className="btn ghost" style={{ flex: 1 }}>View transcript log</button>
              <button className="btn primary" style={{ flex: 1 }}>Tune</button>
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

function AgentCard({ a, active, onClick }) {
  return (
    <div
      onClick={onClick}
      style={{
        background: active ? "var(--bg-sel)" : "var(--bg-1)",
        border: `1px solid ${active ? "var(--accent)" : "var(--line)"}`,
        borderLeft: `2px solid ${active ? "var(--accent)" : "var(--accent-dim)"}`,
        borderRadius: 4, padding: 14, cursor: "pointer",
        display: "flex", flexDirection: "column", gap: 8,
      }}
    >
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <Chip kind="ok"><span className="dot pulse" /> LIVE</Chip>
        <span className="mono dim" style={{ fontSize: 9, marginLeft: "auto" }}>{a.autonomy}</span>
      </div>
      <div style={{ fontSize: 13, fontWeight: 600 }}>{a.name}</div>
      <div style={{ fontSize: 11, color: "var(--text-mid)", lineHeight: 1.5, flex: 1 }}>{a.tagline}</div>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 4 }}>
        <span className="mono dim" style={{ fontSize: 10 }}>{a.actions} actions</span>
        <span className="mono" style={{ fontSize: 11, color: "var(--accent)", marginLeft: "auto" }}>{a.saved}</span>
      </div>
    </div>
  );
}

function ConfRow({ label, v }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
      <span className="dim mono" style={{ fontSize: 10, letterSpacing: "0.1em" }}>{label.toUpperCase()}</span>
      <span style={{ fontSize: 12 }}>{v}</span>
    </div>
  );
}

window.AIConsole = AIConsole;
