/* global React, ReactDOM, window */
// ════════════════════════════════════════════════════════════════
// Detail-page content + renderers. Bootstraps page.html via ?p=slug.
// ════════════════════════════════════════════════════════════════
const { useState } = React;
const { Check, ContactModal, SiteNav, SiteFooter, HOME } = window.SostratusChrome;

const FEATURES = {
  nims: {
    section: "Platform", kicker: "Discovery · NIMS", mock: "AgentsMock",
    title: "One agent. Every device. Zero manual inventory.",
    tag: "Native, agent-based discovery of everything on the wire.",
    sub: "A single NIMS agent per boundary fingerprints everything on the wire, natively, and becomes the foundation for vendor-aware configuration.",
    overview: "NIMS (the Network Infrastructure Management System) replaces a drawer full of single-purpose probes with one agent per network boundary. It speaks the protocols your gear already speaks, identifies every device without manual seeds, and keeps that picture continuously current. Because the same secure channel that reads device state can also write it, NIMS is the foundation the rest of the platform builds on.",
    steps: [
      { t: "Deploy", b: "Drop one NIMS agent on each boundary (a site, a VLAN, a cloud VPC). Enrollment is a single token; no per-device agents." },
      { t: "Discover", b: "The agent walks ARP, LLDP/CDP, SNMP, SSH, and cloud APIs to fingerprint every device it can reach, then sweeps continuously." },
      { t: "Operate", b: "Everything it finds flows straight into inventory, topology, IPAM, and monitoring, with no spreadsheets in the middle." },
    ],
    caps: [
      { t: "Protocol-native", b: "Identifies devices the way they identify themselves, so coverage spans vendors and generations without bespoke connectors." },
      { t: "Boundary-scoped", b: "Each agent owns one boundary. Scans stay local and fast, and never cross a tenant line." },
      { t: "Always current", b: "Continuous sweeps keep inventory live; firmware, neighbor, and config drift are flagged the moment they happen." },
      { t: "Config foundation", b: "The read channel is also the write channel, which is what makes vendor-aware configuration changes possible from one place." },
    ],
    coverage: ["Routers, switches, firewalls, access points", "Servers, hypervisors, virtual machines", "Containers and Kubernetes nodes", "Storage, IoT, and OT endpoints", "Public-cloud and SaaS edges"],
    related: ["devices", "topology", "monitoring"],
  },
  devices: {
    section: "Platform", kicker: "Inventory · Devices", mock: "TenantDevicesMock",
    title: "Every device, classified and searchable.",
    tag: "Auto-classified inventory with vendor and model detection.",
    sub: "Routers to containers, automatically categorized with vendor and model detection. Filter, save views, and drill into any device's full history.",
    overview: "Discovery is only useful if you can find things in it. The Devices view turns raw discovery into a structured, searchable inventory: every device classified by category and type, enriched with vendor and model, and linked to its interfaces, neighbors, and known vulnerabilities. Saved views and filters let each team carve out the slice they care about.",
    steps: [
      { t: "Ingest", b: "Devices arrive from NIMS already fingerprinted, with vendor, model, OS, and serial where available." },
      { t: "Classify", b: "Each device is sorted into a category and type so the list reads like an org chart of your estate." },
      { t: "Drill", b: "Open any device for interfaces, neighbors, CVEs, config, and a full change history." },
    ],
    caps: [
      { t: "Automatic classification", b: "Network infra, compute, virtual, containers, and endpoints are grouped without manual tagging." },
      { t: "Vendor and model detection", b: "Make and model are inferred from discovery signals, not typed in by hand." },
      { t: "Saved views and filters", b: "Pin the queries each team lives in (down devices, a vendor, a site) for one-click recall." },
      { t: "Device detail", b: "Every device carries its interfaces, neighbors, vulnerabilities, and timeline in one place." },
    ],
    coverage: ["Hostname, vendor, model, serial", "IP and interface inventory", "Neighbor and link relationships", "Known CVEs per device", "First-seen and last-seen history"],
    related: ["nims", "topology", "ipam"],
  },
  topology: {
    section: "Platform", kicker: "Networks · Topology", mock: "TopologyPageMock",
    title: "A live map you'll actually want to look at.",
    tag: "Auto-drawn map of sites, devices, and links.",
    sub: "Drawn from discovery: sites, devices, and links, with VLAN overlays and live health, from region down to the rack.",
    overview: "Most network diagrams are stale the day they're drawn. Sostratus draws the map from live discovery and keeps it that way. Sites become zones, devices become nodes, and links carry real-time health, so the map is a working surface rather than a slide. Drill from a region to a site to a single rack without losing context.",
    steps: [
      { t: "Derive", b: "Topology is computed from NIMS neighbor and link data, so it reflects the network as it actually is." },
      { t: "Overlay", b: "Layer VLANs, sites, or link health on top to answer a specific question without redrawing anything." },
      { t: "Drill", b: "Zoom from world to region to site to rack; selecting any node opens its live detail." },
    ],
    caps: [
      { t: "Auto-drawn", b: "No manual placement. The map regenerates as the network changes, including newly discovered devices." },
      { t: "Site and VLAN overlays", b: "Toggle overlays to see segmentation and blast surfaces, not just physical links." },
      { t: "Live link health", b: "Links and nodes carry real status, so degradation shows up on the map, not just in alerts." },
      { t: "Drill to the rack", b: "The same map answers both the strategic and the on-the-floor question." },
    ],
    coverage: ["Multi-site, multi-region maps", "Device and link relationships", "VLAN and subnet overlays", "Live status on nodes and links", "Region to rack drill-down"],
    related: ["devices", "nims", "dcim"],
  },
  ipam: {
    section: "Platform", kicker: "Inventory · IPAM", mock: "IpamMock",
    title: "Address space that reconciles itself.",
    tag: "Prefixes, subnets, and VLANs, reconciled with discovery.",
    sub: "Prefixes, subnets, and VLANs in one place, continuously checked against what NIMS actually sees on the network.",
    overview: "An IPAM is only trustworthy if it matches reality. Because Sostratus already discovers every device and its addresses, the IPAM is reconciled against the live network rather than maintained by hand. Utilization, conflicts, and orphaned allocations surface on their own.",
    steps: [
      { t: "Model", b: "Define prefixes, subnets, and VLANs, or import what you already have." },
      { t: "Reconcile", b: "NIMS-discovered addresses are matched against the plan to flag drift, conflicts, and free space." },
      { t: "Plan", b: "Utilization views make it obvious where you're tight and where there's room to grow." },
    ],
    caps: [
      { t: "Prefixes and subnets", b: "Hierarchical address space with roles and sites attached to every block." },
      { t: "Utilization at a glance", b: "Per-prefix utilization bars turn capacity questions into a quick scan." },
      { t: "VLAN mapping", b: "Tie prefixes to VLANs so segmentation and addressing stay in sync." },
      { t: "Reconciled with discovery", b: "What's planned is continuously compared to what's actually on the wire." },
    ],
    coverage: ["IPv4 and IPv6 prefixes", "Subnet and role assignment", "VLAN to prefix mapping", "Per-prefix utilization", "Conflict and drift detection"],
    related: ["dcim", "devices", "topology"],
  },
  dcim: {
    section: "Platform", kicker: "Inventory · DCIM", mock: "DcimMock",
    title: "Racks and hardware, always in sync.",
    tag: "Live rack elevations, power, and thermal.",
    sub: "Sites, racks, and physical hardware with live elevations, power and thermal readings, and capacity planning built in.",
    overview: "DCIM closes the loop between the logical network and the physical one. Sites, rooms, and racks are modeled with real elevations, and discovered hardware is placed into them, so the rack view matches the floor. Power and thermal readings ride along for capacity and safety planning.",
    steps: [
      { t: "Model", b: "Lay out sites, rooms, and racks with their real U heights and power feeds." },
      { t: "Place", b: "Discovered hardware is mapped into rack units, so elevations stay current." },
      { t: "Plan", b: "Utilization, power, and thermal headroom make capacity decisions concrete." },
    ],
    caps: [
      { t: "Sites, racks, hardware", b: "A physical hierarchy that mirrors the logical inventory device-for-device." },
      { t: "Live rack elevations", b: "Elevations reflect what discovery sees, not a diagram someone forgot to update." },
      { t: "Power and thermal", b: "Per-rack power draw and temperature for safety and capacity headroom." },
      { t: "Capacity planning", b: "U, power, and cooling utilization answer 'can this fit here' before you ship it." },
    ],
    coverage: ["Sites, rooms, and racks", "Rack-unit elevations", "Per-rack power draw", "Thermal readings", "U and power utilization"],
    related: ["ipam", "devices", "topology"],
  },
  monitoring: {
    section: "Operations", kicker: "Monitoring · Alerts", mock: "MonitoringMock",
    title: "Health and alerting, correlated.",
    tag: "Unified health, metrics, and correlated alerts.",
    sub: "One stream of health and metrics across every device, with alerts grouped and correlated so you chase incidents, not noise.",
    overview: "Sostratus monitors the same fleet it discovers, so there's nothing to wire up twice. Metrics and health roll up across sites and tenants, and alerts are correlated into the few that matter instead of a wall of red. Rules and silences keep the signal clean.",
    steps: [
      { t: "Collect", b: "Health and metrics stream from discovered devices automatically, no per-device setup." },
      { t: "Correlate", b: "Related alerts are grouped so one root cause doesn't become fifty notifications." },
      { t: "Act", b: "Drill from an alert to the device, silence noise, and tune rules in place." },
    ],
    caps: [
      { t: "Unified health and metrics", b: "One view across every device type, site, and tenant." },
      { t: "Correlated alerts", b: "Grouping and deduplication turn alert storms into incidents." },
      { t: "Per-device drill-in", b: "Every alert links to the device, its metrics, and its history." },
      { t: "Rules and silences", b: "Tune thresholds and silence maintenance windows without leaving the page." },
    ],
    coverage: ["Device and interface health", "Time-series metrics", "Alert correlation and grouping", "Silences and maintenance windows", "Alert rules and routing"],
    related: ["devices", "chaos", "xdr"],
  },
  chaos: {
    section: "Operations", kicker: "Operations · Chaos", mock: "ChaosMock",
    title: "Prove resilience before it's tested for you.",
    tag: "Controlled experiments and scheduled gamedays.",
    sub: "Run controlled experiments and scheduled gamedays with explicit blast-radius limits and steady-state hypotheses.",
    overview: "Resilience you haven't tested is a guess. Chaos engineering in Sostratus lets you run controlled experiments against real infrastructure with a defined steady state, a hypothesis, and a hard blast-radius limit, then proves (or disproves) that the network behaves the way you think it does.",
    steps: [
      { t: "Hypothesize", b: "State the steady state and what you expect to happen when you perturb it." },
      { t: "Inject", b: "Run the experiment with a strict blast radius and an automatic halt condition." },
      { t: "Learn", b: "Compare observed behavior to the hypothesis and turn gaps into fixes." },
    ],
    caps: [
      { t: "Controlled experiments", b: "Network partitions, process kills, latency, and power loss, scoped precisely." },
      { t: "Scheduled gamedays", b: "Recurring, choreographed exercises with a step tracker the whole team can follow." },
      { t: "Blast-radius control", b: "Every experiment declares and enforces exactly how far it's allowed to reach." },
      { t: "Steady-state hypotheses", b: "Experiments pass or fail against a measurable expectation, not a vibe." },
    ],
    coverage: ["Network partition and latency injection", "Process and power-loss experiments", "Blast-radius enforcement", "Automatic halt and rollback", "Gameday scheduling and tracking"],
    related: ["monitoring", "automation", "topology"],
  },
  automation: {
    section: "Operations", kicker: "Operations · Automation", mock: "AutomationMock",
    title: "Run the routine work on rails.",
    tag: "Jobs, schedules, and workflow templates.",
    sub: "Jobs, schedules, and workflow templates that turn repetitive network operations into auditable automation.",
    overview: "The work that eats a network team's week is rarely hard, it's just repetitive and risky to do by hand. Automation turns those tasks into versioned jobs and scheduled workflows that run the same way every time, with a full audit trail and the same vendor-aware config channel NIMS provides.",
    steps: [
      { t: "Build", b: "Compose jobs from config pushes, checks, and scripts, or start from a workflow template." },
      { t: "Schedule", b: "Run on a cadence or a trigger, with approvals where you want a human in the loop." },
      { t: "Audit", b: "Every run records who, what, where, and the diff, so changes are never a mystery." },
    ],
    caps: [
      { t: "Jobs", b: "Reusable, parameterized units of work that target devices, sites, or whole tenants." },
      { t: "Schedules", b: "Time and event-driven runs for backups, sweeps, and rotations." },
      { t: "Workflow templates", b: "Multi-step playbooks for things like decommissioning a rack end-to-end." },
      { t: "Integrations", b: "Hooks into ticketing and chat so automation fits the process you already run." },
    ],
    coverage: ["Config backup and compliance", "Credential rotation", "Bulk config changes", "Scheduled and triggered runs", "Full run audit and diffs"],
    related: ["chaos", "monitoring", "soar"],
  },
  siem: {
    section: "Security", kicker: "Security · SIEM", mock: "SiemMock",
    title: "Security events, collected and correlated.",
    tag: "Collect, normalize, and correlate security events.",
    sub: "Collect and normalize events from across the estate, then correlate them into the handful that actually matter.",
    overview: "A SIEM that only collects is a log bucket. Sostratus collects and normalizes events from across the same fleet it manages, then correlates them so analysts triage incidents rather than scroll. Because it already knows the assets, every event arrives with context.",
    steps: [
      { t: "Collect", b: "Ingest events from network, endpoint, identity, and cloud sources." },
      { t: "Normalize", b: "Map everything to a common schema so a query spans sources, not silos." },
      { t: "Correlate", b: "Group related events into incidents and rank them by severity." },
    ],
    caps: [
      { t: "Collect and normalize", b: "One schema across sources turns disparate logs into searchable events." },
      { t: "Correlation", b: "Related events become a single incident with the assets already attached." },
      { t: "Severity triage", b: "Events are ranked so the critical few rise above the routine many." },
      { t: "Fast search", b: "Query the whole event stream quickly, by asset, source, or signature." },
    ],
    coverage: ["Network and firewall events", "Endpoint and identity events", "Cloud and SaaS logs", "Normalization to one schema", "Severity and correlation"],
    related: ["soar", "xdr", "monitoring"],
  },
  soar: {
    section: "Security", kicker: "Security · SOAR", mock: "SoarMock",
    title: "Response that runs itself.",
    tag: "Automated, playbook-driven response.",
    sub: "Codify investigation and response as playbooks: enrich, decide, and contain in seconds, with every run audited.",
    overview: "When something fires at 3am, the difference between a minor event and an incident is how fast you respond. SOAR turns your response runbooks into playbooks that enrich, decide, and contain automatically, with humans in the loop only where it matters, and a full audit of every action.",
    steps: [
      { t: "Trigger", b: "A detection or correlation kicks off the matching playbook." },
      { t: "Enrich and decide", b: "Threat intel and asset context feed a decision step with a clear risk threshold." },
      { t: "Contain", b: "Isolate a host, block an address, or disable an account in seconds, then notify." },
    ],
    caps: [
      { t: "Automated playbooks", b: "Investigation and response codified as repeatable, versioned workflows." },
      { t: "Enrich and decide", b: "Pull context automatically and branch on explicit risk criteria." },
      { t: "Contain in seconds", b: "Network and identity actions execute through the same trusted channel as config." },
      { t: "Every run audited", b: "Each step is recorded, so automated actions are fully accountable." },
    ],
    coverage: ["Trigger from SIEM or XDR", "Threat-intel and asset enrichment", "Host isolation and IP blocking", "Account and session controls", "End-to-end run audit"],
    related: ["siem", "xdr", "automation"],
  },
  xdr: {
    section: "Security", kicker: "Security · XDR", mock: "XdrMock",
    title: "One incident, not a thousand signals.",
    tag: "Cross-layer detection and response.",
    sub: "Correlate signals across network, endpoint, and identity into single incidents, mapped to MITRE and built for faster MTTR.",
    overview: "Attacks don't respect tool boundaries, and neither should detection. XDR stitches signals from the network, endpoints, and identity into a single incident with a timeline, maps the activity to MITRE tactics, and hands SOAR everything it needs to respond, which is what brings mean-time-to-respond down.",
    steps: [
      { t: "Correlate", b: "Signals from every layer are joined by entity into one incident." },
      { t: "Map", b: "Activity is mapped to MITRE tactics so the story reads as an attack, not a log dump." },
      { t: "Respond", b: "Incidents flow into SOAR playbooks for containment and recovery." },
    ],
    caps: [
      { t: "Cross-layer correlation", b: "Network, endpoint, and identity signals become one entity-centric incident." },
      { t: "Incident timelines", b: "A readable progression from recon to containment, per incident." },
      { t: "MITRE mapping", b: "Tactics and techniques are labeled so analysts and reports speak the same language." },
      { t: "Faster MTTR", b: "Context plus automated response shortens the path from detection to contained." },
    ],
    coverage: ["Network, endpoint, and identity signals", "Entity-centric incident grouping", "Attack timelines", "MITRE ATT&CK mapping", "Handoff to SOAR"],
    related: ["siem", "soar", "monitoring"],
  },
};

