/* global React, AppShell, Card, KpiStrip, Table, Donut, AreaSpark, MiniBars, Pill, StatusDot, Icon, TENANT_TABS */
// ════════════════════════════════════════════════════════════════
// Operations + Security pages: Monitoring · Chaos · SIEM · SOAR · XDR
// ════════════════════════════════════════════════════════════════
const { AppShell, Card, KpiStrip, Table, Donut, AreaSpark, MiniBars, Pill, StatusDot, Icon, TENANT_TABS } = window;

function PageTitle({ t, d }) {
  return <div style={{ marginBottom: 16 }}><div style={{ fontSize: 22, fontWeight: 600, color: "#ECEAF4" }}>{t}</div><div style={{ fontSize: 13.5, color: "var(--tx-2)", marginTop: 3 }}>{d}</div></div>;
}

// ───────── Monitoring & alerts ─────────
const ALERTS = [
  { sev: "err", a: "CPU > 90% sustained", dev: "node-03", dur: "8m", st: "firing" },
  { sev: "err", a: "Interface down, Gi0/2", dev: "dist-b1", dur: "3m", st: "firing" },
  { sev: "warn", a: "Memory utilization 82%", dev: "dist-b1", dur: "21m", st: "firing" },
  { sev: "warn", a: "Disk I/O latency > 20ms", dev: "vm-prod-34", dur: "12m", st: "ack" },
  { sev: "warn", a: "BGP session flapping", dev: "core-rtr-b", dur: "44m", st: "ack" },
  { sev: "info", a: "Agent reconnected", dev: "nims-gcp", dur: "1h", st: "resolved" },
];
const sevTone = { err: "err", warn: "warn", info: "info" };
function MonitoringMock() {
  return (
    <AppShell scopeIcon="gauge" entityName="Northwind Trading" pageName="alerts" tabs={TENANT_TABS} activeTab="monitoring" breadcrumb={["Monitoring", "Alerts"]} avatar="AR">
      <div>
        <PageTitle t="Alerts" d="Health, metrics, and alerting across every device, one stream, correlated." />
        <KpiStrip items={[{ l: "Firing", v: "3", tone: "#f06080" }, { l: "Warning", v: "12", tone: "#f0a060" }, { l: "Acknowledged", v: "5" }, { l: "Resolved · 24h", v: "41", tone: "#34d399" }]} />
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 16 }}>
          <Card title="Fleet health · 24h"><div style={{ padding: "6px 16px 16px" }}><AreaSpark values={[98, 97, 99, 96, 92, 95, 90, 88, 93, 91, 96, 98, 97, 95, 99, 96, 94, 97, 99, 98, 96, 99, 97, 98]} color="#34d399" /></div></Card>
          <Card title="Alerts · 24h"><div style={{ padding: "12px 18px 18px" }}><MiniBars values={[2, 1, 0, 3, 2, 5, 4, 8, 6, 3, 4, 2, 1, 3, 7, 5, 9, 6, 4, 3, 2, 4, 3, 2]} color="#f0a060" h={74} /></div></Card>
        </div>
        <Card title="Firing &amp; recent">
          <Table grid="0.4fr 2fr 1fr 0.7fr 0.9fr"
            cols={[
              { k: "sev", label: "", render: v => <StatusDot tone={sevTone[v]} size={8} /> },
              { k: "a", label: "Alert", render: v => <span style={{ color: "var(--tx)" }}>{v}</span> },
              { k: "dev", label: "Device", mono: true }, { k: "dur", label: "For", mono: true },
              { k: "st", label: "Status", render: v => <Pill tone={v === "firing" ? "err" : v === "ack" ? "warn" : "ok"}>{v}</Pill> },
            ]} rows={ALERTS} />
        </Card>
      </div>
    </AppShell>
  );
}

