/* OpenSyn homepage — content sections (light panels + dark CRT supports) */
const { Panel: OSPanel, Badge: OSBadge2, Symbol: OSSym2 } = window.OpenSynDesignSystem_a3458e;
const OSGlyph = window.OSGlyph;

const WRAP = { maxWidth: "var(--container-max)", margin: "0 auto", padding: "0 clamp(20px, 5vw, 56px)" };

/* CrtFrame — a navy CRT screen seated in a rounded white fibreglass
   housing, the way the Opsroom data screens are bezelled. */
function CrtFrame({ children, style = {} }) {
  return (
    <div style={{
      background: "linear-gradient(180deg, #FCFBF8 0%, #EEEBE3 100%)",
      borderRadius: "28px", padding: "13px",
      boxShadow: "var(--shadow-raised)",
      border: "1px solid rgba(35,35,35,0.12)", ...style,
    }}>
      <div style={{
        position: "relative", background: "var(--surface-screen)",
        borderRadius: "17px", overflow: "hidden",
        color: "var(--c-cyber-white)", boxShadow: "var(--shadow-screen)",
      }}>
        {children}
      </div>
    </div>
  );
}

function SectionLabel({ children, code, dark = false }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: "12px", marginBottom: "18px" }}>
      <span style={{ width: "26px", height: "2px", background: "var(--c-signal-orange)" }} />
      <span style={{
        fontFamily: "var(--font-mono)", fontSize: "12px", fontWeight: 600,
        letterSpacing: "0.16em", textTransform: "uppercase",
        color: dark ? "var(--os-dim2)" : "var(--text-muted)",
      }}>{children}</span>
      {code && <span style={{ fontFamily: "var(--font-mono)", fontSize: "11px", letterSpacing: "0.1em", color: dark ? "var(--os-dim)" : "var(--text-faint)", marginLeft: "auto" }}>{code}</span>}
    </div>
  );
}

/* ============================================================
   1 · THE CYBERSYN CONNECTION  (light)
   ============================================================ */
function ConnectionSection() {
  return (
    <section id="connection" style={{ background: "var(--surface-page)", padding: "clamp(72px, 10vw, 128px) 0", borderBottom: "1px solid var(--border-soft)" }}>
      <div style={{ ...WRAP, display: "grid", gridTemplateColumns: "minmax(0, 1.05fr) minmax(0, 0.95fr)", gap: "clamp(32px, 5vw, 72px)", alignItems: "center" }} className="os-2col">
        <div>
          <SectionLabel code="SYNCO · 1971–73">The Cybersyn connection</SectionLabel>
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(30px, 4.2vw, 50px)", lineHeight: 1.04, letterSpacing: "-0.02em", color: "var(--text-body)", margin: "0 0 24px", textWrap: "balance" }}>
            Governance logic, not the technology.
          </h2>
          <div style={{ display: "flex", flexDirection: "column", gap: "18px", fontFamily: "var(--font-sans)", fontSize: "var(--fs-body)", lineHeight: 1.62, color: "var(--text-muted)", maxWidth: "56ch" }}>
            <p style={{ margin: 0 }}>
              Chile's Allende government built <strong style={{ color: "var(--text-body)" }}>Project Cybersyn</strong> to
              monitor industrial production over a telex network — a handful of standardized
              indicators and statistical filtering to flag deviations. The interesting part was
              never the hardware. It was the organizational design behind it.
            </p>
            <p style={{ margin: 0 }}>
              Working from Stafford Beer's <strong style={{ color: "var(--text-body)" }}>Viable System Model</strong>,
              its designers organized the economy into recursive layers: units that handled their own
              problems first, a layer that kept them from interfering, an operations layer tracking the
              present, an intelligence layer scanning for risk, and a policy layer — ultimately human —
              that set goals and resolved what the others couldn't.
            </p>
            <p style={{ margin: 0 }}>
              Information moved upward only when a layer couldn't resolve a deviation itself. That
              principle — <strong style={{ color: "var(--text-body)" }}>management by exception</strong> —
              maps unusually well onto the problems multi-agent LLM systems run into today: context
              overload, role collapse, unbounded escalation.
            </p>
          </div>
        </div>
        <EscalationScreen />
      </div>
    </section>
  );
}

