import { useState } from "react";

const TABS = ["Overview", "Architecture", "Agent Harness", "Enterprise", "Pros & Cons", "New Framework"];

// ─── Color Palette ───
const C = {
  bg: "#0a0e17",
  surface: "#111827",
  surfaceAlt: "#1a2236",
  border: "#1e293b",
  accent: "#22d3ee",
  accentDim: "#0e7490",
  warn: "#f59e0b",
  good: "#34d399",
  bad: "#f87171",
  text: "#e2e8f0",
  muted: "#94a3b8",
  heading: "#f1f5f9",
  white: "#ffffff",
  opencode: "#10b981",
  pi: "#a78bfa",
  claude: "#fb923c",
};

const Badge = ({ color, children }) => (
  <span style={{
    display: "inline-block", fontSize: 10, fontWeight: 700,
    padding: "2px 8px", borderRadius: 4,
    background: color + "22", color, letterSpacing: 0.5,
    textTransform: "uppercase", border: `1px solid ${color}44`,
  }}>{children}</span>
);

const SectionTitle = ({ children, sub }) => (
  <div style={{ marginBottom: sub ? 8 : 16, marginTop: sub ? 16 : 24 }}>
    <h3 style={{
      color: C.heading, fontSize: sub ? 15 : 18,
      fontWeight: 700, margin: 0, fontFamily: "'JetBrains Mono', monospace",
      borderBottom: sub ? "none" : `1px solid ${C.border}`,
      paddingBottom: sub ? 0 : 8,
    }}>{children}</h3>
  </div>
);

const Card = ({ title, color, children, icon }) => (
  <div style={{
    background: C.surfaceAlt, border: `1px solid ${color}33`,
    borderRadius: 8, padding: 16, flex: 1, minWidth: 260,
    borderTop: `3px solid ${color}`,
  }}>
    <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
      {icon && <span style={{ fontSize: 18 }}>{icon}</span>}
      <span style={{ color, fontWeight: 700, fontSize: 14, fontFamily: "'JetBrains Mono', monospace" }}>{title}</span>
    </div>
    <div style={{ color: C.text, fontSize: 12.5, lineHeight: 1.65 }}>{children}</div>
  </div>
);

const Row = ({ children }) => (
  <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: 12 }}>{children}</div>
);

const DiagramBox = ({ label, color, children, w, dashed }) => (
  <div style={{
    background: color + "11", border: `${dashed ? "1px dashed" : "1px solid"} ${color}55`,
    borderRadius: 6, padding: "8px 12px", minWidth: w || 120,
    textAlign: "center", position: "relative",
  }}>
    <div style={{ fontSize: 10, fontWeight: 700, color, textTransform: "uppercase", letterSpacing: 0.8 }}>{label}</div>
    {children && <div style={{ fontSize: 11, color: C.muted, marginTop: 4 }}>{children}</div>}
  </div>
);

const Arrow = ({ dir = "down", label, color = C.muted }) => {
  const arrows = { down: "↓", right: "→", left: "←", bidir: "⇄" };
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "2px 4px" }}>
      <span style={{ fontSize: 16, color }}>{arrows[dir]}</span>
      {label && <span style={{ fontSize: 9, color: C.muted, whiteSpace: "nowrap" }}>{label}</span>}
    </div>
  );
};

const ComparisonTable = ({ headers, rows }) => (
  <div style={{ overflowX: "auto", marginBottom: 16 }}>
    <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
      <thead>
        <tr>{headers.map((h, i) => (
          <th key={i} style={{
            padding: "8px 10px", textAlign: "left",
            background: C.surfaceAlt, color: i === 0 ? C.muted : [C.white, C.opencode, C.pi, C.claude][i],
            fontFamily: "'JetBrains Mono', monospace", fontSize: 11,
            borderBottom: `2px solid ${C.border}`, fontWeight: 700,
          }}>{h}</th>
        ))}</tr>
      </thead>
      <tbody>{rows.map((row, ri) => (
        <tr key={ri}>{row.map((cell, ci) => (
          <td key={ci} style={{
            padding: "7px 10px", borderBottom: `1px solid ${C.border}`,
            color: ci === 0 ? C.muted : C.text, fontWeight: ci === 0 ? 600 : 400,
            fontSize: ci === 0 ? 11 : 12, lineHeight: 1.5,
            background: ri % 2 === 0 ? "transparent" : C.surface + "66",
          }}>{cell}</td>
        ))}</tr>
      ))}</tbody>
    </table>
  </div>
);

const ScoreBar = ({ label, scores, colors }) => (
  <div style={{ marginBottom: 10 }}>
    <div style={{ fontSize: 11, color: C.muted, marginBottom: 4, fontWeight: 600 }}>{label}</div>
    <div style={{ display: "flex", gap: 6 }}>
      {scores.map((s, i) => (
        <div key={i} style={{ flex: 1 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 4, marginBottom: 2 }}>
            <span style={{ fontSize: 10, color: colors[i], fontWeight: 700 }}>{["OC", "Pi", "CC"][i]}</span>
            <span style={{ fontSize: 10, color: C.muted }}>{s}/10</span>
          </div>
          <div style={{ height: 6, background: C.surface, borderRadius: 3, overflow: "hidden" }}>
            <div style={{
              width: `${s * 10}%`, height: "100%", borderRadius: 3,
              background: `linear-gradient(90deg, ${colors[i]}88, ${colors[i]})`,
              transition: "width 0.6s ease",
            }} />
          </div>
        </div>
      ))}
    </div>
  </div>
);

// ═══════════════════════════════════════════
// TAB CONTENT
// ═══════════════════════════════════════════

