/* Common Works — Concept Homepages
   Three full alternate homepages, each committing to one structural idea
   end-to-end. Calibrated for the actual buyer: PE deal partners and
   operating partners. Institutional finish — engraving, work product,
   and console — no dev-tool tropes, no decorative noise.
   Reachable only from /lab; nothing here is wired into the live site
   until one is chosen. */
const { useState: useStateC, useEffect: useEffectC, useRef: useRefC } = React;

const CC_RM = !!(window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches);

/* ============================================================
   SHARED ANIMATION TOOLKIT
   ============================================================ */

/* 0..1 progress of an element travelling through the viewport. */
function useScrollProgress(ref) {
  const [p, setP] = useStateC(0);
  useEffectC(() => {
    const el = ref.current;
    if (!el) return;
    let raf = null;
    function onScroll() {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = null;
        const rect = el.getBoundingClientRect();
        const vh = window.innerHeight || document.documentElement.clientHeight;
        const total = rect.height + vh;
        setP(Math.max(0, Math.min(1, (vh - rect.top) / total)));
      });
    }
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    onScroll();
    return () => { window.removeEventListener("scroll", onScroll); window.removeEventListener("resize", onScroll); if (raf) cancelAnimationFrame(raf); };
  }, []);
  return p;
}

/* Fires once (or toggles) when an element scrolls into view. */
function useInView(ref, { once = true, threshold = 0.25 } = {}) {
  const [seen, setSeen] = useStateC(false);
  useEffectC(() => {
    const el = ref.current;
    if (!el) return;
    if (CC_RM || !("IntersectionObserver" in window)) { setSeen(true); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) { setSeen(true); if (once) io.disconnect(); }
        else if (!once) setSeen(false);
      });
    }, { threshold });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return seen;
}

/* Eased count-up toward a target once triggered. */
function useCountUp(target, run, dur = 1200) {
  const [v, setV] = useStateC(CC_RM ? target : 0);
  useEffectC(() => {
    if (CC_RM || !run) { if (CC_RM) setV(target); return; }
    let raf; const start = performance.now();
    function frame(now) {
      const p = Math.min(1, (now - start) / dur);
      const eased = 1 - Math.pow(1 - p, 3);
      setV(target * eased);
      if (p < 1) raf = requestAnimationFrame(frame);
    }
    raf = requestAnimationFrame(frame);
    return () => cancelAnimationFrame(raf);
  }, [run, target]);
  return v;
}

/* Headline whose words rise + fade in on mount. */
function KineticHeading({ text, className = "", as = "h1" }) {
  const [on, setOn] = useStateC(CC_RM);
  useEffectC(() => {
    if (CC_RM) return;
    const t = setTimeout(() => setOn(true), 90);
    return () => clearTimeout(t);
  }, []);
  const words = text.split(" ");
  const Tag = as;
  return (
    <Tag className={className + " kin" + (on ? " on" : "")}>
      {words.map((w, i) => (
        <span className="kin-w" key={i} style={{ transitionDelay: (i * 55) + "ms" }}>
          {w}{i < words.length - 1 ? " " : ""}
        </span>
      ))}
    </Tag>
  );
}

const CC_TABS = [
  { id: "concept-manifesto", path: "/lab/manifesto", n: "01", label: "Manifesto" },
  { id: "concept-systems", path: "/lab/systems", n: "02", label: "Systems" },
  { id: "concept-os", path: "/lab/os", n: "03", label: "Operating System" },
];

function ConceptTopbar({ current }) {
  return (
    <div className="concept-topbar">
      <a className="brand" href="/" onClick={(e) => { e.preventDefault(); window.__go("home"); }}>
        <BrandMark /><span className="wordmark">Common <b>Works</b></span>
      </a>
      <div className="concept-tabs">
        {CC_TABS.map((t) => (
          <a key={t.id} className={"concept-tab" + (current === t.id ? " on" : "")}
             href={t.path}
             onClick={(e) => { e.preventDefault(); window.__go(t.id); }}>
            <span className="concept-tab-n">{t.n}</span>{t.label}
          </a>
        ))}
      </div>
      <a className="concept-exit tlink" href="/lab" onClick={(e) => { e.preventDefault(); window.__go("lab"); }}>
        Back to lab <Arrow />
      </a>
    </div>
  );
}