// ───────── Chaos engineering ─────────
const STEPS = ["Steady state", "Inject", "Observe", "Halt / rollback", "Learn"];
const EXPERIMENTS = [
  { n: "AZ failover, DC-East", method: "Network partition", blast: "1 site", run: "2h ago", res: "passed" },
  { n: "Core-rtr-a kill", method: "Process kill", blast: "2 racks", run: "1d ago", res: "passed" },
  { n: "Latency injection, API", method: "+200ms egress", blast: "12 svc", run: "3d ago", res: "weakness" },
  { n: "PDU-A power loss", method: "Power cut", blast: "1 rack", run: "5d ago", res: "passed" },
];
function ChaosMock() {
  return (
    <AppShell scopeIcon="flask" entityName="Northwind Trading" pageName="chaos engineering" tabs={TENANT_TABS} activeTab="operations" breadcrumb={["Operations", "Chaos Engineering"]} avatar="AR">
      <div>
        <PageTitle t="Chaos engineering" d="Prove resilience with controlled experiments and scheduled gamedays." />
        <Card title="Gameday in progress · AZ failover, DC-East" action={<Pill tone="warn">running · step 3 / 5</Pill>}>
          <div style={{ padding: "18px 18px 20px" }}>
            {/* step tracker */}
            <div style={{ display: "flex", alignItems: "center", marginBottom: 20 }}>
              {STEPS.map((s, i) => {
                const done = i < 2, active = i === 2;
                const c = done ? "#34d399" : active ? "#a78bfa" : "var(--tx-4)";
                return (
                  <React.Fragment key={s}>
                    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 7, flexShrink: 0 }}>
                      <span style={{ width: 26, height: 26, borderRadius: 99, border: `1.5px solid ${c}`, color: c, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11.5, fontFamily: "var(--mono)", background: active ? "rgba(167,139,250,0.12)" : "transparent" }}>{done ? "✓" : i + 1}</span>
                      <span style={{ fontSize: 11.5, color: active ? "#fff" : "var(--tx-3)", fontWeight: active ? 600 : 400 }}>{s}</span>
                    </div>
                    {i < STEPS.length - 1 && <div style={{ flex: 1, height: 1.5, background: i < 2 ? "#34d399" : "var(--divider)", margin: "0 8px", marginBottom: 18 }} />}
                  </React.Fragment>
                );
              })}
            </div>
            {/* steady-state vs observed */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
              {[["Hypothesis", "Failover < 30s, zero data loss", "#a78bfa"], ["Observed", "Failover 18s · 0 errors", "#34d399"], ["Blast radius", "1 site · 4 racks · 842 devices", "#60bce0"]].map(([k, v, c]) => (
                <div key={k} style={{ padding: "13px 15px", border: "1px solid var(--divider)", borderRadius: 10, background: "var(--card-2)" }}>
                  <div className="mono" style={{ fontSize: 9.5, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--tx-3)", marginBottom: 7 }}>{k}</div>
                  <div style={{ fontSize: 14, color: c, fontWeight: 500 }}>{v}</div>
                </div>
              ))}
            </div>
          </div>
        </Card>
        <div style={{ height: 14 }} />
        <Card title="Experiments" action={<span style={{ fontSize: 12.5, fontWeight: 600, color: "#bdb0f6", background: "#242134", border: "1px solid #000", padding: "6px 12px", borderRadius: 6 }}>+ New experiment</span>}>
          <Table grid="1.8fr 1.2fr 0.9fr 0.8fr 0.9fr"
            cols={[
              { k: "n", label: "Experiment", render: v => <span style={{ color: "var(--tx)" }}>{v}</span> },
              { k: "method", label: "Method" }, { k: "blast", label: "Blast radius", mono: true }, { k: "run", label: "Last run", mono: true },
              { k: "res", label: "Result", render: v => <Pill tone={v === "passed" ? "ok" : "warn"}>{v}</Pill> },
            ]} rows={EXPERIMENTS} />
        </Card>
      </div>
    </AppShell>
  );
}

