// V2 — Anatomy (3D layer stack) + Build simulator
const { useState: useStateF, useEffect: useEffectF, useRef: useRefF } = React;

/* =============================================================================
   AnatomySection v2 — dark, isometric exploded stack, scroll-driven
   ============================================================================= */

const ANAT_LAYERS = [
  {
    num: "01", name: "DATA", glow: "#6D8DF7",
    title: "Start with the data.",
    body: "Datastores with 50+ field types, validation, audit mode and soft-delete. Define the shape once — tables, search index and REST API are generated instantly.",
  },
  {
    num: "02", name: "INTERFACE", glow: "#9B7CF7",
    title: "The UI writes itself.",
    body: "New/Edit forms, browse views, dashboards and document templates are derived from your datastores. Add a field, and it appears everywhere — no template work.",
  },
  {
    num: "03", name: "ACCESS", glow: "#5FB2E8",
    title: "Locked down by default.",
    body: "Security groups with datastore, field and row-level permissions. Default-deny, grant-only. SSO, 2FA and IP rules are switches, not projects.",
  },
  {
    num: "04", name: "OPERATE", glow: "#63C7A6",
    title: "Live, monitored, maintained.",
    body: "One-click deploys to UK-sovereign infrastructure. Backups, audit trail, error capture and uptime monitoring are part of the substrate — not bolt-ons.",
  },
];

function PlanePattern({ i }) {
  if (i === 0) return (
    <div className="anat2-pat">
      {[64, 82, 48, 74, 58].map((w, k) => (
        <div key={k} style={{ height: 7, width: `${w}%`, borderRadius: 4, background: "rgba(150,170,255,0.28)" }} />
      ))}
    </div>
  );
  if (i === 1) return (
    <div className="anat2-pat" style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gridTemplateRows: "1fr 1fr", gap: 8 }}>
      {[0, 1, 2, 3].map(k => <div key={k} style={{ borderRadius: 8, background: "rgba(175,150,255,0.22)", border: "1px solid rgba(175,150,255,0.3)" }} />)}
    </div>
  );
  if (i === 2) return (
    <div className="anat2-pat" style={{ display: "grid", gridTemplateColumns: "repeat(6,1fr)", gap: 6 }}>
      {Array.from({ length: 24 }).map((_, k) => (
        <div key={k} style={{ aspectRatio: "1", borderRadius: 4, background: [0,3,7,8,13,14,17,21].includes(k) ? "rgba(120,190,240,0.45)" : "rgba(120,190,240,0.12)" }} />
      ))}
    </div>
  );
  return (
    <div className="anat2-pat" style={{ display: "grid", placeItems: "center" }}>
      <svg width="100%" height="60" viewBox="0 0 200 60" fill="none">
        <path d="M0 40 h30 l8 -22 l12 36 l10 -28 l8 14 h40 l8 -18 l10 24 l8 -12 h66" stroke="rgba(120,220,180,0.6)" strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" />
      </svg>
    </div>
  );
}