const OverviewTab = () => (
  <div>
    <SectionTitle>Framework Identity Matrix</SectionTitle>
    <Row>
      <Card title="OpenCode" color={C.opencode} icon="⬡">
        <p style={{ margin: 0 }}><strong>Origin:</strong> SST / Anomaly (Jay & team). Launched June 2025.</p>
        <p style={{ margin: "6px 0 0" }}><strong>Philosophy:</strong> "Provider-agnostic, open-source Claude Code." Client-server architecture with Go TUI + Bun/TS backend. Prioritizes community-driven extensibility and terminal-first UX.</p>
        <p style={{ margin: "6px 0 0" }}><strong>Stack:</strong> Go (TUI) + TypeScript/Bun (server) + SQLite + Hono HTTP</p>
        <p style={{ margin: "6px 0 0" }}><strong>Scale:</strong> 100K+ GitHub stars, 700+ contributors, 2.5M monthly devs</p>
      </Card>
      <Card title="Pi-Mono" color={C.pi} icon="π">
        <p style={{ margin: 0 }}><strong>Origin:</strong> Mario Zechner (libGDX creator). Personal project turned ecosystem via OpenClaw.</p>
        <p style={{ margin: "6px 0 0" }}><strong>Philosophy:</strong> "Radically minimal — 4 tools, ~1K token system prompt." Intentionally omits sub-agents, plan mode, MCP — everything is an extension. Unix philosophy for agents.</p>
        <p style={{ margin: "6px 0 0" }}><strong>Stack:</strong> Pure TypeScript monorepo (npm workspaces), Node.js runtime, lockstep versioning</p>
        <p style={{ margin: "6px 0 0" }}><strong>Scale:</strong> Powered OpenClaw (145K+ stars in first week). Growing package ecosystem.</p>
      </Card>
      <Card title="Claude Code" color={C.claude} icon="◈">
        <p style={{ margin: 0 }}><strong>Origin:</strong> Anthropic (1st-party). Tight model-harness co-optimization.</p>
        <p style={{ margin: "6px 0 0" }}><strong>Philosophy:</strong> "Give Claude a computer." Heavily engineered harness with deep model coupling. 90% of its own code written by Claude. Enterprise-first with IAM, analytics, SDK.</p>
        <p style={{ margin: "6px 0 0" }}><strong>Stack:</strong> TypeScript + React/Ink (TUI via Yoga) + Bun. Claude Agent SDK (Python + TS)</p>
        <p style={{ margin: "6px 0 0" }}><strong>Scale:</strong> ~60-100 internal releases/day, 1 external release/day. ~12 engineers.</p>
      </Card>
    </Row>

    <SectionTitle>Key Metrics Comparison</SectionTitle>
    <ComparisonTable
      headers={["Dimension", "OpenCode", "Pi-Mono", "Claude Code"]}
      rows={[
        ["License", "MIT (fully open)", "MIT (fully open)", "Proprietary + SDK (open-source SDK)"],
        ["LLM Lock-in", "None — 20+ providers", "None — 20+ providers", "Claude-only (Bedrock/Vertex routing)"],
        ["Core Language", "Go + TypeScript", "TypeScript (pure)", "TypeScript + React/Ink"],
        ["Runtime", "Bun (server) + Go (TUI)", "Node.js", "Bun"],
        ["Built-in Tools", "~8 (file, bash, LSP, search…)", "4 (read, write, edit, bash)", "~15+ (Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch…)"],
        ["MCP Support", "Native, first-class", "None (by design — use extensions)", "Native, with lazy-loading Tool Search"],
        ["Sub-agents", "Primary + Subagent model (@mention)", "None built-in (spawn via bash/extensions)", "Explore, Plan, General + custom YAML subagents"],
        ["Plan Mode", "Built-in (Tab key toggle)", "None (build via extension/package)", "Built-in (permission_mode='plan')"],
        ["Context Mgmt", "Auto-compaction + event bus", "Auto-compaction (customizable via extensions)", "Auto-compaction + summarization + checkpointing"],
        ["Extension Model", "Markdown agent files + MCP plugins", "TS extensions + skills + prompts + packages", "CLAUDE.md + hooks + subagents + MCP + plugins"],
        ["Enterprise IAM", "❌ Not built-in", "❌ Not built-in", "✅ Native IAM + org analytics"],
        ["SDK / Embedding", "HTTP API (client-server)", "Full SDK + RPC + JSON mode", "Claude Agent SDK (Python + TS)"],
      ]}
    />
  </div>
);

