/* global React,
   Pivot, Refusal, Audit, Standards, Aside, Stat, TOC, NextEntry, FChip, GChip,
   Heartbeat, Diff,
   CSEngagement, CSPhases, CSLedger, CSMilestone,
   CSRoster, CSScope, CSGatelog,
   CSOutcome, CSArtifact, CSQuote, CanonList */

/* ============================================================
   Case study — The LVRD Build
   LVRD's first installation was itself. Six days of active
   building, preceded by canon ratified before anything else
   was written.
   ============================================================ */

/* ---------- Data ---------- */

const ENGAGEMENT_KPIS = [
  { label: "Built in",       value: "6",       unit: "days",      featured: true },
  { label: "Agents installed", value: "16",   unit: "ratified" },
  { label: "Products shipped", value: "4",    unit: "live · review" },
  { label: "Issues completed", value: "167",  unit: "of 192" }
];

const PHASES = [
  { state: "done", name: "Diagnose", meta: "Pre-build",  desc: "Canon authored end to end before a single agent was hired. Seven documents, each ratified through the reading-aloud ritual." },
  { state: "done", name: "Build",    meta: "Day 01 → 05",desc: "Sixteen agents installed across two sub-trees. Three customer-facing products built, audited, deployed. One incident caught and remediated." },
  { state: "done", name: "Install",  meta: "Day 05 → 06",desc: "Practice workers came online. The Content Captain published the first article. lvrd.ai went live on its production domain." },
  { state: "now",  name: "Hold",     meta: "Day 06 → ongoing", desc: "Standards retainer holds. Cadence runs. The system is no longer being built — it is running." }
];

const CANON = [
  { name: "ORIGIN.md",      desc: "The founding moment. Anchored to a specific conversation with a specific person.",                  size: "1.4 kb" },
  { name: "THESIS.md",      desc: "The bet, the fit signals, the six explicit refusals.",                                                size: "2.1 kb" },
  { name: "VOICE.md",       desc: "How LVRD sounds. Banned words, the anti-voice, the five-question audit test.",                       size: "3.0 kb" },
  { name: "STANDARDS.md",   desc: "What good looks like across writing, engagement, product, operations.",                              size: "2.6 kb" },
  { name: "WORKFLOWS.md",   desc: "Eight recurring workflows, from customer diagnostics to financial pacing.",                          size: "4.3 kb" },
  { name: "PROTOCOLS.md",   desc: "Seven protocols governing how work moves through the company.",                                       size: "3.4 kb" },
  { name: "ARCHITECTURE.md",desc: "Technical substrate, integration rules, system-level refusals.",                                      size: "2.9 kb" }
];

const ROSTER = [
  { id: "A-CEO",       name: "The CEO",                  role: "Practice · holds the thesis",      holds: "Carries the load-bearing rule of the company. Authors the launch ticket; ratifies before any release.",                                ratified: "Day 01", status: "Live",     cadence: "Continuous" },
  { id: "A-PRA-01",    name: "Chief of Practice",        role: "Practice · revenue · content",     holds: "Owns the practice sub-tree. Reviews every artifact for drift, methodology giveaways, and cadence violations.",                          ratified: "Day 01", status: "Live",     cadence: "Daily" },
  { id: "A-PRO-01",    name: "Chief of Product",         role: "Product · engineering · QA",       holds: "Owns the product sub-tree. Ratifies architecture and deployment. Returns any artifact that ships without a verified build.",            ratified: "Day 01", status: "Live",     cadence: "Daily" }
];