// ───────── SIEM ─────────
const EVENTS = [
  { t: "14:32:01", src: "fw-edge-01", sig: "Outbound to known-bad IP", sev: "err" },
  { t: "14:31:48", src: "ad-dc-01", sig: "Kerberoasting pattern detected", sev: "err" },
  { t: "14:30:12", src: "vpn-gw", sig: "Impossible-travel sign-in", sev: "warn" },
  { t: "14:28:55", src: "node-03", sig: "New listening port 4444", sev: "warn" },
  { t: "14:27:30", src: "core-rtr-a", sig: "Config change outside window", sev: "info" },
  { t: "14:25:09", src: "ad-dc-01", sig: "Privileged group membership add", sev: "warn" },
];
function SiemMock() {
  return (
    <AppShell scopeIcon="shield" entityName="Northwind Trading" pageName="security events" tabs={TENANT_TABS} activeTab="more" breadcrumb={["Security", "SIEM"]} avatar="AR">
      <div>
        <PageTitle t="Security events" d="Collect, normalize, and correlate security events across the whole estate." />
        <KpiStrip items={[{ l: "Events / min", v: "2,840" }, { l: "Critical", v: "2", tone: "#f06080" }, { l: "Correlated", v: "14", tone: "#a78bfa" }, { l: "Sources", v: "486" }]} />
        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 14, marginBottom: 16 }}>
          <Card title="Event volume · 1h"><div style={{ padding: "12px 18px 18px" }}><MiniBars values={[120, 140, 110, 180, 160, 220, 190, 260, 240, 300, 280, 210, 190, 230, 410, 320, 280, 250, 300, 270, 240, 260, 230, 210]} color="#a78bfa" h={78} /></div></Card>
          <Card title="By severity">
            <div style={{ display: "flex", alignItems: "center", gap: 16, padding: "4px 18px 18px" }}>
              <Donut data={[{ label: "Critical", value: 2, color: "#f06080" }, { label: "High", value: 14, color: "#f0a060" }, { label: "Medium", value: 52, color: "#60bce0" }, { label: "Low", value: 130, color: "#5b6178" }]} size={92} />
              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                {[["Critical", "#f06080", 2], ["High", "#f0a060", 14], ["Medium", "#60bce0", 52], ["Low", "#5b6178", 130]].map(([l, c, n]) => (
                  <div key={l} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 11.5, color: "var(--tx-2)" }}><span style={{ width: 9, height: 9, borderRadius: 2, background: c }} />{l}<span className="mono" style={{ color: "var(--tx-3)", marginLeft: "auto" }}>{n}</span></div>
                ))}
              </div>
            </div>
          </Card>
        </div>
        <Card title="Event stream">
          <Table grid="0.4fr 0.8fr 1fr 2.2fr"
            cols={[
              { k: "sev", label: "", render: v => <StatusDot tone={sevTone[v]} size={8} /> },
              { k: "t", label: "Time", mono: true }, { k: "src", label: "Source", mono: true, render: v => <span style={{ color: "var(--tx)" }}>{v}</span> },
              { k: "sig", label: "Signature" },
            ]} rows={EVENTS} />
        </Card>
      </div>
    </AppShell>
  );
}

