/* eagle-soc.jsx — Eagle Eye SOC dashboard. A modern analytics console: KPI
   tiles, charts, MITRE coverage, threat map, gauges, live ticker — with the
   three-architecture launcher as one prominent module and the alert queue as
   an entry point. Theme-aware (light/dark). */

function SocClock() {
  const E = useE(); const [now, setNow] = React.useState(new Date());
  React.useEffect(() => { const i = setInterval(() => setNow(new Date()), 1000); return () => clearInterval(i); }, []);
  return (
    <span className="inline-flex h-9 items-center gap-2 rounded-lg px-2.5 text-[12.5px] tabular-nums" style={{ fontFamily: E.mono, color: E.text, background: E.elevated, border: `1px solid ${E.border}` }}>
      <span className="inline-block h-1.5 w-1.5 rounded-full" style={{ background: E.success, boxShadow: `0 0 6px ${E.success}` }} /> {now.toLocaleTimeString([], { hour12: false })} <span style={{ color: E.muted }}>UTC</span>
    </span>
  );
}

function Card({ title, icon, sub, right, children, pad = true, className = "" }) {
  const E = useE();
  return (
    <div className={"overflow-hidden rounded-2xl " + className} style={{ background: E.surface, border: `1px solid ${E.border}` }}>
      {title && (
        <div className="flex items-center justify-between gap-2 border-b px-4 py-2.5" style={{ borderColor: E.border }}>
          <div className="flex min-w-0 items-center gap-2">
            {icon && <window.Icon name={icon} size={14} style={{ color: E.muted }} />}
            <span className="truncate text-[11.5px] font-bold uppercase tracking-[0.14em]" style={{ color: E.text2, fontFamily: E.mono }}>{title}</span>
            {sub && <span className="truncate text-[11px]" style={{ color: E.muted }}>{sub}</span>}
          </div>
          {right}
        </div>
      )}
      <div className={pad ? "p-4" : ""}>{children}</div>
    </div>
  );
}

function KpiTile({ k }) {
  const E = useE(); const c = E[k.ck];
  return (
    <div className="flex items-center justify-between gap-3 rounded-2xl px-4 py-3.5" style={{ background: E.surface, border: `1px solid ${E.border}` }}>
      <div>
        <div className="flex items-center gap-2 text-[10.5px] uppercase tracking-[0.12em]" style={{ color: E.muted }}>
          <window.Icon name={k.icon} size={13} style={{ color: c }} /> {k.label}
        </div>
        <div className="mt-1 flex items-end gap-2">
          <span className="text-[26px] font-bold leading-none tabular-nums" style={{ fontFamily: E.mono, color: E.text }}>{k.value.toLocaleString()}</span>
          <span className="mb-0.5 rounded px-1.5 py-0.5 text-[10px] font-bold" style={{ background: c + "1a", color: c, fontFamily: E.mono }}>{k.delta}</span>
        </div>
      </div>
      <Sparkline data={k.spark} ck={k.ck} w={92} h={40} />
    </div>
  );
}

function ArchCard({ tierKey, alert, onLaunch }) {
  const E = useE(); const L = window.LAYERS[tierKey]; const c = E[tierKey]; const [hover, setHover] = React.useState(false);
  const lines = { model: "Generic answer · no memory · no tools", app: "RAG + guardrails + session memory", agent: "Autonomous investigation + real actions" };
  return (
    <button onClick={() => onLaunch(tierKey)} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      className="group flex flex-col gap-3 rounded-xl p-3.5 text-left transition-all"
      style={{ background: hover ? c + "14" : E.elevated, border: `1px solid ${hover ? c + "66" : E.border}`, transform: hover ? "translateY(-2px)" : "none" }}>
      <div className="flex items-center justify-between">
        <div className="flex h-9 w-9 items-center justify-center rounded-lg" style={{ background: c + "1f", color: c }}><window.Icon name={L.icon} size={18} /></div>
        <span className="text-[10px] font-bold uppercase tracking-[0.12em]" style={{ color: c, fontFamily: E.mono }}>Layer {L.n}</span>
      </div>
      <div>
        <div className="text-[15px] font-bold" style={{ color: E.text }}>{L.name}</div>
        <div className="mt-0.5 text-[11.5px] leading-snug" style={{ color: E.muted }}>{lines[tierKey]}</div>
      </div>
      <div className="inline-flex items-center gap-1.5 text-[12px] font-bold" style={{ color: c }}>
        <window.Icon name="Play" size={13} /> Run on this alert
        <window.Icon name="ArrowRight" size={13} style={{ transform: hover ? "translateX(2px)" : "none", transition: "transform .2s" }} />
      </div>
    </button>
  );
}