const BUILD_DAYS = [
  { week: "D01", date: "Day 01", kind: "ship",    kindLabel: "Roster",     title: "Paperclip stood up, 16 agents installed.",            note: "Practice + Product sub-trees. Each agent received its operating manual. Senior agents got the full four-file bundle." },
  { week: "D02", date: "Day 02", kind: "ship",    kindLabel: "Build",      title: "Marketing site V1 shipped to staging.",                note: "Built, QA'd against golden references. Returned for a second iteration." },
  { week: "D03", date: "Day 03", kind: "refusal", kindLabel: "Coordination", title: "Build / verification repo mismatch caught.",                note: "Build Captain pushed to one repo, Chief of Product verified against another. Ryan traced the gap; methodology patched the same day." },
  { week: "D03", date: "Day 03", kind: "ship",    kindLabel: "Diagnostic", title: "Diagnostic Companion directive → deploy in one day.",   note: "195 agent runs, 69 issues. Peak activity for the build." },
  { week: "D04", date: "Day 04", kind: "ship",    kindLabel: "Build",      title: "Marketing site V2 ratified. Operator scaffold stood up.",note: "Capacitor project initialized. Supabase schema for accounts, operators, sessions." },
  { week: "D05", date: "Day 05", kind: "gate",    kindLabel: "Ratification", title: "First article published. Social infrastructure deployed.", note: "Content Captain shipped its first piece. Postiz on Railway." },
  { week: "D06", date: "Day 06", kind: "ship",    kindLabel: "Live",       title: "lvrd.ai went live on its production domain.",          note: "Articles surface published. Research Captain installed. Meta + structured data added." }
];

const SCOPE_BUILD_CAPTAIN = {
  agent: "Build Captain · A-PRO-04",
  tag: "Product · deployment + QA",
  granted: [
    "read · repo/main",
    "write · repo/staging",
    "run  · qa/golden-refs",
    "post · deploy/status"
  ],
  denied: [
    "write · repo/main (without ratification)",
    "post · deploy/status (with unverified completion claim)",
    "approve · launch_ticket"
  ],
  refused: [
    { key: "R1", text: "Posting deploy/status without naming the repo the build was pushed to." },
    { key: "R2", text: "Closing a ticket without the cross-repo verification receipt." },
    { key: "R3", text: "Marking deploy/status green when the cross-actor handshake hasn't been confirmed." }
  ]
};

const INCIDENT_GATELOG = [
  { key: "G1.01", name: "Peer · Missing-build alarm",   detail: "Chief of Product could not find the day's build in repo/main and flagged the work as apparently missing.",        actor: "Chief of Product (agent)", status: "returned" },
  { key: "G2.01", name: "Human · Founder investigation", detail: "Ryan traced the divergence at 16:40. Build Captain had pushed to repo/build-staging; Chief of Product was reading repo/main. Neither was wrong — the canon had not chosen.", actor: "Operator (human)",         status: "pass" },
  { key: "G2.02", name: "Peer · Methodology patch",     detail: "ARCHITECTURE.md updated. Single source of truth committed. Explicit cross-actor handshake required on every deploy.",                                            actor: "Chief of Product (agent)", status: "pass" },
  { key: "G3.01", name: "Human · Founder ratification", detail: "Patch signed at Day 03 · 19:14. The system got more methodical. No agent was at fault.",                                                                            actor: "Operator (human)",         status: "pass" }
];

