// pages-products.jsx — OrgLens & ReleaseGuard AI product pages
const { useState: useStateP2, useEffect: useEffectP2 } = React;

/* ═══════════════════════════════════════════════════════════════════════
   ORGLENS
   ═══════════════════════════════════════════════════════════════════════ */

const ORGLENS_NAV = [
  { id: "overview",    label: "Overview" },
  { id: "screens",     label: "Inside the product" },
  { id: "scan",        label: "Scan" },
  { id: "score",       label: "OrgScore" },
  { id: "backlog",     label: "Fix Backlog" },
  { id: "ai",          label: "AI Readiness" },
  { id: "partner",     label: "Partner Edition" },
];

const ORGLENS_SCREENS = [
  {
    id: "dashboard",
    tab: "Dashboard",
    src: "screenshots/orglens-dashboard.png",
    title: "OrgScore command center",
    caption: "A single 0–100 score across six categories. The dashboard surfaces what's bleeding, the 30-day trend, and the next 9 fixes that move the score most.",
  },
  {
    id: "backlog",
    tab: "Fix Backlog",
    src: "screenshots/orglens-backlog.png",
    title: "Prioritized findings, ready to push",
    caption: "Every finding is a remediation card: risk score, business impact, effort, suggested owner. One click pushes selected items to Jira.",
  },
  {
    id: "automap",
    tab: "Automation Map",
    src: "screenshots/orglens-automap.png",
    title: "What runs when records change",
    caption: "Trace triggers, flows, workflow rules, and process builders on a single object's save cycle. See where automation stacking creates governor-limit risk.",
  },
  {
    id: "ai",
    tab: "Agentforce Readiness",
    src: "screenshots/orglens-ai.png",
    title: "Is your org clean enough to trust with agents?",
    caption: "Most AI rollouts fail because of metadata, not models. OrgLens AI scores what agents read — descriptions, picklist consistency, duplicate fields, exposure surface.",
  },
  {
    id: "portfolio",
    tab: "Org Portfolio",
    src: "screenshots/orglens-portfolio.png",
    title: "Portfolio view for consultants and program leads",
    caption: "Roll up org health across the company. Spot the weakest org. Track remediation trends per business unit. Branded reports for SI partner engagements.",
  },
];