function ArchBand({ alert, onLaunch, onPickAlert }) {
  const E = useE();
  return (
    <Card pad={false} className="">
      <div className="flex flex-wrap items-center justify-between gap-3 border-b px-4 py-3" style={{ borderColor: E.border }}>
        <div className="flex items-center gap-2.5">
          <span className="text-[11.5px] font-bold uppercase tracking-[0.16em]" style={{ color: E.gateway, fontFamily: E.mono }}>Model vs Application vs Agent</span>
          <span className="text-[11.5px]" style={{ color: E.muted }}>— launch one architecture on the selected alert</span>
        </div>
        <button onClick={onPickAlert} className="inline-flex h-8 items-center gap-2 rounded-lg px-3 text-[12px] font-semibold transition-colors hover:opacity-80" style={{ color: E.text2, border: `1px solid ${E.border}` }}>
          <window.Icon name="ListChecks" size={14} /> Change alert
        </button>
      </div>
      <div className="grid gap-4 p-4 lg:grid-cols-[260px_1fr]">
        {/* selected alert */}
        <div className="flex flex-col justify-between rounded-xl p-3.5" style={{ background: alert.sev === "HIGH" ? E.guard + "10" : E.elevated, border: `1px solid ${alert.sev === "HIGH" ? E.guard + "33" : E.border}` }}>
          <div>
            <div className="mb-1.5 flex items-center gap-2"><SevChip sev={alert.sev} size="lg" /><span className="text-[10px] uppercase tracking-[0.14em]" style={{ color: E.muted }}>Selected alert</span></div>
            <div className="text-[14px] font-bold" style={{ color: E.text }}>{alert.title}</div>
            <div className="mt-0.5 text-[12px]" style={{ fontFamily: E.mono, color: E.text2 }}>#{alert.code} · {alert.rule}</div>
            <div className="mt-1.5 text-[11.5px] leading-snug" style={{ color: E.muted }}>{alert.descriptor}</div>
          </div>
          <div className="mt-3 flex flex-wrap gap-1.5 text-[10.5px]" style={{ fontFamily: E.mono, color: E.muted }}>
            <span className="rounded px-1.5 py-0.5" style={{ background: E.fill }}>{alert.host}</span>
            <span className="rounded px-1.5 py-0.5" style={{ background: E.fill }}>{alert.user.replace("@company.com", "")}</span>
          </div>
        </div>
        <div className="grid gap-3 sm:grid-cols-3">
          {["model", "app", "agent"].map((k) => <ArchCard key={k} tierKey={k} alert={alert} onLaunch={onLaunch} />)}
        </div>
      </div>
    </Card>
  );
}