const ArchitectureTab = () => (
  <div>
    <SectionTitle>Architectural Topology Comparison</SectionTitle>

    {/* OpenCode Architecture */}
    <SectionTitle sub>⬡ OpenCode — Client-Server Separation</SectionTitle>
    <div style={{ background: C.surface, border: `1px solid ${C.opencode}33`, borderRadius: 8, padding: 16, marginBottom: 16 }}>
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
        <DiagramBox label="Developer" color={C.accent}>Terminal / Desktop / IDE</DiagramBox>
        <Arrow label="stdin/stdout or HTTP" color={C.opencode} />
        <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap", justifyContent: "center" }}>
          <DiagramBox label="Go TUI Process" color={C.opencode} w={140}>BubbleTea rendering, keymap, sessions</DiagramBox>
          <Arrow dir="bidir" label="HTTP/JSON" color={C.opencode} />
          <DiagramBox label="Bun/TS HTTP Server" color={C.opencode} w={160}>Hono router, AI SDK, session state</DiagramBox>
        </div>
        <Arrow label="Standardized via AI SDK" color={C.opencode} />
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", justifyContent: "center" }}>
          <DiagramBox label="Anthropic" color={C.muted} />
          <DiagramBox label="OpenAI" color={C.muted} />
          <DiagramBox label="Gemini" color={C.muted} />
          <DiagramBox label="Bedrock" color={C.muted} />
          <DiagramBox label="Self-Hosted" color={C.muted} />
        </div>
        <Arrow label="Event Bus" color={C.opencode} />
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", justifyContent: "center" }}>
          <DiagramBox label="SQLite" color={C.muted}>Sessions + History</DiagramBox>
          <DiagramBox label="LSP Client" color={C.muted}>Diagnostics loop</DiagramBox>
          <DiagramBox label="MCP Servers" color={C.muted}>Tool extensions</DiagramBox>
          <DiagramBox label="Filesystem" color={C.muted}>Snapshots</DiagramBox>
        </div>
      </div>
      <div style={{ marginTop: 12, fontSize: 11, color: C.muted, lineHeight: 1.6 }}>
        <strong style={{ color: C.opencode }}>Key Insight:</strong> The client-server split means you can run the Bun server on a powerful remote machine while controlling via lightweight TUI from anywhere. The AI SDK abstracts all LLM provider differences into a unified function-calling interface. Event bus enables loose coupling between LSP diagnostics, tool execution, and UI updates.
      </div>
    </div>

    {/* Pi-Mono Architecture */}
    <SectionTitle sub>π Pi-Mono — Layered Monorepo Composition</SectionTitle>
    <div style={{ background: C.surface, border: `1px solid ${C.pi}33`, borderRadius: 8, padding: 16, marginBottom: 16 }}>
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
        <DiagramBox label="Application Layer" color={C.pi} w={320}>
          pi-coding-agent (CLI) · pi-mom (Slack bot) · pi-web-ui (browser)
        </DiagramBox>
        <Arrow label="composes" color={C.pi} />
        <DiagramBox label="Core Framework" color={C.pi} w={280}>
          pi-agent-core — State machine, tool loop, message queue, events
        </DiagramBox>
        <Arrow label="extends" color={C.pi} />
        <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
          <DiagramBox label="pi-ai" color={C.pi} w={200}>Unified LLM API — 20+ providers, streaming, tool validation</DiagramBox>
          <DiagramBox label="pi-tui" color={C.pi} w={200}>Terminal rendering — diff updates, keyboard, components</DiagramBox>
        </div>
        <Arrow label="runtime" color={C.pi} />
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", justifyContent: "center" }}>
          <DiagramBox label="Extensions" color={C.warn} dashed>Custom tools, hooks, commands, UI</DiagramBox>
          <DiagramBox label="Skills" color={C.warn} dashed>On-demand SKILL.md packages</DiagramBox>
          <DiagramBox label="Pi Packages" color={C.warn} dashed>npm/git distributable bundles</DiagramBox>
        </div>
      </div>
      <div style={{ marginTop: 12, fontSize: 11, color: C.muted, lineHeight: 1.6 }}>
        <strong style={{ color: C.pi }}>Key Insight:</strong> True monorepo with lockstep versioning. Each layer is independently usable — you can import just pi-ai for LLM abstraction, or pi-agent-core to build a non-coding agent. The coding agent is just one application built on reusable primitives. Extensions run with full system access (security-by-review, not sandbox). The 4-tool minimalism (~1K system prompt) maximizes prompt cache hit rate and reduces token waste.
      </div>
    </div>

    {/* Claude Code Architecture */}
    <SectionTitle sub>◈ Claude Code — Tightly-Coupled Model-Harness</SectionTitle>
    <div style={{ background: C.surface, border: `1px solid ${C.claude}33`, borderRadius: 8, padding: 16, marginBottom: 16 }}>
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
        <DiagramBox label="Developer" color={C.accent}>Terminal / VS Code / JetBrains</DiagramBox>
        <Arrow label="CLI / SDK API" color={C.claude} />
        <DiagramBox label="Claude Code Runtime" color={C.claude} w={300}>
          React/Ink TUI · Yoga layout · Permissions engine · Hooks pipeline
        </DiagramBox>
        <Arrow label="Agent Loop (gather → act → verify → repeat)" color={C.claude} />
        <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
          <DiagramBox label="Built-in Tools (15+)" color={C.claude} w={180}>Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch, MultiEdit…</DiagramBox>
          <DiagramBox label="Subagent Orchestrator" color={C.claude} w={180}>Explore, Plan, General + custom .claude/agents/*.md</DiagramBox>
        </div>
        <Arrow label="Permissions → Hooks → Rules → canUseTool" color={C.claude} />
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", justifyContent: "center" }}>
          <DiagramBox label="Claude API" color={C.claude}>Opus 4.5 / Sonnet 4.5</DiagramBox>
          <DiagramBox label="Bedrock" color={C.muted} />
          <DiagramBox label="Vertex AI" color={C.muted} />
          <DiagramBox label="Azure Foundry" color={C.muted} />
        </div>
        <Arrow label="Enterprise Layer" color={C.claude} />
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", justifyContent: "center" }}>
          <DiagramBox label="IAM / SSO" color={C.claude}>Org-wide identity</DiagramBox>
          <DiagramBox label="Analytics API" color={C.claude}>Usage + cost tracking</DiagramBox>
          <DiagramBox label="MCP + Tool Search" color={C.claude}>Lazy-loaded tool discovery</DiagramBox>
          <DiagramBox label="CLAUDE.md" color={C.claude}>Persistent project memory</DiagramBox>
        </div>
      </div>
      <div style={{ marginTop: 12, fontSize: 11, color: C.muted, lineHeight: 1.6 }}>
        <strong style={{ color: C.claude }}>Key Insight:</strong> Claude Code is co-evolved with the model — the harness is tuned via RL to work specifically with Claude models. This tight coupling yields the highest single-model performance but creates vendor lock-in. The 6-tier permission evaluation cascade (deny → allow → ask → hooks → canUseTool → mode) is the most sophisticated permission system of the three. MCP Tool Search ("lazy loading") reduces tool context from ~134K to ~5K tokens — an 85% reduction.
      </div>
    </div>
  </div>
);

const AgentHarnessTab = () => (
  <div>
    <SectionTitle>Agent Loop Sequence Flows</SectionTitle>

    {/* Sequence: OpenCode */}
    <SectionTitle sub>⬡ OpenCode — Event-Driven Agent Loop</SectionTitle>
    <div style={{ background: C.surface, border: `1px solid ${C.opencode}33`, borderRadius: 8, padding: 16, marginBottom: 16, fontFamily: "'JetBrains Mono', monospace", fontSize: 11, lineHeight: 1.8, color: C.text }}>
      <pre style={{ margin: 0, whiteSpace: "pre-wrap", color: C.text }}>{`User ──prompt──▶ Go TUI ──HTTP──▶ Bun Server
                                    │
                              ┌─────▼──────┐
                              │  AI SDK     │ ◀── provider/model-id config
                              │  stream()   │
                              └─────┬──────┘
                                    │ tool_call event
                              ┌─────▼──────────────┐
                              │  Permission Check   │
                              │  "ask" / "allow"    │
                              └─────┬──────────────┘
                                    │ approved
                        ┌───────────┼───────────────┐
                        ▼           ▼               ▼
                   [File Edit]  [Bash Exec]   [LSP Diagnostics]
                        │           │               │
                        └───────────┼───────────────┘
                                    ▼
                              Event Bus Emit
                              (diagnostics, file changes, output)
                                    │
                              ┌─────▼──────┐
                              │  Context    │ ◀── auto-compaction when needed
                              │  Updated    │
                              └─────┬──────┘
                                    │ continue / respond
                                    ▼
                              [Next iteration or final response]
                              
  Subagent flow: Primary agent @mentions subagent
  ──▶ Subagent inherits model, gets own tool scope
  ──▶ Result returned to primary conversation`}</pre>
    </div>

    {/* Sequence: Pi-Mono */}
    <SectionTitle sub>π Pi-Mono — Minimal State-Machine Loop</SectionTitle>
    <div style={{ background: C.surface, border: `1px solid ${C.pi}33`, borderRadius: 8, padding: 16, marginBottom: 16, fontFamily: "'JetBrains Mono', monospace", fontSize: 11, lineHeight: 1.8, color: C.text }}>
      <pre style={{ margin: 0, whiteSpace: "pre-wrap", color: C.text }}>{`User ──prompt──▶ createAgentSession()
                        │
                  ┌─────▼──────┐
                  │ pi-ai       │  stream(model, {messages, tools: [read,write,edit,bash]})
                  │ stream()    │
                  └─────┬──────┘
                        │ toolcall_end event
                  ┌─────▼──────────────┐
                  │ validateToolCall() │ ◀── TypeBox schema validation
                  │ (auto-retry on    │     model retries on failure
                  │  validation fail) │
                  └─────┬──────────────┘
                        │ validated args
                  ┌─────▼──────┐
                  │ Execute    │  read/write/edit/bash — that's it
                  │ 4 tools    │
                  └─────┬──────┘
                        │ tool result
                  ┌─────▼──────────────┐
                  │ session.subscribe()│  emit events to UI/SDK/RPC consumers
                  └─────┬──────────────┘
                        │
                  [Compaction check ──▶ auto-summarize if near limit]
                  [Extension hooks ──▶ context, before_agent_start, tool_call]
                        │
                  [Next iteration or final response]
                  
  "Sub-agent": spawn \`pi --print\` via bash tool
  ──▶ New process, separate context, stdout captured
  ──▶ Result piped back as tool result`}</pre>
    </div>

    {/* Sequence: Claude Code */}
    <SectionTitle sub>◈ Claude Code — Multi-Layer Permission Cascade</SectionTitle>
    <div style={{ background: C.surface, border: `1px solid ${C.claude}33`, borderRadius: 8, padding: 16, marginBottom: 16, fontFamily: "'JetBrains Mono', monospace", fontSize: 11, lineHeight: 1.8, color: C.text }}>
      <pre style={{ margin: 0, whiteSpace: "pre-wrap", color: C.text }}>{`User ──prompt──▶ query(prompt, ClaudeAgentOptions)
                        │
                  ┌─────▼──────────┐
                  │ Claude API     │  Extended thinking + tool calling
                  │ (Opus/Sonnet)  │  Model trained on this harness via RL
                  └─────┬──────────┘
                        │ tool_use block
                  ┌─────▼──────────────────────────────────┐
                  │         Permission Evaluation Cascade    │
                  │  1. settings.json DENY rules            │
                  │  2. settings.json ALLOW rules           │
                  │  3. settings.json ASK rules             │
                  │  4. PreToolUse HOOKS (custom scripts)   │
                  │  5. canUseTool CALLBACK (runtime)       │
                  │  6. Permission MODE (plan/acceptEdits/  │
                  │     bypass/default/delegate/dontAsk)    │
                  └─────┬──────────────────────────────────┘
                        │ decision: allow / deny / modify input
                  ┌─────▼──────┐
                  │ Tool Exec  │  15+ built-in tools, MCP tools (lazy-loaded)
                  │ + snapshot │  auto git snapshot before destructive ops
                  └─────┬──────┘
                        │ result
                  ┌─────▼──────────┐
                  │ PostToolUse    │  hooks for validation, logging, telemetry
                  │ Hooks          │
                  └─────┬──────────┘
                        │
                  [Subagent delegation? ──▶ Explore/Plan/General/Custom]
                  [Context compaction + checkpointing if needed]
                        │
                  ┌─────▼──────┐
                  │ async for  │  stream AssistantMessage / ResultMessage
                  │ message    │
                  └────────────┘`}</pre>
    </div>

    <SectionTitle>Agent Harness Capability Radar</SectionTitle>
    {[
      { label: "Tool Execution Safety", scores: [7, 4, 9] },
      { label: "Context Management (Compaction)", scores: [7, 8, 9] },
      { label: "Sub-agent Orchestration", scores: [8, 5, 9] },
      { label: "Extension / Plugin Model", scores: [7, 9, 8] },
      { label: "Provider Flexibility", scores: [9, 10, 3] },
      { label: "Embedding / SDK Quality", scores: [6, 9, 9] },
      { label: "Long-Running Agent Support", scores: [6, 6, 9] },
      { label: "Prompt Cache Efficiency", scores: [7, 9, 8] },
    ].map(r => (
      <ScoreBar key={r.label} label={r.label} scores={r.scores} colors={[C.opencode, C.pi, C.claude]} />
    ))}
    <div style={{ display: "flex", gap: 16, fontSize: 10, color: C.muted, marginTop: 8 }}>
      <span><span style={{ color: C.opencode }}>■</span> OC = OpenCode</span>
      <span><span style={{ color: C.pi }}>■</span> Pi = Pi-Mono</span>
      <span><span style={{ color: C.claude }}>■</span> CC = Claude Code</span>
    </div>
  </div>
);