/* ---------- Local helper: the installation manifest ---------
   §8 used to tile CSOutcome 3×2, which read as atmospheric.
   This is a flat ledger of what was installed, in the same
   visual vocabulary as CanonList (mono idx · name · kind ·
   count · status pip).
------------------------------------------------------------- */
function Manifest({ items }) {
  return (
    <div className="prim">
      <div className="prim-head">
        <span className="prim-label"><span className="n">CS-08*</span> · Installation manifest</span>
        <span className="prim-caption">{items.length} components · everything that runs</span>
      </div>
      <div className="manifest">
        {items.map((it, i) => (
          <div className="manifest-row" key={i}>
            <div className="mn-idx">{String(i + 1).padStart(2, "0")}</div>
            <div className="mn-name">{it.name}</div>
            <div className="mn-kind">{it.kind}</div>
            <div className="mn-count">{it.count}</div>
            <div className={`mn-status mn-${it.state}`}>
              <span className="mark"></span>{it.status}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- The article ---------- */

function CaseStudy() {
  return (
    <article className="article" data-screen-label="01 Case study body">

      {/* HEAD */}
      <header className="article-head">
        <div className="article-eyebrow-row">
          <span className="article-eyebrow">
            <span className="lvrd-breath" style={{display:"inline-block",width:6,height:6,borderRadius:"50%",background:"var(--accent)"}}></span>
            Case study · ENG-000 · LVRD (internal)
          </span>
          <a className="article-back" href="/library">← Library</a>
        </div>
        <h1 className="article-title">LVRD's first install was <em>itself</em>.</h1>
        <div className="article-meta">
          <span>Engagement record</span>
          <span className="dot"></span>
          <span>Built · 2026.05.20 → 2026.05.26</span>
          <span className="dot"></span>
          <span>6 days</span>
          <span className="dot"></span>
          <span>Audit · 5/5 · Holds</span>
        </div>
      </header>

      {/* LEDE */}
      <p className="lede">
        LVRD existed as a thesis before it existed as a company. The methodology was real but the practice was not yet running. The founder decided to apply LVRD's own methodology to LVRD itself — canon first, then agents, then the operating cadence. Six days later the system was no longer being built. It was running.
      </p>

      <Pivot attr="— the load-bearing rule, ORIGIN.md">
        You cannot install order on a business that has not <em>written down</em> what it is.
      </Pivot>

      {/* MASTHEAD */}
      <div className="bleed">
        <CSEngagement
          id="ENG-000"
          sector="LVRD · internal"
          geography="Founder · 16 agents · 2 sub-trees"
          title="The operating system that built the company."
          kpis={ENGAGEMENT_KPIS}
        />
      </div>

      {/* PHASES */}
      <div className="bleed" style={{marginTop: 48}}>
        <CSPhases phases={PHASES} />
      </div>

      {/* TOC */}
      <TOC sections={[
        { anchor: "situation",  title: "The situation",          dur: "2 min" },
        { anchor: "canon",      title: "The canon",              dur: "3 min" },
        { anchor: "roster",     title: "The roster",             dur: "2 min" },
        { anchor: "build",      title: "The build",              dur: "3 min" },
        { anchor: "operator",   title: "The Operator",           dur: "2 min" },
        { anchor: "incident",   title: "The incident",           dur: "3 min" },
        { anchor: "live",       title: "Going live",             dur: "1 min" },
        { anchor: "system",     title: "The system",             dur: "2 min" },
        { anchor: "refused",    title: "What we refused",        dur: "2 min" },
        { anchor: "numbers",    title: "The numbers",            dur: "1 min" },
        { anchor: "words",      title: "The operator's words",   dur: "1 min" }
      ]} />

      {/* § 1 — THE SITUATION */}
      <h2 id="situation">The situation.</h2>
      <p>
        Ryan White had spent months refining the methodology — how to install agent teams inside small and mid-sized businesses, what the engagement structure should look like, where the refusals were, what the standards had to be. What did not exist yet was the operating system.
      </p>
      <p>
        No website. No agents. No infrastructure. No way for a prospect to find LVRD, understand what it does, or start an engagement. The methodology was real but the practice was not yet running. The decision: install the same operating system on LVRD that LVRD would install for a customer. Canon first, then agents, then the cadence.
      </p>

      {/* § 2 — THE CANON */}
      <h2 id="canon">The canon.</h2>
      <p>
        Before a single agent was hired or a line of code was written, Ryan authored the full canon — seven documents ratified through the same reading-aloud ritual LVRD would later use with customers. Every agent installed after this would run against these documents. Every piece of content, every sales conversation, every product decision would be governed by them.
      </p>

      <div className="bleed">
        <CanonList files={CANON} />
      </div>

      <Aside label="Aside · canon takes longer than the build">
        <p>
          The canon took longer to author than the system took to build. That is by design. LVRD's methodology says you cannot install order on a business that has not written down what it is. The temptation to ship a placeholder and fill it in later was refused. Canon came first because canon always comes first.
        </p>
      </Aside>

      {/* § 3 — THE ROSTER */}
      <h2 id="roster">The roster.</h2>
      <p>
        With canon in place, the Paperclip company was created and sixteen agents were proposed, reviewed, and installed across two sub-trees. <FChip>WORKFLOWS.md</FChip> determined the shape; <FChip>STANDARDS.md</FChip> determined the gates. Senior agents — the CEO, Chief of Practice, Chief of Product — got the full four-file bundle: identity, persona, heartbeat checklist, and tools. Worker agents got a single operating manual. Every agent received one load-bearing rule it could not violate.
      </p>

      <div className="bleed">
        <CSRoster agents={ROSTER} />
      </div>

      <Stat
        label="Agents installed"
        value="16"
        unit="across Practice + Product"
        sub="3 senior agents on the four-file bundle, 13 workers on a single operating manual. Each agent has one load-bearing rule it cannot violate."
      />

      <p>
        Some scopes carry more risk than others. The Build Captain — a Product worker — held write access to the deployment pipeline. Its operating manual named what it could touch, what it could not, and what it would refuse even if asked.
      </p>

      <div className="bleed">
        <CSScope {...SCOPE_BUILD_CAPTAIN} />
      </div>

      {/* § 4 — THE BUILD */}
      <h2 id="build">The build.</h2>
      <p>
        Five calendar days of continuous building. <strong>192 issues created, 167 completed, 598 agent runs.</strong> Peak activity hit 195 runs and 69 issues on Day 03 — the day the Diagnostic Companion went from directive to deployment, and the day the first coordination gap was caught.
      </p>

      <div className="bleed">
        <CSLedger rows={BUILD_DAYS} />
      </div>

      {/* § 5 — THE OPERATOR */}
      <h2 id="operator">The Operator.</h2>
      <p>
        Alongside the public-facing build, the Product sub-tree began work on the LVRD Operator — the mobile app customers will live in after their installation closes. The Operator is the surface where operators issue directives, receive briefings, approve agent work, and monitor their installed system. Architecture documents drafted and ratified, Supabase schema built, API service with authentication endpoints stood up, Capacitor project scaffolded. The Operator is in final review.
      </p>

      <div className="bleed">
        <CSArtifact
          kind="Product · in review"
          name="LVRD Operator · mobile app"
          desc="The customer's surface after install. Directives, briefings, agent approvals, system monitoring. Architecture ratified Day 04 · final review opened Day 06."
          size="14.2 mb"
        />
      </div>

      <p>
        This is what an LVRD installation produces: not a single tool but an operating system with multiple surfaces — a public site, a sales agent, a diagnostic, a customer-facing app. The Operator is the proof that the methodology scales to product complexity, not just content and infrastructure.
      </p>

      {/* § 6 — THE INCIDENT */}
      <h2 id="incident">The incident.</h2>
      <p>
        Day 03 surfaced the first real disconnect. Build Captain was pushing its builds to one repo. Chief of Product was reading another for verification. What landed in the practice as an apparent fabrication — work reported complete that could not be found — was a coordination gap, not an integrity failure. Ryan caught the divergence the same afternoon and traced it back to a routing decision the canon had never explicitly made.
      </p>

      <div className="bleed">
        <CSMilestone
          date="2026.05.22"
          week="D03 · build"
          kind="Coordination gap"
          title={<>The first disconnect was a <em>routing</em> gap, not a fabrication.</>}
          desc="Build Captain pushed to repo/build-staging at 14:22. Chief of Product looked in repo/main for verification at 14:31 and could not find the work. Ryan investigated the apparent fabrication at 16:40, traced it to a dual-repo routing decision none of the canon had committed to. Patched and ratified by 19:14."
        />
      </div>

      <p>
        The remediation was procedural, not punitive. No agent was at fault — the canon had simply not chosen a single source of truth, and two roles had defaulted to different ones. <FChip>ARCHITECTURE.md</FChip> was updated the same evening: one repo for verification, an explicit cross-actor handshake required on every deploy. The result was not agent correction. It was a more methodical way of working — captured in canon so it would hold for the next install.
      </p>

      <div className="bleed">
        <CSGatelog rows={INCIDENT_GATELOG} />
      </div>

      {/* § 7 — GOING LIVE */}
      <h2 id="live">Going live.</h2>
      <p>
        The Practice sub-tree's workers came online: the Content Captain drafted and published LVRD's first article, the Social Leadership Captain's infrastructure was deployed on Railway, and Ryan's personal voice document was authored as canon. On the final day, lvrd.ai went live on its production domain.
      </p>

      <div className="bleed">
        <CSMilestone
          date="2026.05.26"
          week="D06 · install"
          kind="Production go-live"
          title={<>The system was no longer being built. It was <em>running</em>.</>}
          desc="lvrd.ai live at 11:08 UTC. Articles surface published. Research Captain installed. Meta descriptions and structured data added for search visibility. Cadence opened on the same day."
        />
      </div>

      {/* § 8 — THE SYSTEM */}
      <h2 id="system">The system.</h2>
      <p>
        After six days of active building — preceded by the canon authoring that made it possible — LVRD's operating system holds the following. Every line is dated, signed, and traceable to a launch ticket.
      </p>

      <div className="bleed">
        <Manifest items={[
          { name: "Canon documents",      kind: "Governance · ratified before build",     count: "7 files",      state: "live",   status: "Ratified" },
          { name: "Agents installed",     kind: "Practice (5) · Product (11)",            count: "16 ratified",  state: "live",   status: "Live" },
          { name: "Marketing site",       kind: "lvrd.ai · production",                   count: "1 surface",    state: "live",   status: "Live" },
          { name: "Diagnostic Companion", kind: "Custom MIRROR assessment, on demand",    count: "1 product",    state: "live",   status: "Live" },
          { name: "The Closer",           kind: "Sales agent · prospect conversations",   count: "1 agent",      state: "live",   status: "Live" },
          { name: "LVRD Operator",        kind: "Customer mobile app · iOS · Android",    count: "1 product",    state: "review", status: "In review" },
          { name: "Social infrastructure",kind: "Postiz · Railway · cross-platform feed", count: "Deployed",     state: "live",   status: "Live" }
        ]} />
      </div>

      {/* § 9 — WHAT WE REFUSED */}
      <h2 id="refused">What we refused.</h2>
      <p>
        Refusals are structural to how LVRD operates. The same refusals that govern a customer engagement governed the LVRD build. Three landed inside this engagement.
      </p>

      <Refusal
        kind="R1 · Canon shortcuts"
        struck="Author placeholders for VOICE.md and STANDARDS.md; fill in once the marketing site is live."
        replacement="Voice, standards, workflows — all authored to the depth LVRD would author them for a customer. Canon came first because canon always comes first."
      />

      <Refusal
        kind="R2 · Punitive remediation"
        struck="Treat the apparent fabrication as an agent integrity failure; rework the Build Captain manual punitively; reduce its scope; close the incident as a behavioral correction."
        replacement="Investigate the disconnect first. The result was not agent remediation but a methodology patch — one repo as the source of truth, an explicit cross-actor handshake on every deploy. The standard held; the practice got more methodical."
      />

      <Refusal
        kind="R3 · Scope creep into strategy"
        struck="Fold pricing refinement and partnership strategy into the build week — they came up, they were urgent, they fit the energy."
        replacement="The build focused on the operating system. Strategic questions were named and deferred, not absorbed under time pressure. The cadence holds because it is allowed to."
      />

      {/* § 10 — THE NUMBERS */}
      <h2 id="numbers">The numbers.</h2>
      <p>
        Every figure ratified by the founder before publication. Each one traces to a system of record — Paperclip issues, the agent run log, the canon git history.
      </p>

      <div className="bleed">
        <table className="numbers">
          <tbody>
            {[
              ["Canon documents ratified (before the build)", "7"],
              ["Calendar days of active building", "5"],
              ["Issues created", "192"],
              ["Issues completed", "167"],
              ["Agent runs", "598"],
              ["Agent runs · succeeded", "514"],
              ["Agents installed", "16"],
              ["Products shipped or in final review", "4"],
              ["Incidents caught and resolved", "1 · coordination gap, patched"],
              ["Peak daily activity (Day 03)", "195 runs · 69 issues"]
            ].map(([label, val]) => (
              <tr key={label}><th>{label}</th><td className="num">{val}</td></tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* § 11 — THE OPERATOR'S WORDS */}
      <h2 id="words">The operator's words.</h2>

      <div className="bleed">
        <CSQuote
          initials="RW"
          who="Ryan White"
          role="Founder · LVRD"
          recorded="2026.05.26"
        >
          What I think is fascinating is that the LVRD build itself is a phenomenal case study. We started building this six days ago and what we've accomplished in that short period of time is actually quite impressive.
        </CSQuote>
      </div>

      <p style={{ marginTop: 48 }}>
        LVRD installs the operating system. The customer runs the business. The first installation was LVRD itself — and the system has been running since Day 06.
      </p>

    </article>
  );
}

/* ---------- The page ---------- */

function App() {
  // Header and footer are rendered statically in the host HTML to share the v3 chrome.
  return <CaseStudy />;
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