function AnatomySection() {
  const [active, setActive] = useStateF(0);
  const sectionRef = useRefF(null);

  useEffectF(() => {
    const onScroll = () => {
      const el = sectionRef.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const total = el.offsetHeight - window.innerHeight;
      if (total <= 0) return;
      const raw = Math.max(0, Math.min(0.999, -rect.top / total));
      setActive(Math.min(ANAT_LAYERS.length - 1, Math.floor(raw * ANAT_LAYERS.length)));
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const goTo = (i) => {
    const el = sectionRef.current;
    if (!el) return;
    const total = el.offsetHeight - window.innerHeight;
    window.scrollTo({ top: el.offsetTop + (i / ANAT_LAYERS.length) * total + 8, behavior: "smooth" });
  };

  return (
    <section className="anat2" ref={sectionRef} style={{ minHeight: "165vh", paddingTop: 0, paddingBottom: 0 }}>
      <div className="container" style={{ paddingTop: 88 }}>
        <div style={{ textAlign: "center", maxWidth: 760, margin: "0 auto" }}>
          <span className="eyebrow" style={{ color: "rgba(255,255,255,0.55)" }}>Anatomy of an app</span>
          <h2 className="h-large" style={{ marginTop: 16, color: "#fff" }}>
            Four layers. <em style={{ fontFamily: "Instrument Serif, serif", fontStyle: "italic", fontWeight: 400 }} className="grad-text">One platform.</em>
          </h2>
          <p className="lead" style={{ margin: "16px auto 0", color: "rgba(255,255,255,0.6)" }}>
            Scroll — every serious application is these four layers. We generate and maintain all of them.
          </p>
        </div>
      </div>
      <div className="container">
        <div className="anat2-sticky">
          <div className="anat2-stage">
            <div className="anat2-scene">
              {ANAT_LAYERS.map((l, i) => (
                <div
                  key={l.num}
                  className={"anat2-plane" + (active === i ? " is-active" : "")}
                  style={{ "--i": i, "--glow": l.glow }}
                  onClick={() => goTo(i)}
                >
                  <span className="anat2-tag">{l.num} · {l.name}</span>
                  <PlanePattern i={i} />
                </div>
              ))}
            </div>
          </div>
          <div className="anat2-copy">
            <div className="anat2-rail" aria-hidden="true">
              <div className="anat2-rail-fill" style={{ height: `${((active + 1) / ANAT_LAYERS.length) * 100}%` }}></div>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {ANAT_LAYERS.map((l, i) => (
                <div key={l.num} className={"anat2-step" + (active === i ? " is-active" : "")} onClick={() => goTo(i)} style={{ "--glow": l.glow }}>
                  <span className="anat2-step-num">{l.num} — {l.name}</span>
                  <h4>{l.title}</h4>
                  <p>{l.body}</p>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* =============================================================================
   BuilderSection v2 — "watch your app assemble itself" simulator
   ============================================================================= */

const SIM_TYPES = [
  { id: "patients", label: "Patient registry",  noun: "patients" },
  { id: "crm",      label: "Sales CRM",         noun: "deals" },
  { id: "assets",   label: "Asset tracker",     noun: "assets" },
  { id: "tickets",  label: "Service desk",      noun: "tickets" },
  { id: "members",  label: "Membership portal", noun: "members" },
  { id: "pwa",      label: "Mobile PWA",        noun: "jobs" },
  { id: "booking",  label: "Booking system",    noun: "bookings" },
  { id: "shop",     label: "Online store",      noun: "orders" },
  { id: "lms",      label: "Learning platform", noun: "courses" },
  { id: "inventory",label: "Inventory & stock", noun: "SKUs" },
  { id: "events",   label: "Events & ticketing",noun: "attendees" },
  { id: "grants",   label: "Grants & casework", noun: "cases" },
];

const SIM_FEATURES = [
  { id: "rbac",    label: "Role-based access", step: "Applying security groups" },
  { id: "tenants", label: "Multi-tenant",      step: "Partitioning tenants" },
  { id: "stripe",  label: "Stripe billing",    step: "Connecting Stripe" },
  { id: "sso",     label: "Microsoft SSO",     step: "Connecting Azure AD" },
  { id: "sms",     label: "SMS alerts",        step: "Configuring SMS relay" },
  { id: "audit",   label: "Audit trail",       step: "Enabling audit mode" },
  { id: "pwa",     label: "Offline PWA",       step: "Enabling offline mode" },
  { id: "docs",    label: "PDF documents",     step: "Adding document templates" },
  { id: "search",  label: "Full-text search",  step: "Turning on search" },
  { id: "api",     label: "Public API",        step: "Turning on the API" },
  { id: "reports", label: "Reports & charts",  step: "Assembling report builder" },
  { id: "i18n",    label: "Multi-language",    step: "Loading translations" },
];

const SIM_ROWS = {
  patients: [["P-00481", "S. Patel", "Active"], ["P-00480", "M. Hughes", "Active"], ["P-00479", "R. Khan", "Triage"], ["P-00478", "T. Brown", "Active"], ["P-00477", "A. Singh", "Critical"], ["P-00476", "L. Wright", "Closed"]],
  assets:   [["AM-04482", "168 Counterbalance", "Out"], ["AM-04483", "Generator", "Stock"], ["AM-04484", "Light Meter", "Stock"], ["AM-04485", "Test Kit", "Out"], ["AM-04486", "Jack", "Repair"], ["AM-04487", "Laptop", "Stock"]],
  tickets:  [["T-22148", "Login fails on Safari", "Open"], ["T-22147", "Export missing rows", "Open"], ["T-22146", "SSO redirect loop", "Pending"], ["T-22145", "Slow dashboard", "Open"], ["T-22144", "2FA reset", "Resolved"], ["T-22143", "API rate limit", "Resolved"]],
  members:  [["M-0912", "Q. Adeyemi", "Founders"], ["M-0911", "K. Park", "Pro"], ["M-0910", "R. Singh", "Pro"], ["M-0909", "M. O'Neil", "Free"], ["M-0908", "L. Costa", "Pro"], ["M-0907", "T. Vance", "Founders"]],
  crm:      [["D-3391", "Northwind Ltd · £48k", "Proposal"], ["D-3390", "Globex · £12k", "Won"], ["D-3389", "Initech · £96k", "Negotiation"], ["D-3388", "Hooli · £7k", "Lost"], ["D-3387", "Acme HQ · £31k", "Qualified"], ["D-3386", "Stark Inc · £120k", "Proposal"]],
  pwa:      [["J-7742", "Boiler service · Leeds", "En route"], ["J-7741", "Meter read · York", "Done"], ["J-7740", "Leak repair · Hull", "Assigned"], ["J-7739", "Install · Ripon", "Done"], ["J-7738", "Survey · Otley", "Scheduled"], ["J-7737", "Callout · Selby", "En route"]],
  booking:  [["B-5521", "A. Chen · 09:00", "Confirmed"], ["B-5520", "R. Okafor · 10:00", "Confirmed"], ["B-5519", "M. Díaz · 11:00", "Held"], ["B-5518", "K. Yamada · 13:00", "Confirmed"], ["B-5517", "S. Ahmed · 14:00", "Cancelled"], ["B-5516", "L. Berg · 15:00", "Confirmed"]],
  shop:     [["#4821", "A. Chen · £128", "Paid"], ["#4820", "R. Okafor · £54", "Fulfilled"], ["#4819", "M. Díaz · £312", "Paid"], ["#4818", "K. Yamada · £20", "Refunded"], ["#4817", "S. Ahmed · £86", "Pending"], ["#4816", "T. Vance · £45", "Paid"]],
  lms:      [["C-118", "Safeguarding L2", "Live"], ["C-117", "Fire Safety", "Live"], ["C-116", "Manual Handling", "Draft"], ["C-115", "First Aid", "Live"], ["C-114", "GDPR Basics", "Live"], ["C-113", "Food Hygiene", "Archived"]],
  inventory:[["SKU-9042", "M6 Bolt · 4,120", "In stock"], ["SKU-9041", "Bearing 608", "Low"], ["SKU-9040", "O-ring 24mm", "In stock"], ["SKU-9039", "Coupling", "Backorder"], ["SKU-9038", "Gasket set", "In stock"], ["SKU-9037", "Drive belt", "Low"]],
  events:   [["A-2210", "H. Mensah · VIP", "Checked in"], ["A-2209", "P. Novak · GA", "Registered"], ["A-2208", "F. Rossi · GA", "Checked in"], ["A-2207", "D. Bauer · Speaker", "Registered"], ["A-2206", "N. Ito · GA", "No-show"], ["A-2205", "G. Silva · VIP", "Checked in"]],
  grants:   [["G-0471", "Community Fund · £8k", "Approved"], ["G-0470", "Youth Grant · £3k", "Review"], ["G-0469", "Arts Award · £12k", "Approved"], ["G-0468", "Access Fund · £2k", "Rejected"], ["G-0467", "Green Grant · £15k", "Review"], ["G-0466", "Skills Fund · £6k", "Approved"]],
};

function BuilderSection() {
  const [type, setType] = useStateF("patients");
  const [feats, setFeats] = useStateF(["rbac", "audit", "sso"]);
  const [phase, setPhase] = useStateF("idle");   // idle | building | done
  const [stepIdx, setStepIdx] = useStateF(0);

  const cfg = SIM_TYPES.find(t => t.id === type);
  const steps = [
    "Adding your data tables",
    "Laying out forms",
    "Arranging browse screens",
    "Connecting the dashboard",
    ...SIM_FEATURES.filter(f => feats.includes(f.id)).map(f => f.step),
    "Publishing your app",
  ];

  useEffectF(() => {
    if (phase !== "building") return;
    setStepIdx(0);
    const t = setInterval(() => {
      setStepIdx(i => {
        if (i + 1 >= steps.length) {
          clearInterval(t);
          setTimeout(() => setPhase("done"), 500);
          return i;
        }
        return i + 1;
      });
    }, 460);
    return () => clearInterval(t);
  }, [phase]);

  const reset = () => setPhase("idle");
  const toggleFeat = (id) => { setFeats(f => f.includes(id) ? f.filter(x => x !== id) : [...f, id]); reset(); };

  return (
    <section className="builder">
      <div className="container">
        <div style={{ maxWidth: 760, marginBottom: 48 }}>
          <span className="eyebrow">See it for yourself</span>
          <h2 className="h-large" style={{ marginTop: 16 }}>
            Watch your app <em style={{ fontFamily: "Instrument Serif, serif", fontStyle: "italic", fontWeight: 400 }} className="grad-text">assemble itself.</em>
          </h2>
          <p className="lead" style={{ marginTop: 16 }}>
            Point and click. No code, no terminal, no build step. The foundations — data, forms, screens, security — come together in one web-based, WYSIWYG interface. This is a taste of the real thing.
          </p>
        </div>

        <div className="builder-grid">
          <div className="builder-controls">
            <div>
              <span className="sim-label">1 — What are we building?</span>
              <div className="builder-tab">
                {SIM_TYPES.map(t => (
                  <button key={t.id} className={type === t.id ? "is-active" : ""} onClick={() => { setType(t.id); reset(); }}>
                    {t.label}
                  </button>
                ))}
              </div>
            </div>

            <div>
              <span className="sim-label">2 — Which foundations?</span>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                {SIM_FEATURES.map(f => {
                  const on = feats.includes(f.id);
                  return (
                    <button key={f.id} onClick={() => toggleFeat(f.id)} className={"sim-chip" + (on ? " is-on" : "")}>
                      {on ? "✓ " : "+ "}{f.label}
                    </button>
                  );
                })}
              </div>
            </div>

            <div>
              <span className="sim-label">3 — Generate</span>
              <button
                className="btn btn-primary sim-generate"
                disabled={phase === "building"}
                onClick={() => setPhase("building")}
              >
                {phase === "building" ? "Assembling…" : phase === "done" ? "Start over" : "Assemble app"}
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M13 3 5 13h6l-1 8 8-10h-6z"/></svg>
              </button>
              <p style={{ fontSize: 12, color: "var(--fg-faint)", marginTop: 10, maxWidth: 320 }}>
                Every part below is assembled visually — the same point-and-click steps you'd take in the builder.
              </p>
            </div>

            <div style={{ marginTop: "auto", padding: "16px 20px", background: "var(--bg-elev)", border: "1px solid var(--line)", borderRadius: 10, fontSize: 13, color: "var(--fg-muted)", lineHeight: 1.5 }}>
              <strong style={{ color: "var(--fg)" }}>Everything here is real platform behaviour:</strong> datastores, generated forms, permission matrices and publishing all work exactly like this — just with your data, all point-and-click.
            </div>
          </div>

          <div className="builder-stage">
            <div className="bp-bar">
              <span style={{ display: "flex", gap: 6 }}>
                <span style={{ width: 10, height: 10, borderRadius: 5, background: "#FF5F57" }}></span>
                <span style={{ width: 10, height: 10, borderRadius: 5, background: "#FEBC2E" }}></span>
                <span style={{ width: 10, height: 10, borderRadius: 5, background: "#27C93F" }}></span>
              </span>
              <span className="url">{cfg.noun}.activemanage.app</span>
            </div>

            {phase === "idle" && (
              <div className="sim-idle">
                <div className="sim-idle-ghost">
                  <div className="g-side"></div>
                  <div className="g-main">
                    <div className="g-bar"></div>
                    <div className="g-row"></div><div className="g-row"></div><div className="g-row"></div>
                  </div>
                </div>
                <p>Configure on the left, then press <strong>Generate app</strong>.</p>
              </div>
            )}

            {phase === "building" && (
              <div className="sim-build">
                <div className="sim-build-head">Assembling your app…</div>
                {steps.map((s, i) => (
                  <div key={s} className={"sim-build-step" + (i < stepIdx ? " done" : i === stepIdx ? " doing" : "")}>
                    <span className="mark">
                      {i < stepIdx ? (
                        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.5"><path d="M5 13l4 4L19 7"/></svg>
                      ) : i === stepIdx ? <span className="spin"></span> : null}
                    </span>
                    <span>{s}</span>
                    {i < stepIdx && <span className="tick-done">Done</span>}
                  </div>
                ))}
              </div>
            )}

            {phase === "done" && <SimResult cfg={cfg} feats={feats} />}
          </div>
        </div>
      </div>
    </section>
  );
}

// Finished app — platform-styled, elements pop in staggered
function SimResult({ cfg, feats }) {
  const rows = SIM_ROWS[cfg.id];
  const B = { side: "#EAEDF1", border: "#DDE2E8", blue: "#1C82C4", blueDk: "#14618F", tile: "#E7F1FB", title: "#2B4257", label: "#46535F", faint: "#8A95A1", line: "#EDF0F3", green: "#1F9254" };
  const has = (id) => feats.includes(id);
  const featLabel = (id) => SIM_FEATURES.find(f => f.id === id)?.label;

  const chip = (label, i) => (
    <span key={label} className="sim-pop" style={{ animationDelay: `${640 + i * 60}ms`, fontSize: 8, fontFamily: "var(--font-mono)", textTransform: "uppercase", letterSpacing: "0.05em", padding: "2px 7px", borderRadius: 999, border: `1px solid ${B.border}`, color: B.label, background: "#fff", whiteSpace: "nowrap" }}>{label}</span>
  );
  const statusColour = (s) =>
    ["Critical", "Repair", "Lost", "Cancelled", "Rejected", "Backorder"].includes(s) ? "#E5484D" :
    ["Triage", "Pending", "Out", "Held", "Review", "Low", "Scheduled", "No-show"].includes(s) ? "#C77700" :
    ["Closed", "Resolved", "Free", "Refunded", "Draft", "Archived", "Registered"].includes(s) ? B.faint :
    B.green;
  const statusBg = (s) => {
    const c = statusColour(s);
    return c === B.faint ? "#EEF0F2" : c + "1A";
  };

  // Sidebar nav is driven by the toggled foundations
  const nav = [
    { s: cfg.label, on: true },
    { s: "Dashboard", on: true },
    { s: "Reports & charts", on: has("reports") },
    { s: "Documents", on: has("docs") },
    { s: "Billing", on: has("stripe") },
    { s: "Messages", on: has("sms") },
    { s: "Audit log", on: has("audit") },
    { s: "API & webhooks", on: has("api") },
    { s: "Users & roles", on: true },
    { s: "Settings", on: true },
  ].filter(n => n.on);

  // KPI cards, some driven by foundations
  const kpis = [
    { k: "Total records", v: "4,128" },
    has("stripe") ? { k: "Revenue MTD", v: "£38.2k" } : { k: "Added this week", v: "216" },
    has("reports") ? { k: "Open reports", v: "7" } : { k: "Active today", v: "83" },
  ];

  // Toolbar buttons, feature-aware
  const tools = [
    has("search") && { t: "Search", primary: false },
    { t: "Filter", primary: false },
    { t: "Sort", primary: false },
    has("docs") && { t: "Export PDF", primary: false },
    (has("sms") || has("stripe")) && { t: has("stripe") ? "Invoice" : "Send SMS", primary: false },
    { t: "+ New", primary: true },
  ].filter(Boolean);

  const cols = ["Ref", "Name", "Owner", "Updated", "Status", ""];

  return (
    <div style={{ flex: 1, display: "grid", gridTemplateColumns: "134px 1fr", minHeight: 0, background: "#F6F8FA" }}>
      {/* Sidebar */}
      <div className="sim-pop" style={{ background: B.side, borderRight: `1px solid ${B.border}`, padding: 10, display: "flex", flexDirection: "column", gap: 2, overflow: "hidden" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 9, padding: "0 2px" }}>
          <img src="images/AMicon.svg" width="17" height="17" alt="" />
          <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 10, color: B.title, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{cfg.label}</span>
        </div>
        {has("tenants") && (
          <div className="sim-pop" style={{ animationDelay: "90ms", display: "flex", alignItems: "center", justifyContent: "space-between", padding: "5px 7px", marginBottom: 5, borderRadius: 5, border: `1px solid ${B.border}`, background: "#fff", fontSize: 8.5, color: B.label }}>
            <span style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>acme-hq</span>
            <span style={{ color: B.faint }}>▾</span>
          </div>
        )}
        {nav.map((n, i) => (
          <div key={n.s} className="sim-pop" style={{
            animationDelay: `${120 + i * 45}ms`,
            display: "flex", alignItems: "center", gap: 7,
            padding: "5px 8px", fontSize: 9.5, borderRadius: 5,
            background: i === 0 ? B.tile : "transparent",
            color: i === 0 ? B.blue : B.label, fontWeight: i === 0 ? 600 : 450,
            whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
          }}>
            <span style={{ width: 5, height: 5, borderRadius: 2, background: i === 0 ? B.blue : B.faint, flexShrink: 0, opacity: i === 0 ? 1 : 0.5 }}></span>
            {n.s}
          </div>
        ))}
        <div className="sim-pop" style={{ animationDelay: "560ms", marginTop: "auto", display: "flex", alignItems: "center", gap: 6, padding: "6px 7px", borderRadius: 5, background: "#fff", border: `1px solid ${B.border}` }}>
          <span style={{ width: 18, height: 18, borderRadius: "50%", background: B.blue, color: "#fff", display: "grid", placeItems: "center", fontSize: 8, fontWeight: 700, flexShrink: 0 }}>JD</span>
          <span style={{ fontSize: 8.5, color: B.label, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>J. Doe</span>
        </div>
      </div>

      {/* Main */}
      <div style={{ display: "flex", flexDirection: "column", minWidth: 0 }}>
        {/* Header + toolbar */}
        <div className="sim-pop" style={{ animationDelay: "200ms", padding: "10px 14px", borderBottom: `1px solid ${B.border}`, background: "#fff", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 13, color: B.title }}>{cfg.label}</div>
            <div style={{ fontSize: 8.5, fontFamily: "var(--font-mono)", color: B.faint }}>{rows.length} of 4,128 records{has("tenants") ? " · tenant: acme-hq" : ""}</div>
          </div>
          <div style={{ display: "flex", gap: 5, flexWrap: "wrap", justifyContent: "flex-end" }}>
            {tools.map((b, i) => (
              <span key={b.t} className="sim-pop" style={{
                animationDelay: `${260 + i * 45}ms`,
                fontSize: 9, fontWeight: 600, padding: "5px 10px", borderRadius: 6, whiteSpace: "nowrap",
                background: b.primary ? B.blue : "#fff",
                color: b.primary ? "#fff" : B.label,
                border: b.primary ? "none" : `1px solid ${B.border}`,
              }}>{b.t}</span>
            ))}
          </div>
        </div>

        {/* KPI cards */}
        <div style={{ display: "grid", gridTemplateColumns: `repeat(${kpis.length}, 1fr)`, gap: 8, padding: "10px 14px", background: "#F6F8FA" }}>
          {kpis.map((kp, i) => (
            <div key={kp.k} className="sim-pop" style={{ animationDelay: `${340 + i * 70}ms`, background: "#fff", border: `1px solid ${B.border}`, borderRadius: 7, padding: "8px 10px" }}>
              <div style={{ fontSize: 7.5, fontFamily: "var(--font-mono)", color: B.faint, textTransform: "uppercase", letterSpacing: "0.05em", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{kp.k}</div>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 16, color: B.title, marginTop: 2 }}>{kp.v}</div>
            </div>
          ))}
        </div>

        {/* Table */}
        <div style={{ flex: 1, background: "#fff", overflow: "hidden", borderTop: `1px solid ${B.border}` }}>
          <div style={{ display: "grid", gridTemplateColumns: "0.75fr 1.2fr 0.85fr 0.7fr 0.7fr 0.5fr", gap: 8, padding: "7px 14px", background: "#F4F6F8", borderBottom: `1px solid ${B.border}` }}>
            {cols.map((c, i) => (
              <span key={i} style={{ fontSize: 7.5, fontFamily: "var(--font-mono)", color: B.faint, textTransform: "uppercase", letterSpacing: "0.05em" }}>{c}</span>
            ))}
          </div>
          {rows.map((r, i) => (
            <div key={i} className="sim-pop" style={{
              animationDelay: `${420 + i * 55}ms`,
              display: "grid", gridTemplateColumns: "0.75fr 1.2fr 0.85fr 0.7fr 0.7fr 0.5fr", gap: 8,
              padding: "8px 14px", borderBottom: `1px solid ${B.line}`, fontSize: 10, alignItems: "center",
            }}>
              <span style={{ fontFamily: "var(--font-mono)", color: B.label }}>{r[0]}</span>
              <span style={{ color: B.title, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r[1]}</span>
              <span style={{ display: "flex", alignItems: "center", gap: 5, color: B.label, minWidth: 0 }}>
                <span style={{ width: 15, height: 15, borderRadius: "50%", background: B.tile, color: B.blue, display: "grid", placeItems: "center", fontSize: 6.5, fontWeight: 700, flexShrink: 0 }}>{r[1].replace(/[^A-Za-z]/g, "").slice(0, 2).toUpperCase() || "AM"}</span>
                <span style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", fontSize: 9 }}>{["A. Chen", "R. Okafor", "M. Díaz", "K. Yamada", "S. Ahmed", "L. Berg"][i % 6]}</span>
              </span>
              <span style={{ fontSize: 8.5, fontFamily: "var(--font-mono)", color: B.faint }}>{["2m", "1h", "3h", "1d", "2d", "4d"][i % 6]}</span>
              <span style={{ fontSize: 8, fontWeight: 700, color: statusColour(r[2]), background: statusBg(r[2]), padding: "2px 7px", borderRadius: 999, justifySelf: "start", whiteSpace: "nowrap" }}>{r[2]}</span>
              <span style={{ display: "flex", gap: 4, color: B.faint, justifySelf: "end" }}>
                <span style={{ width: 16, height: 16, borderRadius: 4, border: `1px solid ${B.border}`, display: "grid", placeItems: "center", fontSize: 9 }}>✎</span>
                <span style={{ width: 16, height: 16, borderRadius: 4, border: `1px solid ${B.border}`, display: "grid", placeItems: "center", fontSize: 10, lineHeight: 1 }}>⋯</span>
              </span>
            </div>
          ))}
        </div>

        {/* Footer: live + pagination + feature chips */}
        <div style={{ padding: "8px 14px", borderTop: `1px solid ${B.border}`, background: "#F4F6F8", display: "flex", gap: 6, flexWrap: "wrap", alignItems: "center" }}>
          <span className="sim-pop" style={{ animationDelay: "600ms", fontSize: 8, fontFamily: "var(--font-mono)", color: B.green, fontWeight: 700 }}>● LIVE</span>
          {has("pwa") && <span className="sim-pop" style={{ animationDelay: "620ms", fontSize: 8, fontFamily: "var(--font-mono)", color: B.blue, fontWeight: 700 }}>⤓ INSTALLABLE</span>}
          <div style={{ flex: 1 }}></div>
          {["REST API", ...feats.map(featLabel)].slice(0, 5).map((l, i) => chip(l, i))}
          <span style={{ display: "flex", gap: 3, alignItems: "center", marginLeft: 4 }}>
            {["‹", "1", "2", "›"].map((p, i) => (
              <span key={i} style={{ width: 16, height: 16, borderRadius: 4, display: "grid", placeItems: "center", fontSize: 8.5, fontFamily: "var(--font-mono)", background: p === "1" ? B.blue : "#fff", color: p === "1" ? "#fff" : B.label, border: `1px solid ${B.border}` }}>{p}</span>
            ))}
          </span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AnatomySection, BuilderSection });