const EnterpriseTab = () => (
  <div>
    <SectionTitle>Enterprise Readiness Assessment</SectionTitle>
    <ComparisonTable
      headers={["Enterprise Requirement", "OpenCode", "Pi-Mono", "Claude Code"]}
      rows={[
        ["Identity & Access (IAM/SSO)", "❌ None — BYO auth", "❌ None — BYO auth", "✅ Native IAM, SSO, org-level policies"],
        ["Usage Analytics & Billing", "❌ Manual tracking", "❌ Manual tracking", "✅ Claude Code Analytics API, cost API"],
        ["Data Residency", "✅ Self-host anywhere, no telemetry", "✅ Self-host anywhere, no telemetry", "✅ AWS/GCP regions + Zero Data Retention option"],
        ["Audit Logging", "⚠️ SQLite sessions (basic)", "⚠️ Session files (basic)", "✅ Structured audit trail + hooks for SIEM"],
        ["Sandboxing / Isolation", "⚠️ User-managed (Docker)", "⚠️ Docker via pi-mom; user-managed otherwise", "✅ Permission cascade + hooks + file checkpointing"],
        ["Compliance (SOC2, HIPAA)", "❌ OSS — user responsibility", "❌ OSS — user responsibility", "✅ Anthropic's compliance certifications apply"],
        ["Multi-Tenant Deployment", "⚠️ Possible via client-server split", "⚠️ Possible via pi-mom (Slack bot pattern)", "✅ Workspace-level isolation built-in"],
        ["Model Governance", "✅ Choose any model, version-pin", "✅ Choose any model, mid-session swap", "⚠️ Claude-only, but Bedrock/Vertex give some control"],
        ["Secret Management", "⚠️ Env vars — user-managed", "⚠️ Env vars — user-managed", "✅ Short-lived tokens, scoped permissions guidance"],
        ["CI/CD Integration", "✅ Non-interactive mode (-p flag)", "✅ Print/JSON mode + RPC", "✅ SDK + headless mode + GitHub Actions support"],
        ["Cost Control", "✅ Choose cheaper models freely", "✅ Full model flexibility, token tracking", "⚠️ Claude pricing only; Max plan for heavy use"],
        ["Self-Hosting Capability", "✅ Full (MIT, no phone-home)", "✅ Full (MIT, no phone-home)", "❌ SDK requires Anthropic API (or Bedrock/Vertex)"],
      ]}
    />

    <SectionTitle>Enterprise Architecture Patterns</SectionTitle>
    <Row>
      <Card title="OpenCode for Enterprise" color={C.opencode} icon="⬡">
        <p style={{ margin: 0 }}><strong>Best pattern:</strong> Deploy Bun server in a private VPC behind API gateway. Go TUI clients connect over internal network. Use Zen model service or self-hosted endpoints for model governance. Wrap with enterprise auth proxy (Keycloak/Okta) at the HTTP layer.</p>
        <p style={{ margin: "6px 0 0" }}><strong>Gap:</strong> Requires significant infrastructure work — no turnkey enterprise offering. No built-in RBAC, audit, or compliance tooling.</p>
      </Card>
      <Card title="Pi-Mono for Enterprise" color={C.pi} icon="π">
        <p style={{ margin: 0 }}><strong>Best pattern:</strong> Use pi-agent-core as a library inside your own enterprise platform. The SDK/RPC modes enable embedding pi into existing developer portals. pi-mom pattern (Slack bot with Docker isolation per channel) is a viable multi-tenant template.</p>
        <p style={{ margin: "6px 0 0" }}><strong>Gap:</strong> Extensions run with full system access — enterprise security teams will demand sandboxing. No auth, audit, or governance primitives. The "build it yourself" philosophy is a strength for flexibility but a weakness for compliance.</p>
      </Card>
      <Card title="Claude Code for Enterprise" color={C.claude} icon="◈">
        <p style={{ margin: 0 }}><strong>Best pattern:</strong> Native IAM + Analytics API provides turnkey enterprise onboarding. Claude Agent SDK enables building custom internal agents with inherited security. Bedrock/Vertex routing addresses cloud-specific data residency. PreToolUse hooks integrate with enterprise policy engines.</p>
        <p style={{ margin: "6px 0 0" }}><strong>Gap:</strong> Claude-only model lock-in is a major risk for enterprises committed to multi-vendor AI strategies. Pricing at scale is unpredictable. Proprietary core limits auditing depth.</p>
      </Card>
    </Row>
  </div>
);