/* navy CRT illustration: the management-by-exception loop */
function EscalationScreen() {
  const rows = [
    ["L5", "Governance", "pentagon", "#E95C2B"],
    ["L4", "Intelligence", "square", "#F0C83D"],
    ["L3", "Operations", "triangle", "#4C9B63"],
    ["L2", "Coordination", "circle", "#4f6be0"],
    ["L1", "Task units", "plus", "#4f6be0"],
  ];
  return (
    <CrtFrame>
      <div aria-hidden="true" style={{ position: "absolute", inset: 0, background: "var(--scanlines)", pointerEvents: "none", zIndex: 3 }} />
      <header style={{ display: "flex", alignItems: "baseline", gap: "10px", padding: "12px 16px", borderBottom: "1px solid var(--c-line-dark)", position: "relative", zIndex: 2 }}>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: "12px", fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase" }}>Management by exception</span>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: "10px", letterSpacing: "0.1em", color: "#8b93bd", marginLeft: "auto" }}>VSM · S1–S5</span>
      </header>
      <div style={{ position: "relative", zIndex: 2, padding: "20px 18px", display: "flex", flexDirection: "column", gap: "8px" }}>
        {rows.map(([l, name, sym, col], i) => (
          <div key={l} style={{ display: "flex", alignItems: "center", gap: "12px" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: "9px", width: "150px", flex: "none" }}>
              <OSGlyph name={sym} size={18} color={col} filled={i === 0} />
              <span style={{ fontFamily: "var(--font-mono)", fontSize: "11px", fontWeight: 700, letterSpacing: "0.06em" }}>{l}</span>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: "11px", letterSpacing: "0.05em", color: "#aeb6e0" }}>{name}</span>
            </span>
            <span style={{ flex: 1, height: "2px", background: "rgba(255,255,255,0.12)", position: "relative" }}>
              <span style={{ position: "absolute", inset: 0, width: i === 0 ? "100%" : `${60 - i * 8}%`, background: col, opacity: 0.5 }} />
            </span>
          </div>
        ))}
        <div style={{ display: "flex", alignItems: "center", gap: "10px", marginTop: "12px", paddingTop: "14px", borderTop: "1px dashed rgba(255,255,255,0.14)" }}>
          <svg width="20" height="40" viewBox="0 0 20 40" aria-hidden="true">
            <path d="M10 38 L10 6 M4 12 L10 4 L16 12" stroke="#E95C2B" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"></path>
          </svg>
          <span style={{ fontFamily: "var(--font-sans)", fontSize: "12.5px", lineHeight: 1.5, color: "rgba(246,244,239,0.82)" }}>
            A deviation escalates <strong style={{ color: "#fff" }}>only</strong> when the layer below
            it can't resolve it. Autonomy stays local; attention rises by exception.
          </span>
        </div>
      </div>
    </CrtFrame>
  );
}

/* ============================================================
   2 · FIVE PRINCIPLES  (light)
   ============================================================ */
const PRINCIPLES = [
  { n: "01", sym: "plus", col: "var(--c-signal-blue)", title: "Hybrid control plane", body: "Agents propose plans, summaries, and tool calls — but deterministic workflow objects, not model judgment, control dependency order, state, retries, and approval gates." },
  { n: "02", sym: "circle", col: "var(--c-signal-blue)", title: "Functional role separation", body: "Planning, execution, verification, memory, and policy are distinct functions held by distinct agents. None collapse into a single do-everything prompt." },
  { n: "03", sym: "triangle", col: "var(--c-signal-yellow)", title: "Management by exception", body: "Local agents attempt recovery first. Escalation happens only after a defined threshold: repeated verifier failure, contradiction, budget breach, or a policy-blocked action." },
  { n: "04", sym: "square", col: "var(--c-signal-green)", title: "Persistent observability", body: "A replayable event log, versioned artifacts, and explicit failure signals — instead of relying on ephemeral chat history as the only record of what happened." },
  { n: "05", sym: "pentagon", col: "var(--c-signal-orange)", title: "Human policy closure", body: "Humans set goals, define risk boundaries, and hold final authority over irreversible or high-stakes actions — no matter how autonomous the agents below them are." },
];