function PageOrgLens({ setRoute }) {
  const [section, setSection] = useStateP2("overview");

  return (
    <main id="main" className="page-enter">
      {/* HEADER */}
      <section style={{ paddingTop: 56, paddingBottom: 40, borderBottom: "1px solid var(--border-subtle)" }}>
        <div className="wrap-wide">
          <div className="row gap-16" style={{ marginBottom: 24 }}>
            <span className="pill pill-accent">ORGLENS AI</span>
            <span className="mono-sm muted">PRODUCT · ORG-HEALTH COMMAND CENTER</span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.6fr) minmax(0, 1fr)", gap: 64, alignItems: "end" }}
               className="ol-hero">
            <div>
              <h1 className="h-display">
                Scan your Salesforce org. <em>See what to fix first.</em>
              </h1>
              <p className="lead" style={{ marginTop: 24 }}>
                OrgLens AI scans your org and produces a single 0–100 score across six
                categories, a prioritized fix backlog with confidence and effort, and
                an executive-ready report that shows leadership exactly which hidden
                risks could turn the next launch, audit, or Agentforce rollout into a fire drill.
              </p>
              <div className="row gap-16" style={{ marginTop: 28, flexWrap: "wrap" }}>
                <button className="btn btn-primary btn-lg" onClick={() => setRoute("contact")}>Start free scan <IconArrow /></button>
                <a className="btn btn-secondary btn-lg" href="orglens-app/index.html" target="_blank" rel="noopener">
                  Try the live demo <IconExt />
                </a>
                <button className="btn btn-ghost btn-lg" onClick={() => setRoute("pricing")}>See pricing</button>
              </div>
            </div>
            <div className="card" style={{ padding: 24, display: "flex", alignItems: "center", gap: 24 }}>
              <ScoreRing value={57} size={120} stroke={6} animated />
              <div>
                <span className="pill pill-risk">AT RISK</span>
                <div className="h4" style={{ marginTop: 10 }}>Example org · Federal civilian</div>
                <div className="body-sm muted" style={{ marginTop: 4 }}>3,400 users · 11 sandboxes · 1,284 unused fields</div>
                <div className="body-sm" style={{ marginTop: 10, color: "var(--risk)" }}>One unowned permission path can become tomorrow's incident.</div>
              </div>
            </div>
          </div>
          <div style={{ marginTop: 40 }}>
            <TrustStrip />
          </div>
        </div>
      </section>

      {/* SUB NAV */}
      <div style={{ position: "sticky", top: "var(--nav-h)", background: "rgba(7,9,15,0.92)", backdropFilter: "blur(10px)", zIndex: 20, borderBottom: "1px solid var(--border-subtle)" }}>
        <div className="wrap-wide subnav">
          {ORGLENS_NAV.map((n) => (
            <button key={n.id}
                    onClick={() => {
                      setSection(n.id);
                      const el = document.getElementById(`ol-${n.id}`);
                      if (el) el.scrollIntoView({ block: "start", behavior: "smooth" });
                    }}
                    className={section === n.id ? "active" : ""}>
              {n.label}
            </button>
          ))}
        </div>
      </div>

      {/* OVERVIEW */}
      <section id="ol-overview" className="section">
        <div className="wrap-wide">
          <div className="row between" style={{ marginBottom: 40, alignItems: "flex-end", flexWrap: "wrap", gap: 16 }}>
            <div>
              <div className="eyebrow">// What it does</div>
              <h2 className="h1" style={{ marginTop: 12, maxWidth: 22 + "ch" }}>
                Six categories. <em style={{ color: "var(--text-secondary)", fontStyle: "normal" }}>One score.</em> One backlog.
              </h2>
            </div>
            <p className="body" style={{ maxWidth: 42 + "ch", color: "var(--text-secondary)" }}>
              The OrgScore is a transparent function of severity, blast radius, usage,
              business sensitivity, and confidence — not a black box. Every score is
              traceable to the rules and signals that produced it, so hidden debt stops
              masquerading as "business as usual."
            </p>
          </div>

          <InactionPanel
            title="Your org is either governed — or silently aging into a liability."
            body="The fields nobody can explain, flows nobody wants to edit, inactive owners nobody removed, and agent-facing descriptions nobody wrote are not harmless clutter. They are future outages, access findings, and AI mistakes waiting for the wrong release window."
            risks={[
              { label: "Launch risk", text: "Brittle automation and unmanaged dependencies surface when the business is already watching." },
              { label: "Access risk", text: "Dormant ownership, overlapping permissions, and guest exposure become hard questions fast." },
              { label: "Agent risk", text: "AI reads the org you have, not the org your roadmap assumes you have." },
            ]}
            cta="Run the scan before it finds you"
            onCta={() => setRoute("contact")}
          />

          <div className="grid grid-3" style={{ gap: 16, marginTop: 24 }}>
            <CategoryCard
              tag="01" name="Data Model Hygiene" status="warn" score={61}
              examples={["Unused custom fields", "Duplicate field candidates", "Picklist values never used", "Fields missing descriptions"]}
            />
            <CategoryCard
              tag="02" name="Automation Health" status="risk" score={48}
              examples={["Flow + trigger + WF rule stacking", "Flows missing fault paths", "Hard-coded IDs", "DML inside loops"]}
            />
            <CategoryCard
              tag="03" name="Security & Access" status="warn" score={72}
              examples={["Inactive users owning assets", "Permission set sprawl", "Profile overlap", "Guest user exposure"]}
            />
            <CategoryCard
              tag="04" name="Apex & Test Quality" status="warn" score={67}
              examples={["Concentration risk in test coverage", "SeeAllData=true classes", "Trigger handler pattern", "Async failure trends"]}
            />
            <CategoryCard
              tag="05" name="Release Readiness" status="warn" score={58}
              examples={["UAT vs Prod metadata drift", "Risky recent changes", "Dependency breakage risk", "Unmanaged package drift"]}
            />
            <CategoryCard
              tag="06" name="AI / Agentforce Readiness" status="risk" score={44}
              examples={["Field description completeness", "Conflicting status fields", "Permission boundaries for agents", "Object documentation gaps"]}
            />
          </div>
        </div>
      </section>

      {/* INSIDE THE PRODUCT — real screenshots */}
      <section id="ol-screens" className="section">
        <div className="wrap-wide">
          <div className="row between" style={{ marginBottom: 40, alignItems: "flex-end", flexWrap: "wrap", gap: 16 }}>
            <div>
              <div className="eyebrow">// Inside the product</div>
              <h2 className="h1" style={{ marginTop: 12, maxWidth: 22 + "ch" }}>
                Lightning by default. <em style={{ color: "var(--text-secondary)", fontStyle: "normal" }}>Your existing org chrome.</em>
              </h2>
            </div>
            <p className="body" style={{ maxWidth: 42 + "ch", color: "var(--text-secondary)" }}>
              OrgLens AI runs as a Salesforce-native managed package — Lightning Design System,
              your existing org chrome, no data leaves your tenant. Screens below are from
              the live product against a sample org.
            </p>
          </div>

          <ProductScreens screens={ORGLENS_SCREENS} />

          <div className="row" style={{ marginTop: 24, justifyContent: "flex-end", gap: 12 }}>
            <a className="btn btn-secondary" href="orglens-app/index.html" target="_blank" rel="noopener">
              Open live demo in new tab <IconExt />
            </a>
          </div>
        </div>
      </section>

      {/* SCAN */}
      <section id="ol-scan" className="section">
        <div className="wrap-wide">
          <div className="grid grid-2" style={{ gap: 64, alignItems: "center" }}>
            <div>
              <div className="eyebrow">// Scan</div>
              <h2 className="h2" style={{ marginTop: 12 }}>One-click via OAuth. Three depths.</h2>
              <p className="body" style={{ marginTop: 16 }}>
                Connect via OAuth, pick a scan depth, and let it run. OrgLens AI pulls
                metadata and usage signals — never customer data — and operates within
                Salesforce API limits with backoff.
              </p>
            </div>

            <div className="card-flat" style={{ overflow: "hidden" }}>
              <ScanDepth
                tag="QUICK"
                duration="2–5 min"
                desc="Metadata · permissions · unused fields · automation inventory"
              />
              <ScanDepth
                tag="DEEP"
                duration="10–30 min"
                desc="Apex · flows · test coverage · dependencies · historical usage"
              />
              <ScanDepth
                tag="PARTNER"
                duration="Variable"
                desc="Multi-org · client-branded report · exportable remediation roadmap"
                last
              />
            </div>
          </div>

          <div className="codeblock" style={{ marginTop: 32, maxWidth: 800 }}>
            <span style={{ color: "var(--accent)" }}>orglens scan</span> --org acme-fed-prod --depth deep --output backlog.csv
            <br /><span style={{ color: "var(--text-dim)" }}># →</span> connected · scanning 14,217 components · estimated 11 min
            <br /><span style={{ color: "var(--text-dim)" }}># →</span> 173 findings · OrgScore 57 · 9 P1 · 41 P2 · 87 P3 · 36 P4
          </div>
        </div>
      </section>

      {/* SCORE */}
      <section id="ol-score" className="section">
        <div className="wrap-wide">
          <div className="row between" style={{ marginBottom: 32, alignItems: "flex-end", flexWrap: "wrap", gap: 16 }}>
            <div>
              <div className="eyebrow">// Scoring</div>
              <h2 className="h2" style={{ marginTop: 12 }}>Every score, traceable to its inputs.</h2>
            </div>
          </div>

          <div className="grid grid-2" style={{ gap: 32 }}>
            <div className="card" style={{ padding: 28 }}>
              <div className="mono-sm muted" style={{ letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 16 }}>
                Example org · category breakdown
              </div>
              {ORGLENS_CATEGORIES.map((c) => (
                <CategoryRow key={c.key} label={c.label} value={c.score} status={c.status} note={c.note} />
              ))}
              <div className="row between" style={{ marginTop: 20 }}>
                <span className="mono-sm muted">Overall OrgScore</span>
                <div className="row gap-16">
                  <span className="pill pill-warn">AT RISK</span>
                  <span style={{ fontSize: 28, fontWeight: 300, color: "var(--text-primary)" }}>57</span>
                </div>
              </div>
            </div>

            <div className="card" style={{ padding: 28 }}>
              <div className="mono-sm muted" style={{ letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 16 }}>
                Priority formula
              </div>
              <div className="codeblock" style={{ marginTop: 0, marginBottom: 24 }}>
                priority =<br />
                {"  "}severity<br />
                {"  "}× blast_radius<br />
                {"  "}× usage_weight<br />
                {"  "}× business_sensitivity<br />
                {"  "}× confidence<br />
                {"  "}− fix_complexity_penalty
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                <PriorityRow level="P0" label="Immediate operational or security risk" />
                <PriorityRow level="P1" label="Fix in the next sprint" />
                <PriorityRow level="P2" label="Add to cleanup backlog" />
                <PriorityRow level="P3" label="Monitor" />
                <PriorityRow level="P4" label="Informational only" />
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* BACKLOG */}
      <section id="ol-backlog" className="section">
        <div className="wrap-wide">
          <div className="row between" style={{ marginBottom: 32, alignItems: "flex-end", flexWrap: "wrap", gap: 16 }}>
            <div>
              <div className="eyebrow">// Fix Backlog</div>
              <h2 className="h2" style={{ marginTop: 12 }}>Findings that become tickets.</h2>
            </div>
            <p className="body" style={{ maxWidth: 42 + "ch", color: "var(--text-secondary)" }}>
              Every finding is a remediation card: why it matters, recommended fix,
              business impact, effort estimate, suggested owner. One click creates a
              Jira story or an Azure DevOps work item.
            </p>
          </div>

          {/* Backlog table */}
          <div className="card" style={{ overflow: "hidden" }}>
            <table className="t">
              <thead>
                <tr>
                  <th style={{ width: 80 }}>Priority</th>
                  <th>Finding</th>
                  <th style={{ width: 200 }}>Object</th>
                  <th style={{ width: 110 }}>Effort</th>
                  <th style={{ width: 130 }}>Owner</th>
                  <th style={{ width: 110 }}>Confidence</th>
                </tr>
              </thead>
              <tbody>
                <BacklogRow priority="P1" finding="Opportunity has 7 overlapping automations"   object="Opportunity"  effort="Medium" owner="Admin + Dev" confidence="94%" />
                <BacklogRow priority="P1" finding="14 record-triggered flows missing fault paths" object="Multi-object" effort="Low"    owner="Admin" confidence="98%" />
                <BacklogRow priority="P1" finding="3 AI-authored flows lack reviewer attribution" object="Case · Renewal" effort="Low" owner="Admin" confidence="100%" />
                <BacklogRow priority="P2" finding="382 Account fields appear unused"              object="Account"      effort="Medium" owner="Admin" confidence="88%" />
                <BacklogRow priority="P2" finding="Apex test coverage concentrated in 2 classes" object="Apex"         effort="High"   owner="Developer" confidence="91%" />
                <BacklogRow priority="P2" finding="22 inactive users own reports + dashboards"   object="Users"        effort="Low"    owner="Admin" confidence="100%" />
                <BacklogRow priority="P3" finding="Permission set sprawl on Case object"         object="Case"         effort="Medium" owner="Admin" confidence="82%" />
                <BacklogRow priority="P3" finding="Workflow rules still active on Lead"          object="Lead"         effort="Low"    owner="Admin" confidence="100%" />
              </tbody>
            </table>
          </div>

          {/* Finding detail */}
          <div style={{ marginTop: 32 }}>
            <div className="mono-sm muted" style={{ letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 16 }}>
              // Drill-in · example
            </div>
            <div className="grid grid-2" style={{ gap: 16 }}>
              <FindingCard
                priority="P1"
                title="Opportunity has 7 overlapping automations"
                where="Object: Opportunity · 3 record-triggered flows + 1 Apex trigger + 2 WF rules + 1 PB"
                why="This stack increases the chance of order-of-execution bugs, failed saves, governor-limit errors, and unexpected field updates on a revenue object. The risk compounds when AI-assisted changes touch any one of the components."
                action="Consolidate legacy Workflow Rules and Process Builder logic into a single record-triggered flow architecture. Add fault paths and reviewer attribution."
                effort="4–8 hours"
                owner="Admin + Developer"
                confidence={94}
              />
              <FindingCard
                priority="P2"
                title="Account.Legacy_Segment__c appears unused"
                where="Object: Account · 0 records populated · 0 references · 0 reports"
                why="Custom fields that linger with no usage create cognitive load for admins, dilute report builder UX, and confuse agents grounded on the Account object."
                action="Mark for deprecation · hide from layouts · monitor 30 days · remove. Generate a destructive-changes package automatically."
                effort="15–30 minutes"
                owner="Admin"
                confidence={88}
              />
            </div>
          </div>
        </div>
      </section>

      {/* AI READINESS */}
      <section id="ol-ai" className="section">
        <div className="wrap-wide">
          <div className="grid grid-2" style={{ gap: 64, alignItems: "center" }}>
            <div>
              <div className="eyebrow eyebrow-accent">// AI Readiness</div>
              <h2 className="h2" style={{ marginTop: 12 }}>Don't deploy agents on a confused org.</h2>
              <p className="body" style={{ marginTop: 16 }}>
                Agentforce and copilots are only as safe as the metadata, automation,
                and permission boundaries underneath. OrgLens AI scores the readiness of
                each object — and tells you which Account-shaped chaos to clean before
                turning on a sales-facing agent.
              </p>
              <ul style={{ listStyle: "none", padding: 0, marginTop: 24, display: "flex", flexDirection: "column", gap: 12 }}>
                <ReadinessReason text="Field description completeness on key objects" />
                <ReadinessReason text="Conflicting status / stage / segment fields" />
                <ReadinessReason text="Sensitive data exposed to broad profiles" />
                <ReadinessReason text="Duplicate field candidates that confuse grounding" />
                <ReadinessReason text="Stale records with no owner / steward field" />
              </ul>
            </div>

            <div className="card" style={{ padding: 32 }}>
              <div className="row between" style={{ marginBottom: 20 }}>
                <span className="pill pill-risk">HIGH RISK</span>
                <span className="mono-sm muted">// AGENTFORCE READINESS</span>
              </div>
              <div className="row" style={{ gap: 24, alignItems: "flex-start" }}>
                <ScoreRing value={44} size={120} stroke={6} label="" animated />
                <div style={{ flex: 1 }}>
                  <div className="h3" style={{ marginBottom: 6 }}>44 / 100</div>
                  <div className="body-sm">Clean Account and Opportunity metadata before deploying sales-facing agents.</div>
                </div>
              </div>
              <hr className="div-h" />
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                <ReadinessBar label="Field descriptions" value={38} status="risk" />
                <ReadinessBar label="Picklist consistency" value={52} status="risk" />
                <ReadinessBar label="Automation clarity" value={49} status="risk" />
                <ReadinessBar label="Permission boundaries" value={67} status="warn" />
                <ReadinessBar label="Object documentation" value={31} status="risk" />
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* PARTNER */}
      <section id="ol-partner" className="section">
        <div className="wrap-wide">
          <div className="row between" style={{ marginBottom: 32, alignItems: "flex-end", flexWrap: "wrap", gap: 16 }}>
            <div>
              <div className="eyebrow">// Partner Edition</div>
              <h2 className="h2" style={{ marginTop: 12 }}>For the SIs delivering the work.</h2>
            </div>
            <p className="body" style={{ maxWidth: 42 + "ch", color: "var(--text-secondary)" }}>
              A scan that turns into a scoped engagement. Branded reports. Client
              portfolio dashboard. Proposal generator from findings.
            </p>
          </div>

          <div className="card" style={{ overflow: "hidden" }}>
            <div style={{ padding: "20px 24px", borderBottom: "1px solid var(--border-subtle)" }}>
              <div className="row between">
                <div className="mono-sm muted" style={{ letterSpacing: "0.08em", textTransform: "uppercase" }}>Portfolio</div>
                <span className="mono-sm muted">14 clients · last refresh 2h ago</span>
              </div>
            </div>
            <table className="t">
              <thead>
                <tr>
                  <th>Client</th>
                  <th>Sector</th>
                  <th>OrgScore</th>
                  <th>P1 risks</th>
                  <th>Last scan</th>
                  <th>Trend</th>
                </tr>
              </thead>
              <tbody>
                <PortfolioRow client="HORIZON-CIV" sector="Federal civilian" score={71} risks={8}  scan="2h ago"   trend="up" />
                <PortfolioRow client="BLUEROCK-FED" sector="Defense"          score={49} risks={31} scan="3d ago"   trend="down" />
                <PortfolioRow client="STATELINE-HHS" sector="SLED · HHS"      score={63} risks={14} scan="1w ago"   trend="flat" />
                <PortfolioRow client="AURORA-DEFENSE" sector="Defense program" score={58} risks={19} scan="Yesterday" trend="up" />
                <PortfolioRow client="MERIDIAN-EDU" sector="Higher education" score={77} risks={4}  scan="2d ago"   trend="up" />
                <PortfolioRow client="PINEGATE-FIN" sector="Regulated commercial" score={52} risks={22} scan="6h ago" trend="down" />
              </tbody>
            </table>
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="section">
        <div className="wrap-wide">
          <CTABanner
            kicker="// Start with a sandbox"
            title="Connect a sandbox. Get an OrgScore in five minutes."
            body="Free, no install in production, no customer data pulled. The scan reveals overall score, category scores, and your top three risks."
            primaryLabel="Start free scan"
            secondaryLabel="See pricing"
            onPrimary={() => setRoute("contact")}
            onSecondary={() => setRoute("pricing")}
          />
        </div>
      </section>

      <style>{`
        @media (max-width: 900px) {
          .ol-hero { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </main>
  );
}

function CategoryCard({ tag, name, status, score, examples }) {
  return (
    <div className="card" style={{ padding: 24 }}>
      <div className="row between" style={{ marginBottom: 16 }}>
        <span className="mono-sm muted">{tag}</span>
        <span className={`pill pill-${status === "ok" ? "ok" : status === "warn" ? "warn" : "risk"}`}>
          {status === "ok" ? "HEALTHY" : status === "warn" ? "NEEDS ATTENTION" : "HIGH RISK"}
        </span>
      </div>
      <h3 className="h3" style={{ marginBottom: 14 }}>{name}</h3>
      <div className="row gap-16" style={{ marginBottom: 18, alignItems: "baseline" }}>
        <span style={{ fontSize: 36, fontWeight: 300, letterSpacing: "-0.02em", color: "var(--text-primary)" }}>{score}</span>
        <span className="mono-sm muted">/ 100 example</span>
      </div>
      <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 6 }}>
        {examples.map((e, i) => (
          <li key={i} className="body-sm" style={{ display: "grid", gridTemplateColumns: "16px 1fr", gap: 8 }}>
            <span style={{ color: "var(--text-dim)" }}>·</span>
            <span>{e}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

function ScanDepth({ tag, duration, desc, last }) {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: "120px 1fr 120px",
      gap: 16,
      padding: "20px 24px",
      borderBottom: last ? "none" : "1px solid var(--border-subtle)",
      alignItems: "center",
    }}>
      <span className="pill pill-accent">{tag}</span>
      <span className="body-sm" style={{ color: "var(--text-primary)" }}>{desc}</span>
      <span className="mono-sm muted" style={{ textAlign: "right" }}>{duration}</span>
    </div>
  );
}

function PriorityRow({ level, label }) {
  return (
    <div className="row gap-16">
      <RiskPill level={level} />
      <span className="body-sm" style={{ color: "var(--text-secondary)" }}>{label}</span>
    </div>
  );
}

function BacklogRow({ priority, finding, object, effort, owner, confidence }) {
  return (
    <tr>
      <td><RiskPill level={priority} /></td>
      <td style={{ color: "var(--text-primary)" }}>{finding}</td>
      <td className="mono-cell">{object}</td>
      <td className="mono-cell">{effort}</td>
      <td className="mono-cell">{owner}</td>
      <td className="mono-cell" style={{ color: "var(--accent)" }}>{confidence}</td>
    </tr>
  );
}

function ReadinessReason({ text }) {
  return (
    <li style={{ display: "grid", gridTemplateColumns: "20px 1fr", gap: 12, alignItems: "start" }}>
      <span style={{ color: "var(--accent)", marginTop: 2 }}><IconCheck s={14} /></span>
      <span className="body-sm" style={{ color: "var(--text-secondary)" }}>{text}</span>
    </li>
  );
}

function ReadinessBar({ label, value, status }) {
  return (
    <div>
      <div className="row between" style={{ marginBottom: 6 }}>
        <span className="body-sm" style={{ color: "var(--text-secondary)" }}>{label}</span>
        <span className="mono-sm" style={{ color: "var(--text-primary)" }}>{value}</span>
      </div>
      <div className={`bar bar-${status}`}>
        <div style={{ width: `${value}%` }} />
      </div>
    </div>
  );
}

function PortfolioRow({ client, sector, score, risks, scan, trend }) {
  const status = score >= 75 ? "ok" : score >= 60 ? "warn" : "risk";
  const trendChar = trend === "up" ? "↗" : trend === "down" ? "↘" : "→";
  const trendColor = trend === "up" ? "var(--ok)" : trend === "down" ? "var(--risk)" : "var(--text-muted)";
  return (
    <tr>
      <td className="mono-cell" style={{ color: "var(--text-primary)" }}>{client}</td>
      <td>{sector}</td>
      <td>
        <div className="row gap-8">
          <div className={`bar bar-${status}`} style={{ width: 60 }}>
            <div style={{ width: `${score}%` }} />
          </div>
          <span className="mono" style={{ color: "var(--text-primary)" }}>{score}</span>
        </div>
      </td>
      <td className="mono-cell" style={{ color: risks > 20 ? "var(--risk)" : risks > 10 ? "var(--warn)" : "var(--text-primary)" }}>{risks}</td>
      <td className="mono-cell">{scan}</td>
      <td><span style={{ color: trendColor, fontSize: 18 }}>{trendChar}</span></td>
    </tr>
  );
}

/* ═══════════════════════════════════════════════════════════════════════
   RELEASEGUARD AI
   ═══════════════════════════════════════════════════════════════════════ */

const RG_NAV = [
  { id: "overview", label: "Overview" },
  { id: "screens",  label: "Inside the product" },
  { id: "flow",     label: "Workflow" },
  { id: "policy",   label: "Policy Pack" },
  { id: "engine",   label: "Review Engine" },
  { id: "audit",    label: "Audit Trail" },
  { id: "vs",       label: "Where it fits" },
  { id: "faq",      label: "FAQ" },
];

const RELEASEGUARD_SCREENS = [
  {
    id: "dashboard",
    tab: "Release Dashboard",
    src: "screenshots/releaseguard-dashboard.png",
    title: "Every release, every status, in one view",
    caption: "Active releases, blocked items, pending review, average readiness score. The dashboard is the room a release manager lives in.",
  },
  {
    id: "findings",
    tab: "AI Review Findings",
    src: "screenshots/releaseguard-findings.png",
    title: "Explainable findings, ranked by severity",
    caption: "Every finding shows what was found, why it matters, and the suggested remediation — alongside an inline AI copilot that summarises the release for approvers.",
  },
  {
    id: "score",
    tab: "Readiness Score",
    src: "screenshots/releaseguard-score.png",
    title: "Why the score is what it is",
    caption: "Weighted breakdown across Test Coverage, Security & Access, Required Artifacts, Approval Chain, Documentation, and Deployment Window. No black box.",
  },
  {
    id: "policy",
    tab: "Policy Pack Builder",
    src: "screenshots/releaseguard-policy.png",
    title: "Policy Pack Builder",
    caption: "Author your governance rules as a versioned policy pack. Required artifacts, security checks, naming conventions, approval chains, Agentforce-specific controls.",
  },
  {
    id: "artifacts",
    tab: "Artifact Generator",
    src: "screenshots/releaseguard-artifacts.png",
    title: "CAB-ready artifacts on demand",
    caption: "Generate the CAB notes, deployment checklist, rollback checklist, tester checklist, approver summary, and executive memo — all from the same review.",
  },
  {
    id: "audit",
    tab: "Audit Trail",
    src: "screenshots/releaseguard-audit.png",
    title: "An audit trail you can hand over",
    caption: "Immutable record of every governance action and policy decision. Every review, override, waiver, and approval — queryable and exportable.",
  },
];

function PageReleaseGuard({ setRoute }) {
  const [section, setSection] = useStateP2("overview");

  return (
    <main id="main" className="page-enter">
      {/* HEADER */}
      <section style={{ paddingTop: 56, paddingBottom: 40, borderBottom: "1px solid var(--border-subtle)" }}>
        <div className="wrap-wide">
          <div className="row gap-16" style={{ marginBottom: 24 }}>
            <span className="pill pill-accent">RELEASEGUARD AI</span>
            <span className="mono-sm muted">PRODUCT · RELEASE-READINESS COPILOT</span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.6fr) minmax(0, 1fr)", gap: 64, alignItems: "end" }}
               className="rg-hero">
            <div>
              <h1 className="h-display">
                Catch risky changes <em>before they ship.</em>
              </h1>
              <p className="lead" style={{ marginTop: 24 }}>
                ReleaseGuard AI is a governance layer above your DevOps pipeline. It
                reviews every release — human-authored or AI-generated — against your
                policy pack, produces an explainable readiness verdict, and writes a
                defensible audit trail before a missing rollback plan, weak test evidence,
                or undocumented AI change reaches UAT or production.
              </p>
              <div className="row gap-16" style={{ marginTop: 28, flexWrap: "wrap" }}>
                <button className="btn btn-primary btn-lg" onClick={() => setRoute("contact")}>Book a briefing <IconArrow /></button>
                <a className="btn btn-secondary btn-lg" href="releaseguard-app/index.html" target="_blank" rel="noopener">
                  Try the live demo <IconExt />
                </a>
                <button className="btn btn-ghost btn-lg" onClick={() => setRoute("pricing")}>See pricing</button>
              </div>
            </div>

            <div className="card" style={{ padding: 24 }}>
              <div className="row between" style={{ marginBottom: 16 }}>
                <span className="mono-sm muted">// release/2026.05.15-r2</span>
                <span className="pill pill-risk">BLOCKED</span>
              </div>
              <div className="h4" style={{ marginBottom: 14 }}>Not ready for UAT</div>
              <div className="body-sm" style={{ color: "var(--risk)", marginBottom: 14 }}>If this ships blind, the rollback conversation starts after users are already hurt.</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                <Statline icon="ok" label="5 policies passed" />
                <Statline icon="warn" label="2 require review" />
                <Statline icon="risk" label="1 blocker · missing rollback plan" />
              </div>
            </div>
          </div>
          <div style={{ marginTop: 40 }}>
            <TrustStrip />
          </div>
        </div>
      </section>

      {/* SUB NAV */}
      <div style={{ position: "sticky", top: "var(--nav-h)", background: "rgba(7,9,15,0.92)", backdropFilter: "blur(10px)", zIndex: 20, borderBottom: "1px solid var(--border-subtle)" }}>
        <div className="wrap-wide subnav">
          {RG_NAV.map((n) => (
            <button key={n.id}
                    onClick={() => {
                      setSection(n.id);
                      const el = document.getElementById(`rg-${n.id}`);
                      if (el) el.scrollIntoView({ block: "start", behavior: "smooth" });
                    }}
                    className={section === n.id ? "active" : ""}>
              {n.label}
            </button>
          ))}
        </div>
      </div>

      {/* INSIDE THE PRODUCT — real screenshots */}
      <section id="rg-screens" className="section">
        <div className="wrap-wide">
          <div className="row between" style={{ marginBottom: 40, alignItems: "flex-end", flexWrap: "wrap", gap: 16 }}>
            <div>
              <div className="eyebrow">// Inside the product</div>
              <h2 className="h1" style={{ marginTop: 12, maxWidth: 22 + "ch" }}>
                Lightning by default. <em style={{ color: "var(--text-secondary)", fontStyle: "normal" }}>AppExchange-native.</em>
              </h2>
            </div>
            <p className="body" style={{ maxWidth: 42 + "ch", color: "var(--text-secondary)" }}>
              ReleaseGuard AI is a Salesforce-native AppExchange managed package —
              Lightning Design System, your existing org chrome, no data leaves your
              tenant. Screens below are from the live product against a sample release.
            </p>
          </div>

          <ProductScreens screens={RELEASEGUARD_SCREENS} />

          <div className="row" style={{ marginTop: 24, justifyContent: "flex-end", gap: 12 }}>
            <a className="btn btn-secondary" href="releaseguard-app/index.html" target="_blank" rel="noopener">
              Open live demo in new tab <IconExt />
            </a>
          </div>
        </div>
      </section>

      {/* OVERVIEW */}
      <section id="rg-overview" className="section">
        <div className="wrap-wide">
          <div className="row between" style={{ marginBottom: 40, alignItems: "flex-end", flexWrap: "wrap", gap: 16 }}>
            <div>
              <div className="eyebrow">// Jobs to be done</div>
              <h2 className="h1" style={{ marginTop: 12, maxWidth: 24 + "ch" }}>
                Tell me if this release <em>can ship.</em>
              </h2>
            </div>
            <p className="body" style={{ maxWidth: 42 + "ch", color: "var(--text-secondary)" }}>
              Most teams govern releases through tickets, spreadsheets, screenshots,
              and tribal memory. ReleaseGuard standardizes the review, makes the
              verdict explainable, and captures every decision — before the evidence gap
              turns into an outage review or audit exception.
            </p>
          </div>

          <InactionPanel
            title="A risky release does not ask for permission before it becomes your reputation."
            body="Without a release gate above the pipeline, every deployment depends on memory: who reviewed the rollback plan, whether AI-authored components were disclosed, which waiver expired, and whether Friday coverage exists. ReleaseGuard forces those answers before production can punish the team."
            risks={[
              { label: "No rollback", text: "The missing artifact is harmless until recovery depends on it." },
              { label: "No provenance", text: "AI-assisted changes become indefensible when nobody can name the human reviewer." },
              { label: "No packet", text: "CAB approval without evidence becomes a liability the first time the release is challenged." },
            ]}
            cta="Block the next blind release"
            onCta={() => setRoute("contact")}
          />

          <div className="grid grid-4" style={{ gap: 16, marginTop: 24 }}>
            <JobCard num="01" title="Show me what's missing"  body="Before approval — not in the CAB meeting." />
            <JobCard num="02" title="Standardize the review"  body="The same checks, every release, every team, every org." />
            <JobCard num="03" title="Create the audit trail"  body="Approvals, waivers, policy versions — all queryable." />
            <JobCard num="04" title="Govern AI-authored change" body="Apply the same evidence standard, regardless of author." />
          </div>
        </div>
      </section>

      {/* WORKFLOW */}
      <section id="rg-flow" className="section">
        <div className="wrap-wide">
          <div className="eyebrow">// Workflow</div>
          <h2 className="h2" style={{ marginTop: 12, marginBottom: 40, maxWidth: 26 + "ch" }}>
            Intake → Review → Verdict → Audit. <em style={{ color: "var(--text-secondary)", fontStyle: "normal" }}>That's the loop.</em>
          </h2>

          <div className="card" style={{ padding: 32 }}>
            <div className="grid rg-flow-grid" style={{ gridTemplateColumns: "repeat(5, 1fr)", gap: 16, alignItems: "stretch" }}>
              <FlowStep num="01" title="Policy Pack"      body="YAML-defined rules, required artifacts, approval routing, blackout windows." />
              <FlowArrow />
              <FlowStep num="02" title="Change Intake"     body="Story, release notes, evidence, metadata diff. Manual upload or API." />
              <FlowArrow />
              <FlowStep num="03" title="AI Review Engine"  body="Compares the package to the policy pack. Flags gaps, risks, missing evidence." />
            </div>
            <div className="grid rg-flow-grid" style={{ gridTemplateColumns: "repeat(5, 1fr)", gap: 16, marginTop: 24, alignItems: "stretch" }}>
              <FlowStep num="04" title="Readiness Score"   body="Green / Yellow / Red. Each verdict carries its full reasoning trail." />
              <FlowArrow />
              <FlowStep num="05" title="Approval Packet"   body="CAB-ready summary, deployment checklist, rollback checklist, briefing." />
              <FlowArrow />
              <FlowStep num="06" title="Audit Trail"       body="Findings, overrides, waivers, policy version. Immutable. Exportable." />
            </div>
          </div>
        </div>
        <style>{`
          @media (max-width: 900px) {
            .rg-flow-grid { grid-template-columns: 1fr !important; }
            .rg-flow-grid svg { display: none; }
          }
        `}</style>
      </section>

      {/* POLICY PACK */}
      <section id="rg-policy" className="section">
        <div className="wrap-wide">
          <div className="grid grid-2" style={{ gap: 48, alignItems: "start" }}>
            <div>
              <div className="eyebrow">// Policy Pack</div>
              <h2 className="h2" style={{ marginTop: 12 }}>Your governance rules, as a versioned artifact.</h2>
              <p className="body" style={{ marginTop: 16 }}>
                Author your policy pack once, version it like code, attach it to a team
                or program line. Required artifacts, approval thresholds, AI-disclosure
                rules, blackout windows, and waiver routing — all explicit, all reviewable.
              </p>
              <ul style={{ listStyle: "none", padding: 0, marginTop: 24, display: "flex", flexDirection: "column", gap: 12 }}>
                <PolicyFeature title="Versioned" desc="Pinned per release. The pack that ran is the pack that's audited." />
                <PolicyFeature title="Composable" desc="Inherit from a baseline (e.g. CoE-Fed-v3.2). Override per program line." />
                <PolicyFeature title="Authored, not configured" desc="YAML you can diff, review, and submit through change control." />
                <PolicyFeature title="AI-aware" desc="Tag AI-authored changes and route them through a separate approval lane." />
              </ul>
            </div>
            <div className="codeblock" style={{ fontSize: 12.5 }}>
              <span style={{ color: "var(--accent)" }}>policy:</span> CoE-Fed-v3.2<br />
              <span style={{ color: "var(--text-dim)" }}># Federal civilian agency baseline · accessibility-mandatory</span><br />
              <br />
              <span style={{ color: "var(--accent)" }}>required_artifacts:</span><br />
              {"  - story_with_acceptance_criteria"}<br />
              {"  - test_evidence_pos_neg"}<br />
              {"  - security_review_note"}<br />
              {"  - rollback_plan"}<br />
              {"  - section_508_review     "}<span style={{ color: "var(--text-dim)" }}># mandatory</span><br />
              <br />
              <span style={{ color: "var(--accent)" }}>ai_changes:</span><br />
              {"  disclosure: required"}<br />
              {"  human_review_tag: required"}<br />
              {"  treat_as_third_party_dep: true"}<br />
              <br />
              <span style={{ color: "var(--accent)" }}>blackout_windows:</span><br />
              {"  - "}<span style={{ color: "var(--text-primary)" }}>"2026-05-30/2026-06-02"</span>{" "}<span style={{ color: "var(--text-dim)" }}># FY26 close</span><br />
              <br />
              <span style={{ color: "var(--accent)" }}>thresholds:</span><br />
              {"  apex_coverage_min: 80"}<br />
              {"  blocker_count_max: 0"}<br />
              {"  review_count_max: 3"}<br />
              <br />
              <span style={{ color: "var(--accent)" }}>waivers:</span><br />
              {"  approvers: [release_manager, qa_lead, security_owner]"}<br />
              {"  expiry_days_max: 30"}
            </div>
          </div>
        </div>
      </section>

      {/* REVIEW ENGINE */}
      <section id="rg-engine" className="section">
        <div className="wrap-wide">
          <div className="eyebrow">// Review Engine</div>
          <h2 className="h2" style={{ marginTop: 12, marginBottom: 40 }}>
            Eight checks. Every release. Every author.
          </h2>

          <div className="grid grid-2" style={{ gap: 16 }}>
            <CheckCard num="01" name="User story & acceptance criteria"
                       desc="Links to a tracked story · all ACs accounted for · scope inside change envelope." />
            <CheckCard num="02" name="Test evidence & coverage delta"
                       desc="Apex coverage threshold · positive + negative path evidence · regression-pack signature." />
            <CheckCard num="03" name="Security & permission impact"
                       desc="FLS deltas reviewed · no new system perms without justification · sensitive-object guard." />
            <CheckCard num="04" name="Naming convention & description policy"
                       desc="Metadata named per CoE standard · descriptions present and meaningful." />
            <CheckCard num="05" name="Dependency & rollback plan"
                       desc="Required rollback artifacts present · no references to deprecated components." />
            <CheckCard num="06" name="Blackout window check"
                       desc="Release window inside approved deploy schedule · holiday and FY-close awareness." />
            <CheckCard num="07" name="Audit trail completeness"
                       desc="Approver chain · CAB notes · waiver log · policy version — all present." />
            <CheckCard num="08" name="AI-authored change disclosure" accent
                       desc="AI-generated components flagged · human reviewer attribution required · model + version logged." />
          </div>
        </div>
      </section>

      {/* AUDIT TRAIL */}
      <section id="rg-audit" className="section">
        <div className="wrap-wide">
          <div className="row between" style={{ marginBottom: 32, alignItems: "flex-end", flexWrap: "wrap", gap: 16 }}>
            <div>
              <div className="eyebrow">// Audit Trail</div>
              <h2 className="h2" style={{ marginTop: 12 }}>An audit trail you can hand over.</h2>
            </div>
          </div>

          <div className="card" style={{ overflow: "hidden" }}>
            <div style={{ padding: "16px 24px", borderBottom: "1px solid var(--border-subtle)", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 16 }}>
              <div className="row gap-16">
                <span className="mono-sm" style={{ color: "var(--text-primary)" }}>release/2026.05.15-r2 · audit</span>
                <span className="pill pill-dim">IMMUTABLE</span>
              </div>
              <span className="mono-sm muted">Policy: CoE-Fed-v3.2 · packet hash 9c1f…2a4e</span>
            </div>
            <table className="t">
              <thead>
                <tr>
                  <th style={{ width: 140 }}>Timestamp (UTC)</th>
                  <th style={{ width: 110 }}>Actor</th>
                  <th>Event</th>
                  <th style={{ width: 110 }}>Outcome</th>
                </tr>
              </thead>
              <tbody>
                <AuditRow ts="2026-05-13 14:02:18" actor="kavi.o"     event="Change intake · 12 components · 3 flagged AI-assisted" outcome="logged" />
                <AuditRow ts="2026-05-13 14:02:24" actor="rg.engine"  event="Policy pack pinned · CoE-Fed-v3.2 · hash 4f72…8e1d" outcome="ok" />
                <AuditRow ts="2026-05-13 14:02:31" actor="rg.engine"  event="Check 05 · Dependency & rollback plan · rollback.sql missing" outcome="block" />
                <AuditRow ts="2026-05-13 14:02:31" actor="rg.engine"  event="Check 08 · 1 of 3 AI components lacks reviewer attribution" outcome="warn" />
                <AuditRow ts="2026-05-13 14:02:31" actor="rg.engine"  event="Readiness verdict computed" outcome="blocked" />
                <AuditRow ts="2026-05-13 15:41:09" actor="m.rendell"  event="Rollback script attached · re-review requested" outcome="logged" />
                <AuditRow ts="2026-05-13 15:41:14" actor="rg.engine"  event="Re-run · all blockers resolved · 2 review items remain" outcome="conditional" />
                <AuditRow ts="2026-05-13 16:08:42" actor="j.halverson" event="Waiver · WP-2026-0511 · negative-path evidence · expiry 14 days" outcome="approved" />
                <AuditRow ts="2026-05-13 16:09:01" actor="rg.engine"  event="Final verdict · ready for promotion · packet sealed" outcome="ready" />
              </tbody>
            </table>
          </div>
        </div>
      </section>

      {/* WHERE IT FITS */}
      <section id="rg-vs" className="section">
        <div className="wrap-wide">
          <div className="eyebrow">// Where it fits</div>
          <h2 className="h2" style={{ marginTop: 12, marginBottom: 32, maxWidth: 28 + "ch" }}>
            Not another DevOps platform. <em style={{ color: "var(--text-secondary)", fontStyle: "normal" }}>The layer above them.</em>
          </h2>

          <div className="card" style={{ padding: 0 }}>
            <FitMatrix
              cols={["Concern", "DevOps Center / pipelines", "Testing tools", "ReleaseGuard AI"]}
              rows={[
                ["Move metadata between orgs",     "✓ Owns this",          "—",                  "Doesn't try to"],
                ["Run static analysis / tests",     "Partial",              "✓ Owns this",         "Consumes their output"],
                ["Define your governance rules",   "—",                    "—",                  "✓ Authored policy packs"],
                ["Decide whether a release ships", "Workflow only",        "Surfaces failures",   "✓ Explainable verdict"],
                ["Govern AI-authored changes",     "—",                    "Partial",            "✓ Built-in"],
                ["Produce an audit packet",        "Limited",              "—",                  "✓ Immutable trail"],
              ]}
            />
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section id="rg-faq" className="section">
        <div className="wrap-wide">
          <div className="row between" style={{ marginBottom: 40, alignItems: "flex-end", flexWrap: "wrap", gap: 16 }}>
            <div>
              <div className="eyebrow">// Frequently asked</div>
              <h2 className="h1" style={{ marginTop: 12, maxWidth: 22 + "ch" }}>
                Common questions <em style={{ color: "var(--text-secondary)", fontStyle: "normal" }}>from federal CoEs and SIs.</em>
              </h2>
            </div>
            <p className="body" style={{ maxWidth: 42 + "ch", color: "var(--text-secondary)" }}>
              Drawn from briefings with federal CoEs, defense program SIs, and regulated
              commercial teams. If yours is missing, the contact form is the fastest path.
            </p>
          </div>

          <FAQList items={RG_FAQS} />

          <div className="row" style={{ marginTop: 32, justifyContent: "flex-end" }}>
            <button className="btn btn-ghost btn-sm" onClick={() => setRoute("contact")}>
              Ask a different question <IconArrow />
            </button>
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="section">
        <div className="wrap-wide">
          <CTABanner
            kicker="// Pilot motion"
            title="A 30-day release-readiness assessment."
            body="Bring one program line. We author the policy pack with your team, run ReleaseGuard against three real releases, and produce a CAB-ready packet for each. If those releases already have the evidence, provenance, and rollback coverage they need, you will know. If not, you will be very glad you found out before production did."
            primaryLabel="Apply for the pilot"
            secondaryLabel="See pricing"
            onPrimary={() => setRoute("contact")}
            onSecondary={() => setRoute("pricing")}
          />
        </div>
      </section>

      <style>{`
        @media (max-width: 900px) {
          .rg-hero { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </main>
  );
}

function Statline({ icon, label }) {
  return (
    <div className="row gap-8" style={{ fontSize: 13 }}>
      <span className={`dot dot-${icon}`} />
      <span style={{ color: "var(--text-secondary)" }}>{label}</span>
    </div>
  );
}

function JobCard({ num, title, body }) {
  return (
    <div style={{ padding: 24, borderLeft: "1px solid var(--border-subtle)" }}>
      <div className="mono-sm" style={{ color: "var(--accent)", letterSpacing: "0.08em" }}>{num}</div>
      <h3 className="h4" style={{ marginTop: 10, marginBottom: 8 }}>{title}</h3>
      <p className="body-sm" style={{ margin: 0 }}>{body}</p>
    </div>
  );
}

function FlowStep({ num, title, body }) {
  return (
    <div style={{
      background: "var(--bg-elevated)",
      border: "1px solid var(--border-subtle)",
      borderRadius: "var(--r-2)",
      padding: 20,
    }}>
      <div className="mono-sm" style={{ color: "var(--accent)", letterSpacing: "0.08em", marginBottom: 12 }}>{num}</div>
      <h4 className="h4" style={{ marginBottom: 6 }}>{title}</h4>
      <p className="body-sm" style={{ margin: 0 }}>{body}</p>
    </div>
  );
}

function FlowArrow() {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "center" }}>
      <svg width="32" height="24" viewBox="0 0 32 24" aria-hidden="true">
        <line x1="0" y1="12" x2="26" y2="12" stroke="var(--border-strong)" strokeWidth="1.2" />
        <polyline points="20,6 28,12 20,18" fill="none" stroke="var(--border-strong)" strokeWidth="1.2" />
      </svg>
    </div>
  );
}