const ProsConsTab = () => {
  const items = [
    {
      name: "OpenCode", color: C.opencode, icon: "⬡",
      pros: [
        "Provider-agnostic — zero vendor lock-in, swap models freely",
        "Client-server split enables remote/headless deployment patterns",
        "LSP integration provides real diagnostic feedback loops (not just LLM guessing)",
        "Massive community (100K+ stars) ensures rapid feature development",
        "Event-driven architecture enables loose coupling and extensibility",
        "Automatic git snapshots provide rollback safety for destructive operations",
        "Zen service offers curated, benchmarked model selection for consistency",
      ],
      cons: [
        "Two-language codebase (Go + TS) increases contributor friction and maintenance burden",
        "No enterprise IAM, audit, or compliance primitives — significant wrapping needed",
        "MCP dependency means tool ecosystem quality is inconsistent",
        "Subagent model is less mature than Claude Code's — no persistent memory per subagent",
        "AI SDK abstraction can mask provider-specific optimizations (e.g., prompt caching behavior)",
        "No SDK for embedding into other applications (only HTTP API)",
        "Desktop app is newer and less polished than terminal experience",
      ],
    },
    {
      name: "Pi-Mono", color: C.pi, icon: "π",
      pros: [
        "Minimal by design — 4 tools + ~1K system prompt maximizes prompt cache hits",
        "Layered monorepo (pi-ai → pi-agent-core → pi-coding-agent) enables true composition",
        "Full SDK + RPC + JSON modes make embedding trivially easy",
        "Extension system is the most flexible — register tools, commands, shortcuts, event handlers, UI",
        "Skills system (on-demand SKILL.md loading) provides progressive context disclosure",
        "TypeBox schema validation on tool args with auto-retry is elegant error recovery",
        "Pure TypeScript — single language, low contributor barrier, no cross-language FFI",
        "Pi packages (npm/git distribution) enable a true ecosystem marketplace",
        "Message queuing + steering messages let you redirect agent mid-execution",
      ],
      cons: [
        "\"Build it yourself\" philosophy shifts enterprise burden to the consumer",
        "No built-in sub-agents, plan mode, permissions, or sandboxing out of the box",
        "Extensions run with full system access — no capability sandboxing",
        "Smaller community compared to OpenCode and Claude Code",
        "No LSP integration — diagnostics rely on bash tool calling linters",
        "Single-developer origin means bus factor risk (though community is growing)",
        "No MCP support — deliberate choice but limits interop with broader tool ecosystem",
        "Context compaction is basic unless you build custom via extensions",
      ],
    },
    {
      name: "Claude Code", color: C.claude, icon: "◈",
      pros: [
        "Deepest model-harness co-optimization — Claude is RL-trained on this specific harness",
        "Most sophisticated permission system (6-tier cascade with hooks, rules, callbacks)",
        "Enterprise-ready out of the box — IAM, SSO, Analytics API, cost tracking, ZDR",
        "MCP Tool Search (lazy loading) solves context bloat — 85% token reduction",
        "Claude Agent SDK (Python + TS) is the most polished agent-building framework",
        "Built-in subagents with persistent memory directories across conversations",
        "File checkpointing provides atomic rollback for multi-file operations",
        "Long-running agent patterns (initializer agent + progress files) are pioneering",
        "60-100 internal releases/day — fastest iteration cycle in the space",
        "Hooks system integrates with external policy engines for enterprise governance",
      ],
      cons: [
        "Hard vendor lock-in — Claude models only (Bedrock/Vertex are still Claude)",
        "Proprietary core — cannot self-host or audit the harness source completely",
        "Cost at scale is unpredictable — Max plan ($200/mo) or API pricing",
        "React/Ink TUI has been reported to flicker; terminal experience less polished than Go TUIs",
        "Tight coupling means if Anthropic changes direction, your investment is at risk",
        "90% AI-generated codebase — potential maintenance debt if patterns drift",
        "No model flexibility — can't use GPT, Gemini, or open models for specific subtasks",
        "SDK requires Claude Code CLI to be installed — heavier dependency chain",
      ],
    },
  ];

  return (
    <div>
      <SectionTitle>Detailed Pros & Cons Analysis</SectionTitle>
      {items.map(fw => (
        <div key={fw.name} style={{ marginBottom: 20 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
            <span style={{ fontSize: 18 }}>{fw.icon}</span>
            <span style={{ color: fw.color, fontWeight: 700, fontSize: 16, fontFamily: "'JetBrains Mono', monospace" }}>{fw.name}</span>
          </div>
          <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
            <div style={{ flex: 1, minWidth: 280 }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: C.good, marginBottom: 6, textTransform: "uppercase", letterSpacing: 0.8 }}>✦ Strengths</div>
              {fw.pros.map((p, i) => (
                <div key={i} style={{ fontSize: 12, color: C.text, marginBottom: 5, paddingLeft: 12, borderLeft: `2px solid ${C.good}33`, lineHeight: 1.5 }}>{p}</div>
              ))}
            </div>
            <div style={{ flex: 1, minWidth: 280 }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: C.bad, marginBottom: 6, textTransform: "uppercase", letterSpacing: 0.8 }}>✦ Weaknesses</div>
              {fw.cons.map((c, i) => (
                <div key={i} style={{ fontSize: 12, color: C.text, marginBottom: 5, paddingLeft: 12, borderLeft: `2px solid ${C.bad}33`, lineHeight: 1.5 }}>{c}</div>
              ))}
            </div>
          </div>
        </div>
      ))}
    </div>
  );
};