function RelatedCards({ slugs }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 16 }}>
      {slugs.map((s) => {
        const f = FEATURES[s];
        return (
          <a key={s} href={"/" + s} style={{ display: "block", padding: "22px 22px 24px", background: "var(--card)", border: "1px solid var(--divider)", borderRadius: 12, textDecoration: "none", transition: "border-color .15s" }}
            onMouseEnter={(e) => e.currentTarget.style.borderColor = "var(--accent)"} onMouseLeave={(e) => e.currentTarget.style.borderColor = "var(--divider)"}>
            <div className="mono" style={{ fontSize: 10.5, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--accent)", marginBottom: 9 }}>{f.section}</div>
            <div style={{ fontSize: 18, fontWeight: 600, color: "#fff", marginBottom: 6 }}>{f.kicker.split("·").pop().trim()}</div>
            <div style={{ fontSize: 13.5, color: "var(--tx-2)", lineHeight: 1.5, marginBottom: 12 }}>{f.tag}</div>
            <span style={{ fontSize: 13.5, color: "#bdb0f6", fontWeight: 600 }}>Learn more →</span>
          </a>
        );
      })}
    </div>
  );
}

function FeaturePage({ slug, onContact }) {
  const f = FEATURES[slug];
  const Mock = window[f.mock];
  return (
    <div>
      <SiteNav onContact={onContact} />
      <header className="grid-bg" style={{ position: "relative", overflow: "hidden", borderBottom: "1px solid var(--divider-2)" }}>
        <div className="noise-glow" style={{ position: "absolute", inset: 0, height: 620, pointerEvents: "none" }} />
        <div className="wrap" style={{ position: "relative", paddingTop: 64, paddingBottom: 56 }}>
          <div className="mono" style={{ fontSize: 12, color: "var(--tx-3)", marginBottom: 22 }}>
            <a href={HOME} style={{ color: "var(--accent)", textDecoration: "none" }}>Home</a> <span style={{ color: "var(--tx-4)" }}>/</span> {f.section} <span style={{ color: "var(--tx-4)" }}>/</span> <span style={{ color: "var(--tx-2)" }}>{f.kicker.split("·").pop().trim()}</span>
          </div>
          <div className="kicker" style={{ marginBottom: 16 }}>{f.kicker}</div>
          <h1 className="disp" style={{ fontSize: 60, maxWidth: "15em" }}>{f.title}</h1>
          <p className="sub" style={{ marginTop: 22, maxWidth: "38em", fontSize: 20 }}>{f.sub}</p>
          <div style={{ display: "flex", gap: 13, marginTop: 32 }}>
            <button onClick={onContact} className="btn btn-primary" style={{ cursor: "pointer" }}>Request access →</button>
            <a href={HOME} className="btn btn-ghost">Back to overview</a>
          </div>
          <div style={{ marginTop: 56 }}><Mock /></div>
        </div>
      </header>

      <section className="feat" style={{ background: "var(--bg)" }}>
        <div className="wrap">
          <p className="sub" style={{ fontSize: 21, maxWidth: "46em", color: "var(--tx)" }}>{f.overview}</p>
        </div>
      </section>

      <section className="feat" style={{ background: "var(--bg-deep)", paddingTop: 80 }}>
        <div className="wrap">
          <div className="kicker" style={{ marginBottom: 10 }}>How it works</div>
          <h2 className="sec">Three steps, no spreadsheets.</h2>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 20, marginTop: 40 }}>
            {f.steps.map((s, i) => (
              <div key={s.t} style={{ padding: "26px 24px 28px", background: "var(--card)", border: "1px solid var(--divider)", borderRadius: 14 }}>
                <div style={{ fontSize: 20, fontWeight: 600, color: "#fff", marginBottom: 8 }}>{s.t}</div>
                <div style={{ fontSize: 14.5, color: "var(--tx-2)", lineHeight: 1.55 }}>{s.b}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="feat" style={{ background: "var(--bg)" }}>
        <div className="wrap">
          <div className="kicker" style={{ marginBottom: 10 }}>Capabilities</div>
          <h2 className="sec">What you get.</h2>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20, marginTop: 40 }}>
            {f.caps.map((c) => (
              <div key={c.t} style={{ display: "flex", gap: 14, padding: "22px 22px", background: "var(--card)", border: "1px solid var(--divider)", borderRadius: 14 }}>
                <span style={{ width: 38, height: 38, borderRadius: 9, flexShrink: 0, background: "rgba(145,128,212,0.14)", color: "var(--primary)", display: "flex", alignItems: "center", justifyContent: "center" }}><Check /></span>
                <div>
                  <div style={{ fontSize: 17, fontWeight: 600, color: "#fff", marginBottom: 5 }}>{c.t}</div>
                  <div style={{ fontSize: 14, color: "var(--tx-2)", lineHeight: 1.55 }}>{c.b}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="feat" style={{ background: "var(--bg-deep)" }}>
        <div className="wrap" style={{ display: "grid", gridTemplateColumns: "0.9fr 1.1fr", gap: 48, alignItems: "start" }}>
          <div>
            <div className="kicker" style={{ marginBottom: 10 }}>Coverage</div>
            <h2 className="sec">What it covers.</h2>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "14px 24px" }}>
            {f.coverage.map((c) => <div key={c} style={{ display: "flex", gap: 11, fontSize: 15, color: "var(--tx-2)", lineHeight: 1.4 }}><Check />{c}</div>)}
          </div>
        </div>
      </section>

      <section className="feat" style={{ background: "var(--bg)" }}>
        <div className="wrap">
          <div className="kicker" style={{ marginBottom: 24 }}>Explore the platform</div>
          <RelatedCards slugs={f.related} />
        </div>
      </section>

      <CTABand onContact={onContact} />
      <SiteFooter onContact={onContact} />
    </div>
  );
}

function CTABand({ onContact }) {
  return (
    <section className="grid-bg" style={{ position: "relative", overflow: "hidden", borderTop: "1px solid var(--divider-2)", padding: "110px 0" }}>
      <div className="noise-glow" style={{ position: "absolute", inset: 0, pointerEvents: "none" }} />
      <div className="wrap" style={{ position: "relative", textAlign: "center" }}>
        <h2 className="disp" style={{ fontSize: 52, maxWidth: "16em", margin: "0 auto" }}>See it on your own network.</h2>
        <p className="sub" style={{ margin: "20px auto 0", maxWidth: "32em" }}>Tell us about your estate and we'll set up a walkthrough.</p>
        <div style={{ display: "flex", gap: 13, marginTop: 32, justifyContent: "center" }}>
          <button onClick={onContact} className="btn btn-primary" style={{ cursor: "pointer" }}>Request access →</button>
          <button onClick={onContact} className="btn btn-ghost" style={{ cursor: "pointer" }}>Talk to the team</button>
        </div>
      </div>
    </section>
  );
}

window.SostratusPages = { FEATURES, FeaturePage, CTABand, RelatedCards };