function PolicyFeature({ title, desc }) {
  return (
    <li style={{ display: "grid", gridTemplateColumns: "16px 1fr", gap: 12, alignItems: "start" }}>
      <span style={{ color: "var(--accent)", marginTop: 4 }}><IconCheck s={14} /></span>
      <div>
        <div style={{ fontSize: 14, color: "var(--text-primary)" }}>{title}</div>
        <div className="body-sm" style={{ marginTop: 2 }}>{desc}</div>
      </div>
    </li>
  );
}

function CheckCard({ num, name, desc, accent }) {
  return (
    <div className="card" style={{ padding: 24, borderColor: accent ? "var(--accent-border)" : "var(--border)" }}>
      <div className="row between" style={{ marginBottom: 12 }}>
        <span className="mono-sm" style={{ color: accent ? "var(--accent)" : "var(--text-muted)", letterSpacing: "0.08em" }}>CHECK · {num}</span>
        {accent && <span className="pill pill-accent">AI-AWARE</span>}
      </div>
      <h3 className="h4" style={{ marginBottom: 8 }}>{name}</h3>
      <p className="body-sm" style={{ margin: 0 }}>{desc}</p>
    </div>
  );
}

function AuditRow({ ts, actor, event, outcome }) {
  const map = {
    ok:          { color: "var(--ok)",    label: "OK" },
    block:       { color: "var(--risk)",  label: "BLOCK" },
    warn:        { color: "var(--warn)",  label: "WARN" },
    blocked:     { color: "var(--risk)",  label: "BLOCKED" },
    conditional: { color: "var(--warn)",  label: "CONDITIONAL" },
    ready:       { color: "var(--ok)",    label: "READY" },
    approved:    { color: "var(--ok)",    label: "APPROVED" },
    logged:      { color: "var(--text-muted)", label: "LOGGED" },
  };
  const m = map[outcome] || map.logged;
  return (
    <tr>
      <td className="mono-cell">{ts}</td>
      <td className="mono-cell" style={{ color: actor.startsWith("rg.") ? "var(--accent)" : "var(--text-primary)" }}>{actor}</td>
      <td>{event}</td>
      <td><span className="mono-sm" style={{ color: m.color, letterSpacing: "0.08em" }}>{m.label}</span></td>
    </tr>
  );
}