/* ============================================================
   CONCEPT 01 — MANIFESTO
   The partner letter, engraved. Bank-note guilloche in place of
   tech decoration, a document masthead, a scroll-ignited thesis,
   engraved movement numerals, and Roman-numeral principles.
   ============================================================ */
const CC_MF_THESIS = "Most AI initiatives inside a portfolio company stall for the same reason: they get graded like technology, not like capital. We close that gap. We underwrite the opportunity before the deal closes, sequence it into the operating plan, and ship the system that makes it real.";

const CC_MF_WORK = [
  "An IC-ready read on where AI moves the thesis, sized and prioritized",
  "A sequenced operating plan, tied to the 100-day plan and board narrative",
  "Production systems inside the business, handed off to the operator",
];

const CC_MF_ROMAN = ["I", "II", "III", "IV", "V", "VI"];

/* Engraved guilloche rosette — the graphic language of a financial
   instrument, drawn in hairlines. Rotates once every six minutes. */
function MfGuilloche() {
  const N = 24;
  return (
    <svg className="mf-guilloche" viewBox="0 0 640 640" aria-hidden="true">
      <g className="mf-guilloche-spin">
        {Array.from({ length: N }, (_, i) => (
          <ellipse key={i} cx="320" cy="320" rx="286" ry="112"
                   transform={"rotate(" + ((180 / N) * i).toFixed(1) + " 320 320)"} />
        ))}
        <circle cx="320" cy="320" r="286" />
        <circle cx="320" cy="320" r="112" />
      </g>
    </svg>
  );
}

/* Scroll-scrubbed thesis — words ignite as you read down. */
function MfThesis() {
  const ref = useRefC(null);
  const p = useScrollProgress(ref);
  const words = CC_MF_THESIS.split(" ");
  const revealed = CC_RM ? words.length : Math.round(Math.max(0, (p - 0.12)) * words.length * 1.7);
  return (
    <section className="mf-thesis" ref={ref}>
      <div className="mf-thesis-sticky">
        <div className="mf-wrap">
          <span className="mf-thesis-marker">The position</span>
          <p className="mf-thesis-text">
            {words.map((w, i) => (
              <span key={i} className={"mf-word" + (i < revealed ? " on" : "")}>{w} </span>
            ))}
          </p>
        </div>
      </div>
    </section>
  );
}

/* One movement — engraved numeral drifts gently against the copy. */
function MfMovement({ s, i, work }) {
  const ref = useRefC(null);
  const p = useScrollProgress(ref);
  const shift = (p - 0.5) * 110;
  const inview = p > 0.08 && p < 0.97;
  return (
    <section className={"mf-movement" + (i % 2 === 1 ? " on-ink" : "")} ref={ref}>
      <span className="mf-movement-num" style={{ transform: "translateY(" + shift.toFixed(1) + "px)" }} aria-hidden="true">
        {String(i + 1).padStart(2, "0")}
      </span>
      <div className="mf-wrap mf-movement-grid">
        <div className={"mf-movement-body" + (inview ? " in" : "")}>
          <span className="mf-movement-stage">{s.stage} — {s.verb}</span>
          <h2>{s.title}</h2>
          <span className="mf-movement-rule" />
          <p>{s.body}</p>
          <div className="mf-movement-work"><b>Work product</b><span>{work}</span></div>
        </div>
      </div>
    </section>
  );
}