function PrincipleCard({ p }) {
  return (
    <article style={{
      position: "relative", background: "var(--surface-panel)",
      border: "2px solid var(--border-strong)", borderTop: `4px solid ${p.col}`,
      borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-panel)",
      padding: "22px 22px 24px", display: "flex", flexDirection: "column", gap: "14px",
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <OSGlyph name={p.sym} size={30} color={p.col} />
        <span style={{ fontFamily: "var(--font-mono)", fontSize: "12px", fontWeight: 600, letterSpacing: "0.14em", color: "var(--text-faint)" }}>P-{p.n}</span>
      </div>
      <h3 style={{ fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: "var(--fs-h3)", lineHeight: 1.2, color: "var(--text-body)", margin: 0 }}>{p.title}</h3>
      <p style={{ fontFamily: "var(--font-sans)", fontSize: "14px", lineHeight: 1.55, color: "var(--text-muted)", margin: 0 }}>{p.body}</p>
    </article>
  );
}

function PrinciplesSection() {
  return (
    <section id="principles" style={{ background: "var(--surface-sunken)", padding: "clamp(72px, 10vw, 128px) 0", borderBottom: "1px solid var(--border-soft)" }}>
      <div style={WRAP}>
        <div style={{ maxWidth: "640px", marginBottom: "44px" }}>
          <SectionLabel code="05 INVARIANTS">Core design principles</SectionLabel>
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(30px, 4.2vw, 50px)", lineHeight: 1.04, letterSpacing: "-0.02em", color: "var(--text-body)", margin: 0, textWrap: "balance" }}>
            Five rules the system never breaks.
          </h2>
        </div>
        <div className="os-principles-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: "var(--panel-gap)" }}>
          {PRINCIPLES.map((p) => <PrincipleCard key={p.n} p={p} />)}
          <ClosureNote />
        </div>
      </div>
    </section>
  );
}

function ClosureNote() {
  return (
    <article style={{
      background: "var(--c-graphite)", color: "var(--c-cyber-white)",
      border: "2px solid var(--c-graphite)", borderTop: "4px solid var(--c-signal-orange)",
      borderRadius: "var(--radius-md)", padding: "22px", display: "flex", flexDirection: "column", justifyContent: "center", gap: "12px",
    }}>
      <span style={{ fontFamily: "var(--font-mono)", fontSize: "11px", fontWeight: 600, letterSpacing: "0.14em", textTransform: "uppercase", color: "#aeb6e0" }}>The cybernetic loop</span>
      <p style={{ fontFamily: "var(--font-sans)", fontSize: "15px", lineHeight: 1.5, margin: 0 }}>
        Every panel reads as <strong style={{ color: "#fff" }}>state → diagnosis → recommendation</strong>.
        Numbers are decisions, not decoration.
      </p>
    </article>
  );
}

/* ============================================================
   3 · ARCHITECTURE AT A GLANCE  (dark CRT)
   ============================================================ */
const LAYERS = [
  { l: "L1", sys: "System 1", name: "Task execution", resp: "Bounded work: retrieve, read, code, run, draft, score", sym: "plus", col: "#4f6be0" },
  { l: "L2", sys: "System 2", name: "Coordination", resp: "Route tasks, manage dependencies, reduce chatter between agents", sym: "circle", col: "#4f6be0" },
  { l: "L3", sys: "System 3", name: "Operations control", resp: "Track present state, quality, budgets, retries, artifact integrity", sym: "triangle", col: "#4C9B63" },
  { l: "L4", sys: "System 4", name: "Research intelligence", resp: "Generate hypotheses, scan for new information, model future branches", sym: "square", col: "#F0C83D" },
  { l: "L5", sys: "System 5", name: "Governance", resp: "Set objectives, define risk limits, approve irreversible actions", sym: "pentagon", col: "#E95C2B" },
];
const OBJECTS = [
  { sym: "circle", name: "Task", col: "#4f6be0", body: "A unit of bounded work with inputs, budget, and a verifiable output." },
  { sym: "square", name: "Artifact", col: "#F6F4EF", body: "A versioned product of work — code, document, dataset, score." },
  { sym: "triangle", name: "Event", col: "#F0C83D", body: "An append-only signal on the replayable log: state change, failure, decision." },
];

function ArchitectureSection() {
  return (
    <section id="architecture" style={{ background: "var(--os-arch-bg)", color: "var(--os-ink)", padding: "clamp(72px, 10vw, 128px) 0" }}>
      <div style={WRAP}>
        <div style={{ maxWidth: "680px", marginBottom: "44px" }}>
          <SectionLabel code="L1 → L5" dark>Architecture at a glance</SectionLabel>
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(30px, 4.2vw, 50px)", lineHeight: 1.04, letterSpacing: "-0.02em", color: "var(--os-ink)", margin: "0 0 18px", textWrap: "balance" }}>
            Five layers, adapted from Cybersyn's System 1–5.
          </h2>
          <p style={{ fontFamily: "var(--font-sans)", fontSize: "var(--fs-body)", lineHeight: 1.6, color: "rgba(var(--os-ink-rgb), 0.74)", margin: 0, maxWidth: "60ch" }}>
            The stack is recursive — a subsystem handling literature review or experiment execution can
            contain its own smaller L1–L5 stack.
          </p>
        </div>

        {/* layer screen */}
        <CrtFrame>
          <div aria-hidden="true" style={{ position: "absolute", inset: 0, background: "var(--scanlines)", pointerEvents: "none", zIndex: 3 }} />
          <header style={{ display: "flex", gap: "10px", padding: "12px 18px", borderBottom: "1px solid var(--c-line-dark)", position: "relative", zIndex: 2 }}>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: "11px", fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase", flex: 1 }}>Layer registry · Screen A</span>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: "10px", letterSpacing: "0.1em", color: "#8b93bd" }}>RECURSIVE</span>
          </header>
          <div style={{ position: "relative", zIndex: 2 }}>
            {LAYERS.slice().reverse().map((row, i) => (
              <div key={row.l} className="os-layer-row" style={{
                display: "grid", gridTemplateColumns: "84px 172px 1fr", alignItems: "center", gap: "18px",
                padding: "16px 18px", borderTop: i === 0 ? "none" : "1px solid rgba(255,255,255,0.07)",
                borderLeft: `4px solid ${row.col}`,
              }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: "10px" }}>
                  <OSGlyph name={row.sym} size={22} color={row.col} filled={row.l === "L5"} />
                  <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "22px", color: "#fff" }}>{row.l}</span>
                </span>
                <span style={{ display: "flex", flexDirection: "column", gap: "2px" }}>
                  <span style={{ fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: "15px", color: "#fff" }}>{row.name}</span>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: "10.5px", letterSpacing: "0.1em", textTransform: "uppercase", color: "#8b93bd" }}>{row.sys}</span>
                </span>
                <span style={{ fontFamily: "var(--font-sans)", fontSize: "14px", lineHeight: 1.5, color: "rgba(246,244,239,0.78)" }}>{row.resp}</span>
              </div>
            ))}
          </div>
        </CrtFrame>

        {/* typed objects */}
        <div style={{ marginTop: "56px" }}>
          <SectionLabel code="TYPED" dark>Typed objects, not free-form chat</SectionLabel>
          <div className="os-objects-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: "var(--panel-gap)", marginTop: "6px" }}>
            {OBJECTS.map((o) => (
              <div key={o.name} style={{ background: "var(--os-card-bg)", border: "1px solid var(--os-card-border)", borderRadius: "var(--radius-lg)", padding: "22px" }}>
                <div style={{ display: "flex", alignItems: "center", gap: "12px", marginBottom: "12px" }}>
                  <OSGlyph name={o.sym} size={26} color={o.col === "#F6F4EF" ? "var(--os-ink)" : o.col} />
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: "15px", fontWeight: 700, letterSpacing: "0.04em", color: "var(--os-ink)" }}>{o.name}</span>
                </div>
                <p style={{ fontFamily: "var(--font-sans)", fontSize: "13.5px", lineHeight: 1.55, color: "rgba(var(--os-ink-rgb), 0.72)", margin: 0 }}>{o.body}</p>
              </div>
            ))}
          </div>
        </div>

        {/* also specified strip */}
        <div style={{ marginTop: "40px", display: "flex", flexWrap: "wrap", gap: "10px", alignItems: "center" }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: "11px", fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--os-dim)", marginRight: "4px" }}>Also specified</span>
          {["Workflow graph · typed nodes", "4 memory surfaces", "6-part verification stack", "Escalation packet format"].map((t) => (
            <span key={t} style={{ fontFamily: "var(--font-mono)", fontSize: "11px", letterSpacing: "0.04em", color: "rgba(var(--os-ink-rgb), 0.82)", border: "1px solid rgba(var(--os-line-rgb), 0.2)", borderRadius: "var(--radius-sm)", padding: "5px 11px" }}>{t}</span>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   4 · FOOTER  (dark)
   ============================================================ */
function FooterSection({ theme = "light" }) {
  return (
    <footer style={{ background: "var(--os-footer-bg)", color: "var(--os-ink)", borderTop: "1px solid rgba(var(--os-line-rgb), var(--os-line-op))", padding: "clamp(48px, 7vw, 80px) 0 40px" }}>
      <div style={{ ...WRAP, display: "grid", gridTemplateColumns: "minmax(0,1.4fr) minmax(0,1fr)", gap: "48px", alignItems: "start" }} className="os-2col">
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: "11px", marginBottom: "18px" }}>
            <img src={theme === "dark" ? "assets/opensyn-mark-light.svg" : "assets/opensyn-mark.svg"} width="34" height="34" alt="OpenSyn mark" />
            <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "22px", letterSpacing: "-0.01em" }}>OpenSyn</span>
          </div>
          <p style={{ fontFamily: "var(--font-sans)", fontSize: "14px", lineHeight: 1.55, color: "rgba(var(--os-ink-rgb), 0.68)", margin: 0, maxWidth: "44ch" }}>
            A harness ontology for multi-agent orchestration, inspired by Project Cybersyn.
            Early-stage scaffold, design phase — nothing here executes yet.
          </p>
          <div style={{ display: "flex", gap: "8px", marginTop: "20px", flexWrap: "wrap" }}>
            <OSBadge2 variant="info" dot>Design phase</OSBadge2>
            <OSBadge2 variant="solid">MIT</OSBadge2>
          </div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: "12px" }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: "11px", fontWeight: 600, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--os-dim)", marginBottom: "4px" }}>Where to go next</span>
          {[["Repository", GITHUB_URL], ["docs/architecture.md", GITHUB_URL + "/blob/main/docs/architecture.md"], ["docs/glossary.md", GITHUB_URL + "/blob/main/docs/glossary.md"], ["ONBOARDING.md", GITHUB_URL + "/blob/main/ONBOARDING.md"]].map(([label, href]) => (
            <a key={label} href={href} target="_blank" rel="noopener" style={{ fontFamily: "var(--font-mono)", fontSize: "13px", letterSpacing: "0.02em", color: "rgba(var(--os-ink-rgb), 0.85)", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: "8px" }}>
              <span style={{ color: "var(--c-signal-orange)" }}>→</span>{label}
            </a>
          ))}
        </div>
      </div>
      <div style={{ ...WRAP, marginTop: "48px", paddingTop: "20px", borderTop: "1px solid rgba(var(--os-line-rgb), var(--os-line-op))", display: "flex", flexWrap: "wrap", gap: "12px", alignItems: "center", justifyContent: "space-between" }}>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: "11px", letterSpacing: "0.06em", color: "rgba(var(--os-ink-rgb), 0.55)" }}>© 2026 OpenSyn · MIT License</span>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: "11px", letterSpacing: "0.06em", color: "rgba(var(--os-ink-rgb), 0.55)" }}>After Project Cybersyn / SYNCO · Stafford Beer's Viable System Model</span>
      </div>
    </footer>
  );
}

Object.assign(window, { ConnectionSection, PrinciplesSection, ArchitectureSection, FooterSection, WRAP, SectionLabel, CrtFrame });