function FitMatrix({ cols, rows }) {
  return (
    <table className="t">
      <thead>
        <tr>
          {cols.map((c, i) => <th key={i} style={i === cols.length - 1 ? { color: "var(--accent)" } : {}}>{c}</th>)}
        </tr>
      </thead>
      <tbody>
        {rows.map((r, ri) => (
          <tr key={ri}>
            {r.map((cell, ci) => (
              <td key={ci} style={{
                color: ci === 0 ? "var(--text-primary)" : "var(--text-secondary)",
                fontFamily: ci === 0 ? "var(--font-sans)" : "var(--font-mono)",
                fontSize: ci === 0 ? 14 : 12,
                background: ci === r.length - 1 ? "rgba(74,127,255,0.04)" : undefined,
              }}>{cell}</td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

function CTABanner({ kicker, title, body, primaryLabel, secondaryLabel, onPrimary, onSecondary }) {
  return (
    <div style={{
      background: "var(--surface-0)",
      border: "1px solid var(--border)",
      borderRadius: "var(--r-3)",
      padding: "48px 40px",
      display: "grid",
      gridTemplateColumns: "1fr auto",
      alignItems: "center",
      gap: 32,
    }} className="cta-grid-2">
      <div>
        <div className="eyebrow eyebrow-accent">{kicker}</div>
        <h2 className="h1" style={{ marginTop: 12, maxWidth: 24 + "ch" }}>{title}</h2>
        <p className="body" style={{ marginTop: 16, maxWidth: 56 + "ch" }}>{body}</p>
      </div>
      <div className="col gap-16" style={{ minWidth: 220 }}>
        <button className="btn btn-primary btn-lg" onClick={onPrimary}>{primaryLabel} <IconArrow /></button>
        <button className="btn btn-secondary btn-lg" onClick={onSecondary}>{secondaryLabel}</button>
      </div>
      <style>{`
        @media (max-width: 760px) {
          .cta-grid-2 { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
}

/* ─────────────────────── Product screenshot tabs ─────────────────────── */

function ProductScreens({ screens }) {
  const [active, setActive] = useStateP2(0);
  const current = screens[active];

  return (
    <div className="card" style={{
      padding: 0,
      overflow: "hidden",
      boxShadow: "0 24px 64px rgba(0,0,0,0.4)",
    }}>
      {/* Tab bar with mock window chrome */}
      <div style={{
        display: "flex",
        alignItems: "center",
        gap: 0,
        padding: "10px 14px 0",
        borderBottom: "1px solid var(--border-subtle)",
        background: "var(--surface-0)",
        flexWrap: "wrap",
      }}>
        <div className="row gap-8" style={{ paddingBottom: 10, marginRight: 16 }}>
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--surface-2)" }} />
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--surface-2)" }} />
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--surface-2)" }} />
        </div>
        {screens.map((s, i) => (
          <button key={s.id} onClick={() => setActive(i)} style={{
            background: "transparent",
            border: 0,
            color: active === i ? "var(--text-primary)" : "var(--text-muted)",
            padding: "10px 14px",
            fontSize: 13,
            fontWeight: 500,
            letterSpacing: "-0.005em",
            borderBottom: `2px solid ${active === i ? "var(--accent)" : "transparent"}`,
            marginBottom: -1,
            transition: "color 120ms, border-color 120ms",
            whiteSpace: "nowrap",
          }}>
            {s.tab}
          </button>
        ))}
      </div>

      {/* Caption + screenshot */}
      <div style={{
        display: "grid",
        gridTemplateColumns: "minmax(0, 320px) minmax(0, 1fr)",
        gap: 32,
        padding: "28px",
        alignItems: "start",
      }} className="ps-grid">
        <div>
          <div className="mono-sm" style={{
            color: "var(--accent)",
            letterSpacing: "0.08em",
            textTransform: "uppercase",
            marginBottom: 10,
          }}>
            {String(active + 1).padStart(2, "0")} / {String(screens.length).padStart(2, "0")} · {current.tab}
          </div>
          <h3 className="h3" style={{ marginBottom: 12 }}>{current.title}</h3>
          <p className="body-sm" style={{ margin: 0 }}>{current.caption}</p>

          <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 4 }}>
            {screens.map((s, i) => (
              <button key={s.id} onClick={() => setActive(i)} style={{
                background: i === active ? "var(--surface-1)" : "transparent",
                border: 0,
                color: i === active ? "var(--text-primary)" : "var(--text-secondary)",
                fontFamily: "inherit",
                padding: "8px 12px",
                borderRadius: "var(--r-2)",
                textAlign: "left",
                fontSize: 12,
                display: "flex",
                alignItems: "center",
                gap: 10,
                cursor: "default",
                transition: "background 120ms, color 120ms",
              }}>
                <span className="mono-sm muted" style={{ width: 18 }}>{String(i + 1).padStart(2, "0")}</span>
                <span>{s.tab}</span>
                {i === active && (
                  <span style={{ marginLeft: "auto", color: "var(--accent)" }}>
                    <IconArrow s={14} />
                  </span>
                )}
              </button>
            ))}
          </div>
        </div>

        <div style={{
          background: "var(--bg-elevated)",
          border: "1px solid var(--border-subtle)",
          borderRadius: "var(--r-2)",
          overflow: "hidden",
          aspectRatio: "920 / 540",
          position: "relative",
        }}>
          {screens.map((s, i) => (
            <img
              key={s.id}
              src={s.src}
              alt={`${s.tab} screen — ${s.title}`}
              style={{
                position: "absolute",
                inset: 0,
                width: "100%",
                height: "100%",
                objectFit: "cover",
                objectPosition: "top left",
                opacity: i === active ? 1 : 0,
                transition: "opacity 320ms cubic-bezier(0.2, 0.6, 0.2, 1)",
                pointerEvents: i === active ? "auto" : "none",
                display: "block",
              }}
              loading={i === 0 ? "eager" : "lazy"}
            />
          ))}
        </div>
      </div>

      <style>{`
        @media (max-width: 900px) {
          .ps-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
}

/* ─────────────────────── FAQ data + component ─────────────────────── */

const RG_FAQS = [
  {
    q: "How is ReleaseGuard AI different from Copado, Gearset, or Flosum?",
    a: "Copado, Gearset, and Flosum are deployment pipeline tools — they move metadata from A to B. ReleaseGuard AI sits one layer earlier: it analyses *what* you're about to deploy before the pipeline runs, scores the risk using AI, maps downstream component dependencies, and generates a rollback plan automatically. You can run ReleaseGuard AI alongside any deployment tool you already use. It's not a replacement — it's the co-pilot your pipeline is missing.",
  },
  {
    q: "Does it require us to change our current deployment process?",
    a: "No. ReleaseGuard AI connects to your existing Salesforce org via a standard managed package install — no changes to your pipeline, no migration, no professional services engagement required to go live. Most customers complete their first AI-generated risk scan within 15 minutes of installation. If you use Copado, Gearset, or SFDX pipelines, ReleaseGuard AI runs alongside them via our pre-built hooks and the Slack integration works with any existing channel structure.",
  },
  {
    q: "How does the AI risk scoring actually work? Is it just static analysis?",
    a: "It's not static analysis. The AI engine combines three signals: metadata diff analysis (what changed and where), dependency graph traversal (what those changes affect downstream), and org-specific pattern recognition (what has historically caused failures in *your* org based on your release history). The score is dynamic — the same change in one org might score 30 and in another score 75, depending on how interconnected the affected components are in that specific org's configuration. The AI also gets more accurate over time as it learns your org's deployment patterns.",
  },
  {
    q: "We have strict data security requirements. What data leaves our org?",
    a: "Only metadata structure and component relationship data is transmitted for analysis — never record data, PII, or field values. ReleaseGuard AI is a Salesforce AppExchange managed package that has passed Salesforce's full Security Review, meaning it adheres to all Platform Encryption, FLS, and sharing model standards. All data in transit is encrypted via TLS 1.2+, and no customer metadata is used to train shared AI models. Enterprise customers can request a full Data Processing Agreement and security architecture review as part of the onboarding process.",
    flag: "high-stakes",
  },
  {
    q: "What happens when the AI blocks a deployment our team wants to push through?",
    a: "The AI never has the final word — your team does. A blocked deployment triggers an approval workflow where a designated approver (configurable per org, team, or release type) can review the specific risks flagged and override with a documented reason. That override is logged in the release history with the approver's name, timestamp, and the risk score at time of override — giving you a full audit trail for governance and post-incident review. We find that most teams value this because it creates accountability without removing authority.",
    flag: "high-stakes",
  },
  {
    q: "How long does an AI scan take on a large org with thousands of components?",
    a: "For a typical release changeset of 10–50 components, the AI scan completes in under 2 minutes. For large enterprise orgs running full-org dependency analysis (500+ components), initial scan times range from 4–8 minutes. Subsequent scans on the same org are significantly faster because ReleaseGuard AI caches the org's dependency graph and only re-analyses delta changes. We recommend running the scan as a pre-commit gate in your sandbox pipeline so results are ready before the deployment window opens.",
  },
  {
    q: "We're on Salesforce Government Cloud / Financial Services Cloud / Health Cloud. Is ReleaseGuard AI compatible?",
    a: "Yes. ReleaseGuard AI is compatible with all Salesforce cloud environments including Government Cloud (GovCloud), Financial Services Cloud, Health Cloud, and Manufacturing Cloud. The managed package respects each cloud's specific platform constraints and API versions. GovCloud customers should note that data residency remains within the GovCloud boundary — no metadata is transmitted outside of it. Please contact our team before installation in a GovCloud environment as there is a brief additional configuration step specific to that infrastructure.",
  },
  {
    q: "What does the onboarding process look like and how long until we see value?",
    a: "Day 1: install the managed package from AppExchange (under 10 minutes), connect your production org, and run your first AI risk scan. Most customers see their first meaningful insight — a flagged component they weren't aware of — within that first session. Week 1: configure your approval workflow, set team thresholds for risk score blocking, and connect your Slack channel. Week 2: run ReleaseGuard AI against your next scheduled release and review the AI-generated rollback plan with your team. By day 30, you'll have a full release history baseline and the AI's org-specific pattern recognition will be calibrated to your environment. There is no implementation fee, no required professional services, and no minimum onboarding period.",
  },
];

// Inline-render *italic* asterisks → <em> for emphasis in answers.
function renderEmphasis(text) {
  const parts = text.split(/(\*[^*]+\*)/g);
  return parts.map((p, i) =>
    /^\*[^*]+\*$/.test(p)
      ? <em key={i} style={{ fontStyle: "normal", color: "var(--text-primary)", fontWeight: 500 }}>{p.slice(1, -1)}</em>
      : <React.Fragment key={i}>{p}</React.Fragment>
  );
}

function FAQList({ items }) {
  const [open, setOpen] = useStateP2(0);

  return (
    <div style={{
      borderTop: "1px solid var(--border-subtle)",
      borderBottom: "1px solid var(--border-subtle)",
    }}>
      {items.map((item, i) => {
        const isOpen = open === i;
        return (
          <FAQItem
            key={i}
            num={String(i + 1).padStart(2, "0")}
            question={item.q}
            answer={item.a}
            flag={item.flag}
            isOpen={isOpen}
            onToggle={() => setOpen(isOpen ? -1 : i)}
          />
        );
      })}
    </div>
  );
}

function FAQItem({ num, question, answer, flag, isOpen, onToggle }) {
  return (
    <div style={{
      borderBottom: "1px solid var(--border-subtle)",
    }}>
      <button
        onClick={onToggle}
        aria-expanded={isOpen}
        style={{
          width: "100%",
          background: "transparent",
          border: 0,
          padding: "24px 0",
          textAlign: "left",
          display: "grid",
          gridTemplateColumns: "56px 1fr 28px",
          alignItems: "baseline",
          gap: 20,
          color: "inherit",
          cursor: "default",
          fontFamily: "inherit",
        }}
      >
        <span className="mono-sm" style={{
          color: isOpen ? "var(--accent)" : "var(--text-muted)",
          letterSpacing: "0.08em",
          transition: "color 160ms",
        }}>{num}</span>
        <span style={{
          fontSize: 17,
          lineHeight: 1.35,
          letterSpacing: "-0.008em",
          color: "var(--text-primary)",
          fontWeight: 400,
        }}>
          {question}
          {flag === "high-stakes" && (
            <span className="mono-sm" style={{
              marginLeft: 12,
              padding: "2px 8px",
              borderRadius: 999,
              color: "var(--accent)",
              border: "1px solid var(--accent-border)",
              background: "var(--accent-dim)",
              letterSpacing: "0.08em",
              verticalAlign: "middle",
              fontSize: 10,
            }}>OFTEN ASKED</span>
          )}
        </span>
        <span style={{
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
          color: "var(--text-secondary)",
          fontSize: 20,
          width: 28, height: 28,
          transition: "transform 200ms ease, color 160ms",
          transform: isOpen ? "rotate(45deg)" : "rotate(0)",
        }} aria-hidden="true">+</span>
      </button>

      <div
        style={{
          display: "grid",
          gridTemplateRows: isOpen ? "1fr" : "0fr",
          transition: "grid-template-rows 280ms cubic-bezier(0.2, 0.6, 0.2, 1)",
        }}
      >
        <div style={{ overflow: "hidden" }}>
          <div style={{
            display: "grid",
            gridTemplateColumns: "56px 1fr 28px",
            gap: 20,
            paddingBottom: 28,
          }}>
            <div />
            <p className="body" style={{
              margin: 0,
              maxWidth: 72 + "ch",
              color: "var(--text-secondary)",
              fontSize: 15.5,
              lineHeight: 1.65,
            }}>
              {renderEmphasis(answer)}
            </p>
            <div />
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PageOrgLens, PageReleaseGuard });