// ───────── SOAR (playbook workflow) ─────────
const FLOW = [
  { ic: "bell", l: "Trigger", s: "SIEM critical" },
  { ic: "search", l: "Enrich", s: "Threat intel + asset" },
  { ic: "wrench", l: "Decide", s: "Risk score ≥ 80" },
  { ic: "shield", l: "Contain", s: "Isolate host · block IP" },
  { ic: "refresh", l: "Notify", s: "Page + ticket" },
];
const PLAYBOOKS = [
  { n: "Isolate compromised host", trig: "EDR critical", runs: "128", succ: "99%", t: "42s" },
  { n: "Block malicious IP at edge", trig: "SIEM correlation", runs: "312", succ: "100%", t: "9s" },
  { n: "Disable user + reset sessions", trig: "Impossible travel", runs: "47", succ: "96%", t: "1m 8s" },
  { n: "Quarantine phishing mailbox", trig: "Mail gateway", runs: "210", succ: "98%", t: "23s" },
];
function SoarMock() {
  return (
    <AppShell scopeIcon="robot" entityName="Northwind Trading" pageName="playbooks" tabs={TENANT_TABS} activeTab="more" breadcrumb={["Security", "SOAR"]} avatar="AR">
      <div>
        <PageTitle t="Response playbooks" d="Automate investigation and response, from detection to containment, hands-off." />
        <Card title="Playbook · Isolate compromised host" action={<Pill tone="ok">enabled · auto-run</Pill>}>
          <div style={{ display: "flex", alignItems: "stretch", gap: 0, padding: "22px 18px", overflowX: "auto" }}>
            {FLOW.map((f, i) => (
              <React.Fragment key={f.l}>
                <div style={{ flex: 1, minWidth: 130, display: "flex", flexDirection: "column", alignItems: "center", gap: 10, textAlign: "center" }}>
                  <span style={{ width: 46, height: 46, borderRadius: 12, background: "rgba(145,128,212,0.13)", border: "1px solid rgba(145,128,212,0.3)", color: "#a78bfa", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name={f.ic} size={22} /></span>
                  <div><div style={{ fontSize: 14, fontWeight: 600, color: "#fff" }}>{f.l}</div><div className="mono" style={{ fontSize: 10.5, color: "var(--tx-3)", marginTop: 3 }}>{f.s}</div></div>
                </div>
                {i < FLOW.length - 1 && <div style={{ display: "flex", alignItems: "center", color: "var(--tx-4)", paddingTop: 16, flexShrink: 0 }}>→</div>}
              </React.Fragment>
            ))}
          </div>
        </Card>
        <div style={{ height: 14 }} />
        <Card title="Playbooks" action={<span style={{ fontSize: 12.5, fontWeight: 600, color: "#bdb0f6", background: "#242134", border: "1px solid #000", padding: "6px 12px", borderRadius: 6 }}>+ New playbook</span>}>
          <Table grid="2fr 1.2fr 0.6fr 0.7fr 0.8fr"
            cols={[
              { k: "n", label: "Playbook", render: v => <span style={{ color: "var(--tx)" }}>{v}</span> },
              { k: "trig", label: "Trigger" }, { k: "runs", label: "Runs", mono: true }, { k: "succ", label: "Success", mono: true, render: v => <span style={{ color: "#34d399" }}>{v}</span> }, { k: "t", label: "Avg time", mono: true },
            ]} rows={PLAYBOOKS} />
        </Card>
      </div>
    </AppShell>
  );
}

// ───────── XDR (detection timeline) ─────────
const TIMELINE = [
  { x: 6, sev: "info", l: "Recon" }, { x: 22, sev: "warn", l: "Initial access" }, { x: 38, sev: "warn", l: "Execution" },
  { x: 52, sev: "err", l: "Priv-esc" }, { x: 68, sev: "err", l: "Lateral move" }, { x: 86, sev: "ok", l: "Contained" },
];
const DETECTIONS = [
  { t: "Credential dumping (LSASS)", tac: "Credential Access", ent: "node-03", sev: "err", st: "open" },
  { t: "Lateral movement via SMB", tac: "Lateral Movement", ent: "ad-dc-01", sev: "err", st: "open" },
  { t: "Suspicious PowerShell", tac: "Execution", ent: "ws-mktg-12", sev: "warn", st: "investigating" },
  { t: "Anomalous data egress", tac: "Exfiltration", ent: "fw-edge-01", sev: "warn", st: "contained" },
];
function XdrMock() {
  return (
    <AppShell scopeIcon="radar" entityName="Northwind Trading" pageName="detections" tabs={TENANT_TABS} activeTab="more" breadcrumb={["Security", "XDR"]} avatar="AR">
      <div>
        <PageTitle t="Detections &amp; response" d="Correlate signals across network, endpoint, and identity into single incidents." />
        <KpiStrip items={[{ l: "Open detections", v: "9", tone: "#f06080" }, { l: "Critical incidents", v: "2", tone: "#f06080" }, { l: "MTTR", v: "14m", tone: "#34d399" }, { l: "Entities", v: "1,569" }]} />
        <Card title="Incident · INC-2041 · Hands-on-keyboard intrusion" action={<Pill tone="err">critical · active</Pill>}>
          <div style={{ padding: "26px 30px 30px" }}>
            <div style={{ position: "relative", height: 64 }}>
              <div style={{ position: "absolute", top: 30, left: 0, right: 0, height: 2, background: "linear-gradient(90deg, #60bce0, #f0a060, #f06080, #34d399)" }} />
              {TIMELINE.map((e, i) => {
                const c = { info: "#60bce0", warn: "#f0a060", err: "#f06080", ok: "#34d399" }[e.sev];
                return (
                  <div key={i} style={{ position: "absolute", left: `${e.x}%`, top: 0, transform: "translateX(-50%)", textAlign: "center", width: 90 }}>
                    <div style={{ fontSize: 10.5, color: "var(--tx-2)", marginBottom: 6, height: 14 }}>{e.l}</div>
                    <span style={{ display: "inline-block", width: 12, height: 12, borderRadius: 99, background: c, border: "2px solid #08080A", boxShadow: `0 0 8px ${c}` }} />
                  </div>
                );
              })}
            </div>
          </div>
        </Card>
        <div style={{ height: 14 }} />
        <Card title="Detections">
          <Table grid="0.4fr 2fr 1.3fr 1fr 0.9fr"
            cols={[
              { k: "sev", label: "", render: v => <StatusDot tone={sevTone[v]} size={8} /> },
              { k: "t", label: "Detection", render: v => <span style={{ color: "var(--tx)" }}>{v}</span> },
              { k: "tac", label: "MITRE tactic" }, { k: "ent", label: "Entity", mono: true },
              { k: "st", label: "Status", render: v => <Pill tone={v === "open" ? "err" : v === "investigating" ? "warn" : "ok"}>{v}</Pill> },
            ]} rows={DETECTIONS} />
        </Card>
      </div>
    </AppShell>
  );
}

Object.assign(window, { MonitoringMock, ChaosMock, SiemMock, SoarMock, XdrMock });