const NewFrameworkTab = () => (
  <div>
    <SectionTitle>NEXUS — The Hypothetical Enterprise Agent Framework</SectionTitle>
    <div style={{ background: `linear-gradient(135deg, ${C.surfaceAlt}, ${C.surface})`, border: `1px solid ${C.accent}44`, borderRadius: 10, padding: 20, marginBottom: 20 }}>
      <div style={{ fontSize: 13, color: C.accent, fontWeight: 700, fontFamily: "'JetBrains Mono', monospace", marginBottom: 8, letterSpacing: 1 }}>DESIGN THESIS</div>
      <div style={{ fontSize: 13, color: C.text, lineHeight: 1.7 }}>
        Combine Pi-Mono's composable layering and minimal core with OpenCode's provider freedom and event architecture, then add Claude Code's enterprise governance and model-optimized harness — but make every layer swappable, auditable, and sandboxed. The result: a framework where the <strong style={{ color: C.accent }}>agent harness itself is model-aware but not model-locked</strong>, enterprise-governed but not enterprise-inflexible.
      </div>
    </div>

    <SectionTitle sub>The 12 Killer App Features</SectionTitle>

    {[
      {
        n: "01", title: "Universal Model Router with Capability-Aware Dispatch",
        desc: "Not just provider abstraction — a router that understands each model's strengths. Automatically routes code generation to the best coding model, review tasks to the best reasoning model, and boilerplate to the cheapest fast model. Supports quality/cost/latency policies per-task. Enterprises define model governance policies (approved models, max spend per task) and the router enforces them.",
        kills: "Kills Claude Code's lock-in, OpenCode's naive provider switch, and Pi's manual model selection."
      },
      {
        n: "02", title: "Capability-Sandboxed Extension Runtime (WASM + V8 Isolates)",
        desc: "Extensions and skills run in WebAssembly or V8 isolate sandboxes with explicit capability grants (fs:read, fs:write:/project/**, net:*.internal.com, exec:npm,yarn). No more 'full system access' that terrifies security teams. Each extension declares capabilities in a manifest, and the runtime enforces them. Code-signed packages get auto-approved; unsigned packages require admin review.",
        kills: "Kills Pi-Mono's full-access extensions, OpenCode's MCP trust issues, and Claude Code's limited extension model."
      },
      {
        n: "03", title: "Federated Agent Mesh (Not Just Sub-agents)",
        desc: "Agents don't just delegate to sub-agents — they form a mesh where any agent can discover, negotiate with, and compose with any other agent across processes, machines, and even organizations. Built on an Agent Protocol (standardized agent-to-agent communication). Supports agent teams working on a shared codebase with distributed locking, context sharing, and conflict resolution.",
        kills: "Kills Claude Code's single-machine subagents, OpenCode's @mention model, and Pi's bash-spawn workaround."
      },
      {
        n: "04", title: "Native Observability Stack (OpenTelemetry + Agent Traces)",
        desc: "Every agent loop iteration, tool call, LLM request, and context operation emits structured spans and metrics via OpenTelemetry. Includes a custom 'Agent Trace' format that captures the full decision tree — why the agent chose this tool, what context it had, what alternatives it considered (via extended thinking). Plugs directly into Datadog, Grafana, Honeycomb, or any OTEL-compatible backend. Enterprises get cost attribution per team, project, and agent.",
        kills: "Kills the black-box nature of all three frameworks. None currently have production-grade observability."
      },
      {
        n: "05", title: "Composable Permission DSL (Policy-as-Code)",
        desc: "A declarative policy language (like OPA/Rego but for agents) that defines what agents can do, when, and under what conditions. Policies are version-controlled, auditable, and testable. Supports temporal policies (agents can deploy only during business hours), contextual policies (agent can write to /src but not /config in production), and escalation chains (if cost exceeds $X, require human approval).",
        kills: "Kills Claude Code's JSON-file permissions, OpenCode's basic ask/allow, and Pi's non-existent permissions."
      },
      {
        n: "06", title: "Persistent Agent Memory with Vector + Graph Store",
        desc: "Not just CLAUDE.md scratchpads — a structured memory layer combining vector embeddings (for semantic retrieval of past decisions), a knowledge graph (for understanding relationships between code entities), and episodic memory (what happened in past sessions). Shared across agent mesh with access control. Enables institutional knowledge that survives individual sessions and even team changes.",
        kills: "Kills Claude Code's file-based memory, OpenCode's SQLite sessions, and Pi's stateless design."
      },
      {
        n: "07", title: "Multi-Context Window Orchestrator with Progress Checkpoints",
        desc: "Built-in support for tasks that span hours or days. An orchestrator agent decomposes work into checkpoint-able units, each unit produces a verifiable artifact, and a progress manifest tracks overall state. New context windows boot with a synthesized summary of all prior work — not just compaction, but intelligent re-contextualization tailored to the next unit of work.",
        kills: "Kills the context-window-as-session limitation that plagues all three frameworks."
      },
      {
        n: "08", title: "Built-in Compliance Engine (SOC2, HIPAA, GDPR Modes)",
        desc: "First-class compliance modes that enforce data handling rules at the framework level. HIPAA mode: no PHI in tool outputs, auto-redaction in logs, encrypted memory store. SOC2 mode: immutable audit trail, access logging, retention policies. GDPR mode: right-to-erasure support for agent memory, data minimization in context. These aren't afterthoughts — they're built into the permission system and memory layer.",
        kills: "Kills the 'compliance is the user's problem' stance of all three frameworks."
      },
      {
        n: "09", title: "Differential Context Management (Not Just Compaction)",
        desc: "Instead of summarizing old context (lossy), maintain a differential context structure: core invariants (always present), working set (recent, full-fidelity), archived segments (retrievable on demand via vector search), and provenance chains (which context led to which decisions). The model sees a tailored view optimized for the current task, not a truncated conversation history.",
        kills: "Kills basic summarization-based compaction used by all three."
      },
      {
        n: "10", title: "Native CI/CD Agent Pipeline (GitOps-Native)",
        desc: "Agents are first-class citizens in CI/CD. Define agent pipelines in YAML alongside your code. Agents can be triggered by PRs, commits, scheduled cron, or Slack commands. Each pipeline run creates an isolated, reproducible agent environment with pinned model versions, tool versions, and policies. Supports agent-in-the-loop reviews where an agent reviews PRs and a human reviews the agent's review.",
        kills: "Kills the bolt-on CI integration patterns that all three frameworks require."
      },
      {
        n: "11", title: "Hot-Swappable Harness Components (Plugin Architecture for the Framework Itself)",
        desc: "The TUI, the LLM client, the permission engine, the memory store, the tool executor, and the context manager are all swappable components behind well-defined interfaces. Want to use Pi's minimal tool set with Claude Code's permission cascade and OpenCode's LSP diagnostics? Compose them. Enterprise wants to swap the LLM client for their internal gateway? One config change.",
        kills: "Kills the monolithic all-or-nothing adoption model of all three frameworks."
      },
      {
        n: "12", title: "Agent Marketplace with Enterprise Curation",
        desc: "A package ecosystem (like Pi packages but with enterprise governance) where agent configurations, skills, extensions, and pipeline templates are shared, versioned, and rated. Enterprise mode adds: internal-only marketplace, mandatory code review before listing, vulnerability scanning, and usage analytics per package. Community packages undergo automated security analysis before publishing.",
        kills: "Kills the fragmented package/plugin ecosystems across all three frameworks."
      },
    ].map(f => (
      <div key={f.n} style={{ marginBottom: 16, background: C.surfaceAlt, border: `1px solid ${C.border}`, borderRadius: 8, padding: 14, borderLeft: `3px solid ${C.accent}` }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 6 }}>
          <span style={{ color: C.accent, fontWeight: 700, fontSize: 12, fontFamily: "'JetBrains Mono', monospace" }}>#{f.n}</span>
          <span style={{ color: C.heading, fontWeight: 700, fontSize: 14 }}>{f.title}</span>
        </div>
        <div style={{ fontSize: 12.5, color: C.text, lineHeight: 1.65, marginBottom: 8 }}>{f.desc}</div>
        <div style={{ fontSize: 11, color: C.warn, fontStyle: "italic" }}>{f.kills}</div>
      </div>
    ))}

    <SectionTitle sub>NEXUS Architecture Vision</SectionTitle>
    <div style={{ background: C.surface, border: `1px solid ${C.accent}33`, borderRadius: 8, padding: 16, fontFamily: "'JetBrains Mono', monospace", fontSize: 11, lineHeight: 1.8, color: C.text }}>
      <pre style={{ margin: 0, whiteSpace: "pre-wrap", color: C.text }}>{`
┌─────────────────────────────────────────────────────────┐
│                    NEXUS FRAMEWORK                       │
├─────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌──────────────┐  ┌───────────────┐  │
│  │ CLI / TUI   │  │ IDE Plugin   │  │ Web Dashboard │  │
│  │ (Rust-based)│  │ (VS/JB/Zed) │  │ (React)       │  │
│  └──────┬──────┘  └──────┬───────┘  └───────┬───────┘  │
│         └────────────────┼───────────────────┘          │
│                    ┌─────▼─────┐                        │
│                    │ Agent API │  gRPC + REST + WebSocket│
│                    └─────┬─────┘                        │
├──────────────────────────┼──────────────────────────────┤
│  ORCHESTRATION LAYER     │                              │
│  ┌───────────────┐  ┌────▼────┐  ┌──────────────────┐  │
│  │ Model Router  │  │ Agent   │  │ Policy Engine    │  │
│  │ (capability-  │  │ Mesh    │  │ (OPA-compatible  │  │
│  │  aware)       │  │ (P2P)   │  │  permission DSL) │  │
│  └───────┬───────┘  └────┬────┘  └────────┬─────────┘  │
├──────────┼───────────────┼────────────────┼─────────────┤
│  CORE RUNTIME            │                │             │
│  ┌───────▼───────┐  ┌────▼──────┐  ┌─────▼──────────┐  │
│  │ Tool Executor │  │ Context   │  │ Memory Store   │  │
│  │ (WASM sandbox │  │ Manager   │  │ (Vector+Graph  │  │
│  │  + native)    │  │ (differ-  │  │  +Episodic)    │  │
│  │               │  │  ential)  │  │                │  │
│  └───────┬───────┘  └────┬──────┘  └─────┬──────────┘  │
├──────────┼───────────────┼────────────────┼─────────────┤
│  ENTERPRISE LAYER        │                │             │
│  ┌───────▼───────┐  ┌────▼──────┐  ┌─────▼──────────┐  │
│  │ IAM / SSO     │  │ Compliance│  │ Observability  │  │
│  │ (OIDC/SAML)   │  │ Engine   │  │ (OpenTelemetry │  │
│  │               │  │ (SOC2/   │  │  + Agent Trace) │  │
│  │               │  │  HIPAA)  │  │                │  │
│  └───────────────┘  └──────────┘  └────────────────┘  │
├─────────────────────────────────────────────────────────┤
│  INFRASTRUCTURE                                         │
│  ┌──────────┐ ┌──────────┐ ┌────────┐ ┌─────────────┐  │
│  │ Any LLM  │ │ MCP/A2A  │ │ CI/CD  │ │ Marketplace │  │
│  │ Provider │ │ Protocol │ │ Native │ │ (Curated)   │  │
│  └──────────┘ └──────────┘ └────────┘ └─────────────┘  │
└─────────────────────────────────────────────────────────┘`}</pre>
    </div>
  </div>
);