function ManifestoConcept() {
  const CW = window.CW;
  return (
    <div className="mf" data-screen-label="Concept — Manifesto">
      <ConceptTopbar current="concept-manifesto" />

      <section className="mf-hero">
        <MfGuilloche />
        <div className="mf-wrap mf-hero-in">
          <div className="mf-masthead">
            <span>Common Works</span>
            <span className="mf-masthead-mid">A working thesis on AI value creation</span>
            <span>New York · MMXXVI</span>
          </div>
          <KineticHeading text={CW.hero.headline} className="mf-hero-h" />
          <p className="mf-hero-sub">{CW.hero.sub}</p>
          <div className="mf-hero-meta">
            {CW.hero.meta.map((m) => (
              <div key={m.k}>
                <span className="mf-meta-k">{m.k}</span>
                <span className="mf-meta-v">{m.v}</span>
              </div>
            ))}
          </div>
        </div>
        <div className="mf-hero-cue" aria-hidden="true"><span /></div>
      </section>

      <MfThesis />

      {CW.arc.map((s, i) => <MfMovement key={s.title} s={s} i={i} work={CC_MF_WORK[i]} />)}

      <section className="mf-principles">
        <div className="mf-wrap">
          <span className="mf-eyebrow on-ink">Principles</span>
          <h2 className="mf-principles-h">Why Common Works</h2>
          <div className="mf-principles-list">
            {CW.diff.map((d, i) => (
              <div className="mf-principle" key={d.h}>
                <span className="mf-principle-n" aria-hidden="true">{CC_MF_ROMAN[i]}</span>
                <h3>{d.h}</h3>
                <p>{d.p}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="mf-cta">
        <div className="mf-wrap">
          <span className="mf-eyebrow on-forest">Correspondence</span>
          <h2>Evaluating a deal or planning value creation?</h2>
          <a className="mf-cta-link" href={"mailto:" + CW.email}>{CW.email} <Arrow /></a>
          <div className="mf-colophon">
            <span>Common Works</span>
            <span>{CW.location}</span>
            <span>{CW.domain}</span>
          </div>
        </div>
      </section>
    </div>
  );
}

/* ============================================================
   CONCEPT 02 — SYSTEMS
   The evidence file. The work product is the pitch: an engagement
   protocol, IC-grade documents with references and classification,
   a self-building reference architecture, and outcome cards.
   ============================================================ */
const CC_SYS_PHASES = [
  { n: "01", name: "Underwrite", artifact: "AI diligence memo", window: "Wks 0–6" },
  { n: "02", name: "Sequence", artifact: "Value creation plan", window: "Wks 6–12" },
  { n: "03", name: "Ship", artifact: "Production systems, live", window: "Wks 12–36" },
  { n: "04", name: "Hand off", artifact: "Capability owned in-house", window: "Wk 36 →" },
];

function SystemsProtocol() {
  return (
    <div className="sy-protocol">
      <div className="sy-doc-head">
        <span className="sy-doc-ref">Engagement protocol</span>
        <span className="sy-doc-title">Diligence through handoff</span>
        <span className="sy-chip">Standard sequence</span>
      </div>
      <div className="sy-protocol-body">
        <span className="sy-protocol-spine" aria-hidden="true"><i /></span>
        {CC_SYS_PHASES.map((p) => (
          <div className="sy-phase" key={p.n}>
            <span className="sy-phase-node" aria-hidden="true" />
            <span className="sy-phase-n">{p.n}</span>
            <span className="sy-phase-name">{p.name}<em>{p.artifact}</em></span>
            <span className="sy-phase-window">{p.window}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

const CC_SYS_ARTIFACTS = [
  {
    id: "memo", tab: "Diligence memo", ref: "CW-114-DM",
    title: "AI diligence memo — Project Meridian",
    context: "Prepared pre-close for the deal team and investment committee",
    rows: [
      { k: "Revenue growth", v: "+4.2%", note: "vs. 2.1% cohort average" },
      { k: "Gross margin", v: "61.8%", note: "+340 bps year over year" },
      { k: "Automation coverage", v: "32%", note: "18 processes identified" },
      { k: "Data maturity", v: "Tier 2", note: "Clean warehouse, no MLOps" },
      { k: "AI readiness score", v: "6.4 / 10", note: "Top-quartile potential" },
    ],
    verdict: "IC read: underwritable — Tier 1 conviction.",
  },
  {
    id: "blueprint", tab: "Value creation plan", ref: "CW-114-VC",
    title: "Value creation plan — 100-day plan",
    context: "Prepared with management in the first 30 days post-close",
    rows: [
      { k: "01 · Unify data warehouse", v: "Wks 1–12", note: "Foundation for every downstream initiative" },
      { k: "02 · Automate AR / AP matching", v: "Wks 6–16", note: "+180 bps margin, run-rate" },
      { k: "03 · Demand forecasting agent", v: "Wks 10–22", note: "Reduces working capital drag" },
      { k: "04 · Customer support copilot", v: "Wks 14–30", note: "Headcount avoidance at scale" },
    ],
    verdict: "Sequenced to the 100-day plan and board narrative.",
  },
  {
    id: "status", tab: "Delivery status", ref: "CW-114-SR",
    title: "Embedded pod — delivery status",
    context: "Circulated weekly to the operating partner and CEO",
    rows: [
      { k: "Unified data warehouse", v: "Live", note: "Handed off to the internal data team" },
      { k: "AR / AP matching agent", v: "Live", note: "Processing 100% of eligible invoices" },
      { k: "Demand forecasting agent", v: "In review", note: "Ops pilot, week 3 of 4" },
      { k: "Support copilot", v: "Queued", note: "Scoped, starts next sprint" },
    ],
    verdict: "Capability that stays after we leave — not a deck.",
  },
];

function SystemsArtifactPanel({ artifact }) {
  const [shown, setShown] = useStateC(false);
  useEffectC(() => {
    setShown(false);
    const t = setTimeout(() => setShown(true), 40);
    return () => clearTimeout(t);
  }, [artifact]);
  return (
    <div className={"sy-doc" + (shown ? " in" : "")}>
      <div className="sy-doc-head">
        <span className="sy-doc-ref">{artifact.ref}</span>
        <span className="sy-doc-title">{artifact.title}</span>
        <span className="sy-chip">Illustrative</span>
      </div>
      <div className="sy-doc-context">{artifact.context}</div>
      <div className="sy-doc-body">
        {artifact.rows.map((r, i) => (
          <div className="sy-doc-row" key={r.k} style={{ transitionDelay: (i * 70) + "ms" }}>
            <span className="sy-doc-k">{r.k}</span>
            <span className="sy-doc-v">{r.v}</span>
            <span className="sy-doc-note">{r.note}</span>
          </div>
        ))}
      </div>
      <div className="sy-doc-verdict">{artifact.verdict}</div>
      <div className="sy-doc-foot"><span>Common Works · New York</span><span>Page 1 of 1</span></div>
    </div>
  );
}

const CC_SYS_ARCH = [
  { n: "Data ingestion", sub: "ERP · CRM · ops systems" },
  { n: "Warehouse", sub: "Governed, tested models" },
  { n: "Intelligence", sub: "LLMs + evaluation harness" },
  { n: "Orchestration", sub: "Agents in the workflow" },
];

function SystemsArchitecture() {
  const ref = useRefC(null);
  const seen = useInView(ref, { threshold: 0.4 });
  const bw = 150, W = 760;
  const gap = (W - bw * CC_SYS_ARCH.length) / (CC_SYS_ARCH.length - 1);
  const xs = CC_SYS_ARCH.map((_, i) => i * (bw + gap));
  return (
    <div className={"sy-arch" + (seen ? " in" : "")} ref={ref}>
      <svg viewBox={"0 0 " + W + " 104"} aria-hidden="true">
        {CC_SYS_ARCH.slice(0, -1).map((_, i) => (
          <g key={i}>
            <line className="sy-arch-line" x1={xs[i] + bw} y1="52" x2={xs[i + 1]} y2="52" pathLength="1"
                  style={{ transitionDelay: (0.25 + i * 0.28) + "s" }} />
            <line className="sy-arch-flow" x1={xs[i] + bw} y1="52" x2={xs[i + 1]} y2="52"
                  style={{ animationDelay: (i * 0.4) + "s" }} />
          </g>
        ))}
        {CC_SYS_ARCH.map((a, i) => (
          <g className="sy-arch-node" key={a.n} style={{ transitionDelay: (i * 0.28) + "s" }}>
            <rect x={xs[i]} y="22" width={bw} height="60" rx="2" />
            <text className="sy-arch-name" x={xs[i] + bw / 2} y="48">{a.n}</text>
            <text className="sy-arch-sub" x={xs[i] + bw / 2} y="67">{a.sub}</text>
          </g>
        ))}
      </svg>
      <p className="sy-illustrative kicker">Installed inside the portfolio company's environment and handed off to its team.</p>
    </div>
  );
}

const CC_SYS_SPARKS = [
  { label: "Time to first production ship", metric: "6 wks", note: "Median, from pod start", d: "M0,7 L12,9 L24,8 L36,15 L48,14 L60,21 L72,20 L84,26 L96,28" },
  { label: "Automation coverage", metric: "32% → 71%", note: "Over an 18-month hold", d: "M0,33 L12,31 L24,27 L36,29 L48,19 L60,21 L72,11 L84,13 L96,3" },
  { label: "Initiatives sequenced", metric: "14", note: "Ranked by EBITDA impact", d: "M0,27 L12,25 L24,26 L36,19 L48,17 L60,15 L72,10 L84,8 L96,4" },
];

function SystemsSparklines() {
  const ref = useRefC(null);
  const seen = useInView(ref, { threshold: 0.35 });
  return (
    <div className={"sy-sparks" + (seen ? " in" : "")} ref={ref}>
      {CC_SYS_SPARKS.map((c, i) => (
        <div className="sy-spark-card" key={c.label}>
          <span className="sy-spark-label">{c.label}</span>
          <svg className="sy-spark-svg" viewBox="0 0 96 36" preserveAspectRatio="none" aria-hidden="true">
            <line className="base" x1="0" y1="35.5" x2="96" y2="35.5" />
            <path className="ln" d={c.d} pathLength="1" style={{ transitionDelay: (0.15 + i * 0.18) + "s" }} />
          </svg>
          <span className="sy-spark-metric">{c.metric}</span>
          <span className="sy-spark-note">{c.note}</span>
        </div>
      ))}
    </div>
  );
}

function SystemsConcept() {
  const CW = window.CW;
  const [active, setActive] = useStateC(0);
  const sectors = ["Industrials", "Healthcare", "Financial Services", "Consumer", "Data & Infra"];
  return (
    <div className="sy" data-screen-label="Concept — Systems">
      <ConceptTopbar current="concept-systems" />

      <section className="sy-hero">
        <div className="wrap-wide sy-hero-grid">
          <div className="sy-hero-copy">
            <span className="eyebrow">Common Works — Concept 02</span>
            <KineticHeading text="The output isn't a deck. It's a working system." className="sy-hero-h display" />
            <p className="sy-hero-sub lead">{CW.hero.sub}</p>
          </div>
          <SystemsProtocol />
        </div>
      </section>

      <section className="sy-artifacts">
        <div className="wrap-wide">
          <div className="sec-head">
            <div className="eyebrow">The work product</div>
            <h2 className="display">Three documents carry the engagement.</h2>
          </div>
          <div className="sy-tabs">
            {CC_SYS_ARTIFACTS.map((a, i) => (
              <button key={a.id} className={"sy-tab" + (active === i ? " on" : "")} onClick={() => setActive(i)}>
                <span className="sy-tab-n">{"0" + (i + 1)}</span>{a.tab}
              </button>
            ))}
          </div>
          <SystemsArtifactPanel artifact={CC_SYS_ARTIFACTS[active]} />
          <p className="sy-illustrative kicker">Illustrative artifacts — representative of engagement deliverables, not a specific client's data.</p>
        </div>
      </section>

      <section className="sy-arch-sec band-cream2">
        <div className="wrap-wide">
          <div className="sec-head">
            <div className="eyebrow">What we install</div>
            <h2 className="display">The system builds toward production.</h2>
          </div>
          <SystemsArchitecture />
        </div>
      </section>

      <section className="sy-stats">
        <div className="wrap-wide">
          <span className="kicker sy-stats-label">Representative engagement outcomes — illustrative</span>
          <SystemsSparklines />
        </div>
      </section>

      <section className="sy-sectors">
        <div className="wrap-wide sy-sectors-row">
          <span className="kicker sy-sectors-label">Sector coverage</span>
          <div className="sy-sectors-list">
            {sectors.map((s) => <span key={s} className="sy-sector">{s}</span>)}
          </div>
        </div>
      </section>

      <CTABand />
    </div>
  );
}

/* ============================================================
   CONCEPT 03 — OPERATING SYSTEM
   The engagement console. A disciplined instrument panel: phase
   stepper, readiness gauge, an interactive value-creation bridge,
   a week-gridded operating plan, and a delivery ledger.
   ============================================================ */

const CC_OS_FACTS = [
  { k: "Sector", v: "Industrials" },
  { k: "EV at entry", v: "$340M" },
  { k: "Hold plan", v: "4 years" },
  { k: "Pod", v: "4 engineers" },
];

const CC_OS_PHASES = [
  { label: "Diligence", status: "Complete", done: true },
  { label: "Blueprint", status: "Complete", done: true },
  { label: "Build", status: "Week 14 of 26", current: true },
];

/* Readiness gauge: counts up once and holds. Scored, not noisy. */
function OsGauge() {
  const ref = useRefC(null);
  const seen = useInView(ref, { threshold: 0.3 });
  const v = useCountUp(6.4, seen, 1400);
  const R = 40, C = 2 * Math.PI * R, frac = v / 10;
  return (
    <div className="os-gauge" ref={ref}>
      <svg viewBox="0 0 100 100" aria-hidden="true">
        <circle className="os-gauge-ticks" cx="50" cy="50" r="46" />
        <circle className="os-gauge-track" cx="50" cy="50" r={R} />
        <circle className="os-gauge-fill" cx="50" cy="50" r={R} transform="rotate(-90 50 50)"
                style={{ strokeDasharray: C, strokeDashoffset: C * (1 - frac) }} />
      </svg>
      <div className="os-gauge-val"><b>{v.toFixed(1)}</b><span>/ 10</span></div>
    </div>
  );
}

/* Interactive value-creation bridge — entry EV to exit EV. */
function OsUnderwriteModule() {
  const [ebitda, setEbitda] = useStateC(20);
  const [uplift, setUplift] = useStateC(6);
  const [on, setOn] = useStateC(CC_RM);
  useEffectC(() => {
    if (CC_RM) return;
    const t = setTimeout(() => setOn(true), 60);
    return () => clearTimeout(t);
  }, []);
  const MULT = 8.5, HOLD = 4, ORGANIC = 0.03;
  const E = Math.max(0, ebitda);
  const entry = E * MULT;
  const organic = E * ORGANIC * HOLD * MULT;
  const ai = E * (Math.max(0, uplift) / 100) * HOLD * MULT;
  const exit = entry + organic + ai;
  const max = Math.max(exit, 1) * 1.16;
  const moic = entry > 0 ? exit / entry : 0;
  const aiShare = (organic + ai) > 0 ? (ai / (organic + ai)) * 100 : 0;
  const steps = [
    { label: "Entry EV", cls: "entry", from: 0, to: entry, txt: "$" + entry.toFixed(0) + "M" },
    { label: "Organic growth", cls: "organic", from: entry, to: entry + organic, txt: "+$" + organic.toFixed(0) + "M" },
    { label: "AI value creation", cls: "ai", from: entry + organic, to: exit, txt: "+$" + ai.toFixed(0) + "M" },
    { label: "Exit EV", cls: "exit", from: 0, to: exit, txt: "$" + exit.toFixed(0) + "M" },
  ];
  return (
    <div className="os-module">
      <div className="os-module-top">
        <div className="os-module-inputs">
          <label>EBITDA at entry ($M)
            <input type="number" value={ebitda} min="1" onChange={(e) => setEbitda(+e.target.value || 0)} />
          </label>
          <label>AI-driven EBITDA uplift (% / yr)
            <input type="number" value={uplift} min="0" max="30" onChange={(e) => setUplift(+e.target.value || 0)} />
          </label>
        </div>
        <div className="os-readout">
          <div className="os-readout-item"><b>{moic.toFixed(1)}x</b><span>Implied MOIC</span></div>
          <div className="os-readout-item"><b>{aiShare.toFixed(0)}%</b><span>Of value creation from AI</span></div>
        </div>
      </div>
      <div className="os-wf" role="img"
           aria-label={"Value bridge from $" + entry.toFixed(0) + "M entry to $" + exit.toFixed(0) + "M exit enterprise value"}>
        <div className="os-wf-grid" aria-hidden="true" />
        {steps.map((s, i) => {
          const b = (s.from / max) * 100;
          const top = (s.to / max) * 100;
          return (
            <div className="os-wf-col" key={s.label}>
              <span className={"os-wf-bar " + s.cls}
                    style={{ bottom: b + "%", height: (on ? top - b : 0) + "%", transitionDelay: (i * 70) + "ms" }} />
              <span className="os-wf-val" style={{ bottom: "calc(" + (on ? top : b) + "% + 8px)" }}>{s.txt}</span>
              {i < steps.length - 1 && <span className="os-wf-link" style={{ bottom: (on ? top : b) + "%" }} aria-hidden="true" />}
              <span className="os-wf-label kicker">{s.label}</span>
            </div>
          );
        })}
      </div>
      <p className="os-illustrative kicker">
        Illustrative: {MULT}x entry and exit multiple, {(ORGANIC * 100).toFixed(0)}% annual organic growth,
        {" "}{HOLD}-year hold, uplift applied to EBITDA. Not investment advice.
      </p>
    </div>
  );
}

const CC_OS_GANTT = [
  { seq: "01", name: "Unify data warehouse", lever: "Foundation", start: 2, len: 26 },
  { seq: "02", name: "AR / AP automation", lever: "+180 bps margin", start: 14, len: 26 },
  { seq: "03", name: "Demand forecasting", lever: "Working capital", start: 26, len: 30 },
  { seq: "04", name: "Support copilot", lever: "Cost avoidance", start: 38, len: 34 },
];

function OsPlanModule() {
  const ref = useRefC(null);
  const seen = useInView(ref, { threshold: 0.3 });
  return (
    <div className="os-module os-gantt" ref={ref}>
      <div className="os-gantt-head kicker">
        <span />
        <span>Initiative</span>
        <span>Schedule — the marker is today, day 46</span>
        <span className="os-gantt-head-r">Value lever</span>
      </div>
      {CC_OS_GANTT.map((it, i) => (
        <div className="os-gantt-row" key={it.seq}>
          <span className="os-gantt-seq kicker">{it.seq}</span>
          <span className="os-gantt-name">{it.name}</span>
          <div className="os-gantt-track">
            <div className="os-gantt-bar"
                 style={{ left: it.start + "%", width: (seen ? it.len : 0) + "%", transitionDelay: (i * 90) + "ms" }} />
          </div>
          <span className="os-gantt-lever">{it.lever}</span>
        </div>
      ))}
      <div className="os-gantt-axis kicker">
        <div><span>Day 0</span><span>Day 50</span><span>Day 100</span></div>
      </div>
    </div>
  );
}

const CC_OS_SYSTEMS = [
  { name: "Unified data warehouse", status: "Live", cls: "live", note: "Owned by the internal data team" },
  { name: "AR / AP matching agent", status: "Live", cls: "live", note: "100% of eligible invoices" },
  { name: "Demand forecasting agent", status: "In build", cls: "building", note: "Ops pilot, week 3 of 4" },
  { name: "Support copilot", status: "Queued", cls: "queued", note: "Scoped, starts next sprint" },
];

const CC_OS_ARCH = ["Sources", "Warehouse", "Models", "Workflows", "Operators"];

const CC_OS_LOG = [
  "wk 14 · warehouse — 1.24M rows reconciled, 0 critical issues",
  "wk 14 · ar/ap agent — 4,318 invoices matched, 100% of volume",
  "wk 13 · forecasting — eval pass 3 of 4, MAPE 6.1%",
  "wk 13 · copilot — retrieval corpus scoped, 812 documents",
  "wk 12 · orchestration — nightly run green, 42 min",
  "wk 12 · handoff — warehouse runbook owned by client team",
];

function OsLog() {
  const [lines, setLines] = useStateC(CC_RM ? CC_OS_LOG.slice(0, 6) : []);
  useEffectC(() => {
    if (CC_RM) return;
    let i = 0;
    const id = setInterval(() => {
      setLines((prev) => [...prev, CC_OS_LOG[i % CC_OS_LOG.length]].slice(-6));
      i++;
    }, 1900);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="os-log">
      <div className="os-log-head kicker">Delivery ledger <span className="os-log-live">● updated weekly</span></div>
      <div className="os-log-body">
        {lines.map((l, i) => <div className="os-log-line" key={i + l}><span>›</span> {l}</div>)}
        <div className="os-log-line os-log-cursor"><span>›</span> <span className="os-log-caret" /></div>
      </div>
    </div>
  );
}

function OsBuildModule() {
  return (
    <div className="os-module os-build">
      <div className="os-build-cols">
        <div className="os-build-list">
          {CC_OS_SYSTEMS.map((s) => (
            <div className="os-build-row" key={s.name}>
              <span className={"os-status-dot " + s.cls} />
              <span className="os-build-name">{s.name}<em>{s.note}</em></span>
              <span className="os-build-status">{s.status}</span>
            </div>
          ))}
        </div>
        <OsLog />
      </div>
      <span className="kicker os-arch-label">Installed architecture — owned by the company at handoff</span>
      <div className="os-arch">
        {CC_OS_ARCH.map((n, i) => (
          <React.Fragment key={n}>
            <span className="os-arch-node">{n}</span>
            {i < CC_OS_ARCH.length - 1 && <span className="os-arch-line" />}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

const CC_OS_STAGES = [
  { id: "underwrite", n: "01", label: "Underwrite", sub: "Size the value at stake", Comp: OsUnderwriteModule },
  { id: "sequence", n: "02", label: "Sequence", sub: "Order the operating plan", Comp: OsPlanModule },
  { id: "ship", n: "03", label: "Ship", sub: "Track what goes live", Comp: OsBuildModule },
];

function OSConcept() {
  const CW = window.CW;
  const [stage, setStage] = useStateC("underwrite");
  const Module = (CC_OS_STAGES.find((s) => s.id === stage) || CC_OS_STAGES[0]).Comp;
  return (
    <div className="os" data-screen-label="Concept — Operating System">
      <ConceptTopbar current="concept-os" />

      <section className="os-hero">
        <div className="wrap-wide">
          <span className="eyebrow">Common Works — Concept 03</span>
          <KineticHeading text="Run the engagement. Not a pitch." className="os-hero-h display" />
          <p className="os-hero-sub lead">{CW.hero.sub}</p>
        </div>
      </section>

      <section className="os-console">
        <div className="wrap-wide">
          <div className="os-console-head">
            <div className="os-engagement">
              <span className="kicker">Active engagement — illustrative</span>
              <span className="os-engagement-name">Project Meridian</span>
              <div className="os-facts">
                {CC_OS_FACTS.map((f) => (
                  <div className="os-fact" key={f.k}>
                    <span className="os-fact-k">{f.k}</span>
                    <span className="os-fact-v">{f.v}</span>
                  </div>
                ))}
              </div>
              <div className="os-phases">
                {CC_OS_PHASES.map((p, i) => (
                  <React.Fragment key={p.label}>
                    {i > 0 && <span className="os-phase-link" aria-hidden="true" />}
                    <div className={"os-phase" + (p.current ? " current" : "") + (p.done ? " done" : "")}>
                      <span className="os-phase-dot" aria-hidden="true" />
                      <span className="os-phase-label">{p.label}</span>
                      <span className="os-phase-status kicker">{p.status}</span>
                    </div>
                  </React.Fragment>
                ))}
              </div>
            </div>
            <div className="os-engagement-score">
              <span className="kicker">AI readiness</span>
              <OsGauge />
              <span className="os-gauge-note">Scored at diligence, re-scored quarterly against the plan</span>
            </div>
          </div>

          <div className="os-stage-tabs" role="tablist">
            {CC_OS_STAGES.map((s) => (
              <button key={s.id} role="tab" aria-selected={stage === s.id}
                      className={"os-stage-tab" + (stage === s.id ? " on" : "")} onClick={() => setStage(s.id)}>
                <span className="os-stage-n">{s.n}</span>
                <span className="os-stage-lab">{s.label}<em>{s.sub}</em></span>
              </button>
            ))}
          </div>

          <div className="os-panel" key={stage}><Module /></div>
        </div>
      </section>

      <section className="os-note band-cream2">
        <div className="wrap-wide">
          <p className="lead">This is how an engagement actually runs: diligence becomes the plan, the plan becomes what ships.</p>
        </div>
      </section>

      <CTABand />
    </div>
  );
}

Object.assign(window, { ManifestoConcept, SystemsConcept, OSConcept, ConceptTopbar });