function QueueTable({ alerts, currentId, onSelect, onLaunch }) {
  const E = useE();
  const launchBtns = [["model", E.model, "Box"], ["app", E.app, "Boxes"], ["agent", E.agent, "Workflow"]];
  return (
    <div className="lr-scroll overflow-x-auto">
      <table className="w-full border-collapse">
        <thead><tr style={{ borderBottom: `1px solid ${E.border}` }}>
          {["Severity", "Alert", "Rule", "Host", "User", "Category", "Time", "Launch"].map((h, i) => (
            <th key={i} className={"py-2.5 text-[10px] font-bold uppercase tracking-[0.14em] " + (i === 0 ? "pl-4 pr-2 text-left" : i === 6 ? "px-2 text-right" : i === 7 ? "pr-4 text-right" : "px-2 text-left")} style={{ color: E.muted, fontFamily: E.mono }}>{h}</th>
          ))}
        </tr></thead>
        <tbody>
          {alerts.map((a) => {
            const sel = a.id === currentId;
            return (
              <tr key={a.id} onClick={() => onSelect(a.id)} className="group cursor-pointer transition-colors"
                style={{ background: sel ? E.gateway + "14" : a.hero ? E.guard + "0c" : "transparent", borderLeft: `2px solid ${sel ? E.gateway : a.hero ? E.guard : "transparent"}` }}>
                <td className="py-2.5 pl-4 pr-2"><div className="flex items-center gap-1.5"><SevChip sev={a.sev} />{a.hero && <span className="rounded px-1 py-0.5 text-[8.5px] font-bold uppercase" style={{ background: E.guard + "22", color: E.guard }}>Hero</span>}</div></td>
                <td className="px-2 py-2.5"><span className="text-[12px] font-semibold tabular-nums" style={{ fontFamily: E.mono, color: a.hero ? E.text : E.text2 }}>#{a.code}</span></td>
                <td className="px-2 py-2.5"><span className="text-[12px]" style={{ fontFamily: E.mono, color: E.text2 }}>{a.rule}</span></td>
                <td className="px-2 py-2.5"><span className="text-[12px]" style={{ fontFamily: E.mono, color: E.muted }}>{a.host}</span></td>
                <td className="px-2 py-2.5"><span className="text-[12px]" style={{ color: E.muted }}>{a.user.replace("@company.com", "")}</span></td>
                <td className="px-2 py-2.5"><span className="rounded px-1.5 py-0.5 text-[10.5px]" style={{ background: E.fill, color: E.text2 }}>{a.category}</span></td>
                <td className="px-2 py-2.5 text-right"><span className="text-[11.5px] tabular-nums" style={{ fontFamily: E.mono, color: E.muted }}>{a.time}</span></td>
                <td className="py-2 pl-2 pr-4">
                  <div className="flex items-center justify-end gap-1">
                    {launchBtns.map(([k, c, ic]) => (
                      <button key={k} title={"Launch " + k} onClick={(e) => { e.stopPropagation(); onSelect(a.id); onLaunch(k); }}
                        className="flex h-6 w-6 items-center justify-center rounded-md transition-colors hover:opacity-100"
                        style={{ color: c, background: c + "14", border: `1px solid ${c}33`, opacity: 0.85 }}>
                        <window.Icon name={ic} size={12} />
                      </button>
                    ))}
                  </div>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

function SocDashboard({ alert, onLaunch, onPickAlert, onSelectAlert, onExit, mode, onToggleTheme, onGo }) {
  const E = useE();
  return (
    <div className="lr-scroll h-full w-full overflow-y-auto" style={{ background: E.bg, fontFamily: E.sans, color: E.text }}>
      {/* ambient */}
      <div className="pointer-events-none fixed inset-0"><div className="absolute -top-40 left-1/2 h-[460px] w-[820px] -translate-x-1/2 rounded-full" style={{ background: `radial-gradient(circle, ${E.glow}, transparent 65%)` }} /></div>

      {/* top bar */}
      <header className="sticky top-0 z-20 border-b" style={{ background: E.headerBg, borderColor: E.border, backdropFilter: "blur(12px)" }}>
        <div className="flex w-full flex-wrap items-center justify-between gap-3 px-6 py-3 lg:px-8">
          <div className="flex items-center gap-3">
            <button onClick={onExit} className="inline-flex h-9 items-center gap-1.5 rounded-lg px-2.5 text-[12px] font-medium transition-colors hover:opacity-80" style={{ color: E.muted, border: `1px solid ${E.border}` }}>
              <window.Icon name="ArrowLeft" size={14} /> Last Rose
            </button>
            <div className="flex items-center gap-2.5">
              <div className="flex h-9 w-9 items-center justify-center rounded-xl" style={{ background: `linear-gradient(135deg, ${E.gateway}, ${E.app})`, color: E.isDark ? "#050508" : "#fff" }}><window.Icon name="Eye" size={19} strokeWidth={2.4} /></div>
              <div className="leading-tight"><div className="text-[15px] font-bold" style={{ color: E.text }}>Eagle Eye</div><div className="text-[10px] uppercase tracking-[0.18em]" style={{ color: E.muted, fontFamily: E.mono }}>Security Operations</div></div>
            </div>
            <span className="rounded-md px-2 py-1 text-[10px] font-bold uppercase tracking-[0.16em]" style={{ background: E.identity + "1f", color: E.identity, fontFamily: E.mono }}>Demo</span>
            <ScreenTabs current="soc" onGo={onGo} />
          </div>
          <div className="flex items-center gap-2.5">
            <SocClock />
            <button onClick={onPickAlert} className="inline-flex h-9 items-center gap-2 rounded-lg px-3 text-[12.5px] font-semibold transition-colors hover:opacity-80" style={{ color: E.isDark ? "#050508" : "#fff", background: E.gateway }}>
              <window.Icon name="Command" size={14} /> Alert Launcher
            </button>
            <window.OpenInNewTab href="#/eagle/soc" size={15} className="h-9 w-9" title="Open the SOC dashboard in new tab" style={{ color: E.text2, background: E.elevated, border: `1px solid ${E.border}` }} />
            <EagleThemeToggle mode={mode} onToggle={onToggleTheme} />
            <div className="hidden items-center gap-2.5 rounded-lg px-2.5 py-1.5 sm:flex" style={{ background: E.elevated, border: `1px solid ${E.border}` }}>
              <div className="flex h-7 w-7 items-center justify-center rounded-full text-[11px] font-bold" style={{ background: E.app + "26", color: E.app, fontFamily: E.mono }}>AR</div>
              <div className="leading-tight"><div className="text-[12px] font-semibold" style={{ color: E.text }}>alex.reyes</div><div className="text-[10px]" style={{ color: E.muted }}>SOC Tier-2 Analyst</div></div>
            </div>
          </div>
        </div>
      </header>

      <main className="relative z-10 w-full space-y-4 px-6 pb-20 pt-5 lg:px-8">
        {/* KPI row */}
        <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
          {window.KPIS.map((k) => <KpiTile key={k.key} k={k} />)}
        </div>

        {/* architecture launcher band */}
        <ArchBand alert={alert} onLaunch={onLaunch} onPickAlert={onPickAlert} />

        {/* analytics: area + donut */}
        <div className="grid items-stretch gap-4 lg:grid-cols-3">
          <Card title="Alerts over time" sub="last 24h · stacked by severity" icon="ChartArea" className="lg:col-span-2">
            <AreaStack data={window.ALERTS_24H} height={196} />
          </Card>
          <Card title="Severity mix" icon="ChartPie">
            <div className="flex h-[196px] items-center justify-center"><Donut data={window.SEVERITY_DIST} /></div>
          </Card>
        </div>

        {/* threat topology + MITRE */}
        <div className="grid items-stretch gap-4 lg:grid-cols-3">
          <Card title="Threat topology" sub="sources → org → assets" icon="Radar">
            <div className="flex h-[300px] items-center justify-center"><div style={{ width: "100%", maxWidth: 320 }}><ThreatMap origins={window.THREAT_ORIGINS} targets={window.THREAT_TARGETS} /></div></div>
          </Card>
          <Card title="MITRE ATT&CK coverage" sub="tactics × techniques · detections" icon="Grid3x3" className="lg:col-span-2">
            <MitreHeatmap data={window.MITRE} />
            <div className="mt-4 border-t pt-3" style={{ borderColor: E.border }}>
              <div className="mb-2 text-[10.5px] font-bold uppercase tracking-[0.14em]" style={{ color: E.muted, fontFamily: E.mono }}>Detections by kill-chain stage</div>
              <KillChain data={window.KILLCHAIN} height={130} />
            </div>
          </Card>
        </div>

        {/* hosts + users + gauges */}
        <div className="grid items-stretch gap-4 lg:grid-cols-4">
          <Card title="Top targeted hosts" icon="Server"><HBars items={window.TOP_HOSTS} /></Card>
          <Card title="Top users at risk" icon="Users"><HBars items={window.TOP_USERS} /></Card>
          <Card title="Response SLAs" sub="triage / respond" icon="Gauge" className="lg:col-span-2">
            <div className="flex h-full items-center justify-around gap-2 py-1">{window.GAUGES.map((g) => <RadialGauge key={g.key} g={g} />)}</div>
          </Card>
        </div>

        {/* agent activity + event ticker */}
        <div className="grid items-stretch gap-4 lg:grid-cols-3">
          <Card title="AI agent activity" sub="autonomous actions" icon="Bot" right={<span className="inline-flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-wider" style={{ color: E.agent }}><span className="h-1.5 w-1.5 rounded-full" style={{ background: E.agent, boxShadow: `0 0 6px ${E.agent}` }} /> live</span>} className="lg:col-span-2">
            <AgentActivity items={window.AGENT_ACTIVITY} />
          </Card>
          <Card title="Event stream" icon="Activity" right={<span className="inline-flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-wider" style={{ color: E.success }}><span className="h-1.5 w-1.5 rounded-full" style={{ background: E.success, boxShadow: `0 0 6px ${E.success}` }} /> live</span>}>
            <EventTicker events={window.EVENT_STREAM} rows={7} />
          </Card>
        </div>

        {/* full-width live alert queue */}
        <Card title="Live alert queue" sub="click to select · launch ▸ Model / App / Agent" icon="ListChecks" pad={false}>
          <QueueTable alerts={window.ALERTS} currentId={alert.id} onSelect={onSelectAlert} onLaunch={onLaunch} />
        </Card>
      </main>
    </div>
  );
}

Object.assign(window, { SocDashboard });