// ═══════════════════════════════════════════
// MAIN COMPONENT
// ═══════════════════════════════════════════

export default function FrameworkComparison() {
  const [tab, setTab] = useState(0);
  const content = [OverviewTab, ArchitectureTab, AgentHarnessTab, EnterpriseTab, ProsConsTab, NewFrameworkTab];
  const TabContent = content[tab];

  return (
    <div style={{
      background: C.bg, color: C.text, minHeight: "100vh",
      fontFamily: "'Segoe UI', -apple-system, sans-serif", fontSize: 13,
    }}>
      {/* Header */}
      <div style={{
        background: `linear-gradient(135deg, ${C.surface} 0%, ${C.surfaceAlt} 100%)`,
        borderBottom: `1px solid ${C.border}`, padding: "20px 24px 16px",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 4 }}>
          <span style={{ fontSize: 22, fontWeight: 800, color: C.heading, fontFamily: "'JetBrains Mono', monospace", letterSpacing: -0.5 }}>
            ◈ AGENT FRAMEWORK
          </span>
          <Badge color={C.accent}>DEEP ANALYSIS</Badge>
        </div>
        <div style={{ fontSize: 12, color: C.muted, marginBottom: 14 }}>
          Technical comparison: OpenCode vs Pi-Mono vs Claude Code — Architecture, Agent Harness, Enterprise Readiness
        </div>

        {/* Tabs */}
        <div style={{ display: "flex", gap: 2, flexWrap: "wrap" }}>
          {TABS.map((t, i) => (
            <button key={t} onClick={() => setTab(i)} style={{
              padding: "7px 14px", fontSize: 11, fontWeight: 600,
              background: tab === i ? C.accent + "22" : "transparent",
              color: tab === i ? C.accent : C.muted,
              border: tab === i ? `1px solid ${C.accent}44` : `1px solid transparent`,
              borderRadius: 6, cursor: "pointer",
              fontFamily: "'JetBrains Mono', monospace",
              transition: "all 0.15s ease",
              letterSpacing: 0.3,
            }}>{t}</button>
          ))}
        </div>
      </div>

      {/* Content */}
      <div style={{ padding: "16px 24px 40px", maxWidth: 960, margin: "0 auto" }}>
        <TabContent />
      </div>
    </div>
  );
}
