import { useRef, useEffect, useState } from 'react';
import { motion } from 'framer-motion';

type DocSection = 'getting-started' | 'cli-reference' | 'workflows' | 'how-it-works';

function ArchitectureDiagram() {
  return (
    <div className="bg-slate-900/80 border border-slate-700/50 rounded-2xl p-6 sm:p-8 overflow-x-auto">
      <div className="min-w-[600px] font-mono text-xs sm:text-sm text-slate-300">
        {/* User Input Layer */}
        <div className="flex justify-center mb-4">
          <div className="bg-sky-500/20 border border-sky-400/50 rounded-lg px-6 py-3 text-sky-400 font-semibold text-center">
            User Prompt / CLI Command
          </div>
        </div>
        <div className="flex justify-center mb-4">
          <div className="text-sky-400/60">|</div>
        </div>

        {/* Orchestrator */}
        <div className="flex justify-center mb-4">
          <div className="bg-cyan-500/15 border border-cyan-400/40 rounded-lg px-6 py-3 text-cyan-400 font-semibold text-center w-72">
            Orchestrator (pulse.py)
            <div className="text-slate-500 text-xs mt-1">Constitution hash check + compliance gate</div>
          </div>
        </div>
        <div className="flex justify-center mb-4">
          <div className="text-cyan-400/60">|</div>
        </div>

        {/* Agent Layer */}
        <div className="flex justify-center gap-3 mb-4">
          {['Claude', 'Gemini', 'Codex', 'Grok', 'Ollama'].map((agent) => (
            <div
              key={agent}
              className="bg-purple-500/15 border border-purple-400/40 rounded-lg px-4 py-2 text-purple-300 text-center"
            >
              {agent}
            </div>
          ))}
        </div>
        <div className="flex justify-center gap-3 mb-4">
          <div className="text-purple-400/60">|</div>
          <div className="w-32" />
          <div className="text-purple-400/60">|</div>
        </div>

        {/* Brain Pipeline */}
        <div className="grid grid-cols-3 gap-3 mb-4">
          <div className="bg-amber-500/15 border border-amber-400/40 rounded-lg px-4 py-3 text-amber-300 text-center">
            <div className="font-semibold">Capture</div>
            <div className="text-slate-500 text-xs mt-1">Signed logs</div>
          </div>
          <div className="bg-amber-500/15 border border-amber-400/40 rounded-lg px-4 py-3 text-amber-300 text-center">
            <div className="font-semibold">Bridge</div>
            <div className="text-slate-500 text-xs mt-1">Extract + Score</div>
          </div>
          <div className="bg-amber-500/15 border border-amber-400/40 rounded-lg px-4 py-3 text-amber-300 text-center">
            <div className="font-semibold">Store</div>
            <div className="text-slate-500 text-xs mt-1">Hippocampus</div>
          </div>
        </div>
        <div className="flex justify-center mb-4">
          <div className="text-amber-400/60">|</div>
        </div>

        {/* Memory Regions */}
        <div className="flex justify-center gap-2 mb-4 flex-wrap">
          {['Lessons', 'Failures', 'Patterns', 'Evidence', 'Knowledge', 'Private'].map((region) => (
            <div
              key={region}
              className="bg-green-500/10 border border-green-400/30 rounded-lg px-3 py-1.5 text-green-300 text-xs"
            >
              {region}
            </div>
          ))}
        </div>
        <div className="flex justify-center mb-4">
          <div className="text-green-400/60">|</div>
        </div>

        {/* Bottom Layer */}
        <div className="grid grid-cols-3 gap-3">
          <div className="bg-rose-500/10 border border-rose-400/30 rounded-lg px-4 py-3 text-rose-300 text-center">
            <div className="font-semibold">Consolidation</div>
            <div className="text-slate-500 text-xs mt-1">22-stage pipeline (dedup, reconsolidation, mining, schema promotion, graph update, pruning, and more)</div>
          </div>
          <div className="bg-rose-500/10 border border-rose-400/30 rounded-lg px-4 py-3 text-rose-300 text-center">
            <div className="font-semibold">Knowledge Graph</div>
            <div className="text-slate-500 text-xs mt-1">362+ nodes, 6 edge types</div>
          </div>
          <div className="bg-rose-500/10 border border-rose-400/30 rounded-lg px-4 py-3 text-rose-300 text-center">
            <div className="font-semibold">Prediction</div>
            <div className="text-slate-500 text-xs mt-1">TP/FP scoring + decay</div>
          </div>
        </div>
      </div>
    </div>
  );
}

const SECTIONS: { id: DocSection; label: string; icon: string }[] = [
  { id: 'getting-started', label: 'Getting Started', icon: 'M13 10V3L4 14h7v7l9-11h-7z' },
  { id: 'cli-reference', label: 'CLI Reference', icon: 'M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z' },
  { id: 'workflows', label: 'Workflows', icon: 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4' },
  { id: 'how-it-works', label: 'How PULSE Works', icon: 'M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z' },
];

export default function Docs() {
  const [activeSection, setActiveSection] = useState<DocSection>('getting-started');
  const sectionRefs = useRef<Record<DocSection, HTMLElement | null>>({
    'getting-started': null,
    'cli-reference': null,
    'workflows': null,
    'how-it-works': null,
  });

  useEffect(() => {
    const observers: IntersectionObserver[] = [];

    for (const section of SECTIONS) {
      const el = sectionRefs.current[section.id];
      if (!el) continue;

      const observer = new IntersectionObserver(
        ([entry]) => {
          if (entry.isIntersecting) {
            setActiveSection(section.id);
          }
        },
        { rootMargin: '-20% 0px -60% 0px' }
      );
      observer.observe(el);
      observers.push(observer);
    }

    return () => observers.forEach((o) => o.disconnect());
  }, []);

  const scrollToSection = (id: DocSection) => {
    sectionRefs.current[id]?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100">
      {/* Header */}
      <div className="border-b border-slate-800/50 bg-slate-900/50 backdrop-blur-sm sticky top-0 z-10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
          <h1 className="text-3xl sm:text-4xl font-bold text-sky-400">Documentation</h1>
          <p className="text-slate-400 mt-2">Everything you need to know about PULSE</p>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex gap-8">
          {/* Sidebar Navigation */}
          <aside className="hidden lg:block w-56 flex-shrink-0">
            <nav className="sticky top-28 space-y-1">
              {SECTIONS.map((section) => (
                <button
                  key={section.id}
                  onClick={() => scrollToSection(section.id)}
                  className={`w-full flex items-center gap-3 px-4 py-3 rounded-lg text-sm font-medium transition-colors duration-200 text-left focus:outline-none focus:ring-2 focus:ring-sky-400 ${
                    activeSection === section.id
                      ? 'bg-slate-800 text-sky-400 border-l-2 border-sky-400'
                      : 'text-slate-400 hover:text-slate-200 hover:bg-slate-800/50'
                  }`}
                >
                  <svg className="w-5 h-5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d={section.icon} />
                  </svg>
                  {section.label}
                </button>
              ))}
            </nav>
          </aside>

          {/* Main Content */}
          <main className="flex-1 min-w-0 space-y-16">
            {/* Getting Started */}
            <section
              ref={(el) => { sectionRefs.current['getting-started'] = el; }}
              id="getting-started"
            >
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.5 }}
              >
                <h2 className="text-2xl font-bold text-sky-400 mb-6">Getting Started</h2>

                <div className="space-y-8">
                  {/* Overview */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
                    <h3 className="text-lg font-semibold text-slate-200 mb-4">What you'll build</h3>
                    <p className="text-slate-400 leading-relaxed mb-4">
                      After completing this guide, you'll have a fully operational PULSE instance with:
                    </p>
                    <ul className="space-y-2 text-slate-400 text-sm">
                      <li className="flex items-start gap-2">
                        <span className="text-sky-400 mt-0.5">-</span>
                        A brain that captures, extracts, and stores knowledge from every agent interaction
                      </li>
                      <li className="flex items-start gap-2">
                        <span className="text-sky-400 mt-0.5">-</span>
                        Constitutional governance enforced by HMAC-SHA256 cryptographic signing
                      </li>
                      <li className="flex items-start gap-2">
                        <span className="text-sky-400 mt-0.5">-</span>
                        A swarm task board where multiple agents self-organize via ASOP protocol
                      </li>
                      <li className="flex items-start gap-2">
                        <span className="text-sky-400 mt-0.5">-</span>
                        CLI tools to monitor status, launch agents, and manage workers
                      </li>
                    </ul>
                  </div>

                  {/* Step 1: Install */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
                    <div className="flex items-start gap-4">
                      <div className="flex-shrink-0 w-10 h-10 rounded-full bg-sky-500/20 border border-sky-400/50 flex items-center justify-center text-sky-400 font-bold">
                        1
                      </div>
                      <div className="flex-1">
                        <h3 className="text-lg font-semibold text-slate-200 mb-3">Install PULSE</h3>
                        <pre className="bg-slate-900/90 border border-slate-700/50 rounded-xl p-4 text-sm font-mono text-green-400 mb-3 overflow-x-auto">
                          <span className="text-sky-400">$</span> pip install pulse-os
                        </pre>
                        <p className="text-slate-400 text-sm">
                          Requires Python 3.9+. See the{' '}
                          <a href="/install" className="text-sky-400 hover:underline">
                            Installation Guide
                          </a>{' '}
                          for platform-specific instructions.
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* Step 2: Initialize */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
                    <div className="flex items-start gap-4">
                      <div className="flex-shrink-0 w-10 h-10 rounded-full bg-sky-500/20 border border-sky-400/50 flex items-center justify-center text-sky-400 font-bold">
                        2
                      </div>
                      <div className="flex-1">
                        <h3 className="text-lg font-semibold text-slate-200 mb-3">Initialize your brain</h3>
                        <pre className="bg-slate-900/90 border border-slate-700/50 rounded-xl p-4 text-sm font-mono text-green-400 mb-3 overflow-x-auto">
                          <span className="text-sky-400">$</span> pulse init
                        </pre>
                        <p className="text-slate-400 text-sm">
                          Creates <code className="px-2 py-0.5 rounded bg-slate-900/80 text-sky-300">~/.pulse/brain/</code>{' '}
                          with 9 memory regions (Lessons, Failures, Patterns, Evidence, Knowledge, Private),
                          a state directory, and default configuration.
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* Step 3: Configure */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
                    <div className="flex items-start gap-4">
                      <div className="flex-shrink-0 w-10 h-10 rounded-full bg-sky-500/20 border border-sky-400/50 flex items-center justify-center text-sky-400 font-bold">
                        3
                      </div>
                      <div className="flex-1">
                        <h3 className="text-lg font-semibold text-slate-200 mb-3">Add your API keys</h3>
                        <pre className="bg-slate-900/90 border border-slate-700/50 rounded-xl p-4 text-sm font-mono text-green-400 mb-3 overflow-x-auto">
{`# Add to ~/.pulse/.env
ANTHROPIC_API_KEY=sk-ant-...
GOOGLE_API_KEY=...
OPENAI_API_KEY=sk-...`}
                        </pre>
                        <p className="text-slate-400 text-sm">
                          Optional — only needed for cloud-hosted models. For local-only usage, install Ollama and
                          PULSE auto-detects available models.
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* Step 4: Launch */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
                    <div className="flex items-start gap-4">
                      <div className="flex-shrink-0 w-10 h-10 rounded-full bg-sky-500/20 border border-sky-400/50 flex items-center justify-center text-sky-400 font-bold">
                        4
                      </div>
                      <div className="flex-1">
                        <h3 className="text-lg font-semibold text-slate-200 mb-3">Launch your first agent</h3>
                        <pre className="bg-slate-900/90 border border-slate-700/50 rounded-xl p-4 text-sm font-mono text-green-400 mb-3 overflow-x-auto">
{`# Interactive agent chat
$ pulse claude
$ pulse gemini

# Check system status
$ pulse status

# Start background workers
$ pulse swarm`}
                        </pre>
                        <p className="text-slate-400 text-sm">
                          <code className="px-2 py-0.5 rounded bg-slate-900/80 text-sky-300">pulse claude</code> launches an
                          interactive session with brain-first enforcement. The agent receives a boot briefing of lessons,
                          failures, and patterns before any work begins.
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* Step 5: Verify */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
                    <div className="flex items-start gap-4">
                      <div className="flex-shrink-0 w-10 h-10 rounded-full bg-green-500/20 border border-green-400/50 flex items-center justify-center text-green-400 font-bold">
                        ✓
                      </div>
                      <div className="flex-1">
                        <h3 className="text-lg font-semibold text-slate-200 mb-3">Verify everything works</h3>
                        <pre className="bg-slate-900/90 border border-slate-700/50 rounded-xl p-4 text-sm font-mono text-green-400 mb-3 overflow-x-auto">
                          <span className="text-sky-400">$</span> pulse status
                        </pre>
                        <p className="text-slate-400 text-sm">
                          You should see orchestrator health, brain stats (lessons, failures, patterns, graph nodes),
                          active agents, and task board summary. If the brain shows 0 items, run an agent session first —
                          knowledge accumulates from interactions.
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </motion.div>
            </section>

            {/* CLI Reference */}
            <section
              ref={(el) => { sectionRefs.current['cli-reference'] = el; }}
              id="cli-reference"
            >
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ once: true, margin: '-80px' }}
                transition={{ duration: 0.5 }}
              >
                <h2 className="text-2xl font-bold text-sky-400 mb-6">CLI Reference</h2>
                <p className="text-slate-400 mb-8">
                  Every command starts with <code className="px-2 py-0.5 rounded bg-slate-900/80 text-sky-300">pulse</code>.
                  Run <code className="px-2 py-0.5 rounded bg-slate-900/80 text-sky-300">pulse</code> with no arguments to open the interactive agent picker.
                </p>

                <div className="space-y-8">
                  {/* Agents */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-6">
                    <h3 className="text-lg font-semibold text-sky-400 mb-4">Agents (Interactive Chat)</h3>
                    <div className="space-y-3 font-mono text-sm">
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse</code><span className="text-slate-400">Interactive picker — choose provider, model, and start chatting</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse claude</code><span className="text-slate-400">Launch Claude (pick model: Haiku, Sonnet, Opus)</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse gemini</code><span className="text-slate-400">Launch Gemini (pick model: Flash, Pro, 3.x preview)</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse codex</code><span className="text-slate-400">Launch OpenAI Codex</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse grok</code><span className="text-slate-400">Launch Grok (xAI)</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse ollama</code><span className="text-slate-400">Launch a local Ollama model (zero API cost)</span></div>
                    </div>
                  </div>

                  {/* Swarm */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-6">
                    <h3 className="text-lg font-semibold text-sky-400 mb-4">Swarm (Background Workers)</h3>
                    <div className="space-y-3 font-mono text-sm">
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse swarm</code><span className="text-slate-400">Interactive crew builder — pick providers, models, and worker count</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse swarm gemini</code><span className="text-slate-400">Skip to Gemini model picker</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse swarm status</code><span className="text-slate-400">Show running workers and their current tasks</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse swarm stop</code><span className="text-slate-400">Kill all background workers</span></div>
                    </div>
                  </div>

                  {/* Task Board */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-6">
                    <h3 className="text-lg font-semibold text-sky-400 mb-4">Task Board</h3>
                    <div className="space-y-3 font-mono text-sm">
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse post "task description"</code><span className="text-slate-400">Post a single task to the board</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse relay "big prompt"</code><span className="text-slate-400">Auto-decompose a prompt into multiple tasks via LLM</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse clean</code><span className="text-slate-400">Remove completed tasks and release stale claims</span></div>
                    </div>
                  </div>

                  {/* Monitoring */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-6">
                    <h3 className="text-lg font-semibold text-sky-400 mb-4">Monitoring</h3>
                    <div className="space-y-3 font-mono text-sm">
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse status</code><span className="text-slate-400">System health, brain stats, active agents, task board</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse watch</code><span className="text-slate-400">Auto-refreshing status dashboard (updates every 3s)</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse brain</code><span className="text-slate-400">Brain usage dashboard — lessons, patterns, graph nodes</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse costs</code><span className="text-slate-400">Token usage and cost breakdown per provider</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse logs [worker_id]</code><span className="text-slate-400">Tail worker logs in real time</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse dashboard [port]</code><span className="text-slate-400">Launch the web monitoring UI</span></div>
                    </div>
                  </div>

                  {/* Synthesis */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-6">
                    <h3 className="text-lg font-semibold text-sky-400 mb-4">Synthesis (Advanced)</h3>
                    <div className="space-y-3 font-mono text-sm">
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse forage</code><span className="text-slate-400">Verify stale knowledge against the web</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse synthesize</code><span className="text-slate-400">Detect proven skill chains and propose composites</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse hebbian</code><span className="text-slate-400">Update model-domain performance weights from outcomes</span></div>
                    </div>
                  </div>

                  {/* System */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-6">
                    <h3 className="text-lg font-semibold text-sky-400 mb-4">System</h3>
                    <div className="space-y-3 font-mono text-sm">
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse init</code><span className="text-slate-400">Initialize PULSE brain for the current project</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse start</code><span className="text-slate-400">Start the orchestrator and all background daemons</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse stop</code><span className="text-slate-400">Stop all PULSE processes</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse activate &lt;KEY&gt;</code><span className="text-slate-400">Activate a license key</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse license</code><span className="text-slate-400">Show current license and plan info</span></div>
                      <div className="flex gap-4"><code className="text-green-400 w-64 flex-shrink-0">pulse uninstall</code><span className="text-slate-400">Remove PULSE data for this project</span></div>
                    </div>
                  </div>
                </div>
              </motion.div>
            </section>

            {/* Workflows */}
            <section
              ref={(el) => { sectionRefs.current['workflows'] = el; }}
              id="workflows"
            >
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ once: true, margin: '-80px' }}
                transition={{ duration: 0.5 }}
              >
                <h2 className="text-2xl font-bold text-sky-400 mb-6">Workflows</h2>
                <p className="text-slate-400 mb-8">
                  Real patterns that save time and money. PULSE is designed around these workflows — not as an afterthought.
                </p>

                <div className="space-y-8">
                  {/* Workflow 1: Orchestrator Pattern */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
                    <h3 className="text-lg font-semibold text-sky-400 mb-2">The Orchestrator Pattern</h3>
                    <p className="text-slate-400 text-sm mb-4">One interactive agent plans the work. The swarm executes it.</p>

                    <div className="bg-slate-900/90 border border-slate-700/50 rounded-xl p-5 font-mono text-sm space-y-4 mb-4">
                      <div>
                        <div className="text-slate-500 mb-1"># Step 1: Open an interactive agent as your orchestrator</div>
                        <div><span className="text-sky-400">$</span> <span className="text-green-400">pulse gemini</span></div>
                      </div>
                      <div>
                        <div className="text-slate-500 mb-1"># Step 2: Tell it your big task — it decomposes into subtasks</div>
                        <div className="text-slate-300">&gt; "Refactor the auth module, add rate limiting, write tests,</div>
                        <div className="text-slate-300">&gt;  and update the API docs. Post everything to the task board."</div>
                      </div>
                      <div>
                        <div className="text-slate-500 mb-1"># The agent runs: pulse relay --tasks "Refactor auth:refactoring:medium" ...</div>
                        <div className="text-slate-500"># Tasks land on the board, tiered by complexity</div>
                      </div>
                      <div>
                        <div className="text-slate-500 mb-1"># Step 3: Launch a swarm to execute in parallel</div>
                        <div><span className="text-sky-400">$</span> <span className="text-green-400">pulse swarm</span></div>
                        <div className="text-slate-500"># Pick 5x Gemini Flash (fast tier, $0.001/task) for docs + tests</div>
                        <div className="text-slate-500"># Pick 3x Sonnet (standard tier) for the feature work</div>
                        <div className="text-slate-500"># Pick 1x Opus (premium tier) for the architecture refactor</div>
                      </div>
                    </div>

                    <div className="bg-sky-500/10 border border-sky-400/30 rounded-xl p-4">
                      <p className="text-sky-300 text-sm font-medium mb-1">Why this works</p>
                      <p className="text-slate-400 text-sm">
                        You give one prompt. The orchestrator agent breaks it into 8-12 tasks. 9 workers execute
                        them in parallel in under 10 minutes. Without PULSE, you'd manually prompt each task one by one — that's 45+ minutes of copy-paste-wait.
                      </p>
                    </div>
                  </div>

                  {/* Workflow 2: Cost-Optimized Swarm */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
                    <h3 className="text-lg font-semibold text-sky-400 mb-2">Cost-Optimized Swarm</h3>
                    <p className="text-slate-400 text-sm mb-4">Use cheap models for simple work, premium models only when it matters.</p>

                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                      <div className="bg-green-500/10 border border-green-400/30 rounded-xl p-4 text-center">
                        <div className="text-green-400 font-semibold mb-1">Fast Tier</div>
                        <div className="text-slate-400 text-xs mb-2">Haiku, Flash, o4-mini</div>
                        <div className="text-slate-300 text-sm">Docs, formatting, renaming, simple tests</div>
                        <div className="text-green-400 text-xs mt-2 font-mono">~$0.001 per task</div>
                      </div>
                      <div className="bg-amber-500/10 border border-amber-400/30 rounded-xl p-4 text-center">
                        <div className="text-amber-400 font-semibold mb-1">Standard Tier</div>
                        <div className="text-slate-400 text-xs mb-2">Sonnet, Gemini Pro, Codex</div>
                        <div className="text-slate-300 text-sm">Features, refactoring, integration</div>
                        <div className="text-amber-400 text-xs mt-2 font-mono">~$0.01 per task</div>
                      </div>
                      <div className="bg-purple-500/10 border border-purple-400/30 rounded-xl p-4 text-center">
                        <div className="text-purple-400 font-semibold mb-1">Premium Tier</div>
                        <div className="text-slate-400 text-xs mb-2">Opus, Gemini 3 Pro, o3</div>
                        <div className="text-slate-300 text-sm">Architecture, security, complex design</div>
                        <div className="text-purple-400 text-xs mt-2 font-mono">~$0.10 per task</div>
                      </div>
                    </div>

                    <div className="bg-sky-500/10 border border-sky-400/30 rounded-xl p-4">
                      <p className="text-sky-300 text-sm font-medium mb-1">Real example</p>
                      <p className="text-slate-400 text-sm">
                        A 12-task project: 6 fast tasks ($0.006) + 4 standard ($0.04) + 2 premium ($0.20) = <strong className="text-sky-300">$0.25 total</strong>.
                        Without tiering, running everything on a premium model would cost $1.20. PULSE auto-assigns tiers, so you save 80% by default.
                      </p>
                    </div>
                  </div>

                  {/* Workflow 3: Brain-First Development */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
                    <h3 className="text-lg font-semibold text-sky-400 mb-2">Brain-First Development</h3>
                    <p className="text-slate-400 text-sm mb-4">Every agent starts every session by reading what the team already learned.</p>

                    <div className="bg-slate-900/90 border border-slate-700/50 rounded-xl p-5 font-mono text-sm space-y-3 mb-4">
                      <div>
                        <div className="text-slate-500"># When any agent boots, it automatically receives:</div>
                        <div className="text-amber-400">  [BRAIN] 47 lessons | 23 failures | 18 patterns | 362 graph nodes</div>
                        <div className="text-amber-400">  [BRAIN] WARNING: auth_handler.py has 3 known failure patterns</div>
                        <div className="text-amber-400">  [BRAIN] PREDICTION: timezone bug likely in billing module (0.87 confidence)</div>
                      </div>
                      <div>
                        <div className="text-slate-500"># The agent now knows:</div>
                        <div className="text-slate-300">  - What patterns work in this codebase</div>
                        <div className="text-slate-300">  - What mistakes were already made (and how to avoid them)</div>
                        <div className="text-slate-300">  - Which files are risky and why</div>
                      </div>
                    </div>

                    <div className="bg-sky-500/10 border border-sky-400/30 rounded-xl p-4">
                      <p className="text-sky-300 text-sm font-medium mb-1">The compound effect</p>
                      <p className="text-slate-400 text-sm">
                        Week 1: Brain has 10 lessons. Week 4: 200+ lessons, 80 patterns, and a knowledge graph connecting everything.
                        By month 2, your agents are making decisions informed by hundreds of past interactions. New team members
                        (human or AI) inherit all of it instantly. No onboarding, no lost context, no repeated mistakes.
                      </p>
                    </div>
                  </div>

                  {/* Workflow 4: Scale Example */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
                    <h3 className="text-lg font-semibold text-sky-400 mb-2">Scaling: 20 Workers on a Real Project</h3>
                    <p className="text-slate-400 text-sm mb-4">A concrete example of what PULSE can do at scale.</p>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      <div className="bg-red-500/10 border border-red-400/30 rounded-xl p-5">
                        <h4 className="text-red-400 font-semibold mb-3">Without PULSE</h4>
                        <ul className="text-slate-400 text-sm space-y-2">
                          <li>- Open Claude, explain your codebase (5 min)</li>
                          <li>- Ask for auth refactor, wait for response (3 min)</li>
                          <li>- Review, apply, then open new chat for tests (2 min)</li>
                          <li>- Re-explain everything to the new session (5 min)</li>
                          <li>- Repeat for each of 12 tasks...</li>
                          <li className="text-red-400 font-semibold pt-2">Total: ~2-3 hours of manual prompting</li>
                        </ul>
                      </div>
                      <div className="bg-green-500/10 border border-green-400/30 rounded-xl p-5">
                        <h4 className="text-green-400 font-semibold mb-3">With PULSE</h4>
                        <ul className="text-slate-400 text-sm space-y-2">
                          <li>- <code className="text-sky-300">pulse gemini</code> → "Here's the plan, post it" (2 min)</li>
                          <li>- <code className="text-sky-300">pulse swarm</code> → pick 10 Flash + 8 Pro + 2 Opus (1 min)</li>
                          <li>- 20 workers claim tasks and execute in parallel</li>
                          <li>- <code className="text-sky-300">pulse watch</code> → monitor progress live</li>
                          <li>- All workers share the same brain context</li>
                          <li className="text-green-400 font-semibold pt-2">Total: ~12 minutes hands-off</li>
                        </ul>
                      </div>
                    </div>
                  </div>
                </div>
              </motion.div>
            </section>

            {/* How PULSE Works */}
            <section
              ref={(el) => { sectionRefs.current['how-it-works'] = el; }}
              id="how-it-works"
            >
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ once: true, margin: '-80px' }}
                transition={{ duration: 0.5 }}
              >
                <h2 className="text-2xl font-bold text-sky-400 mb-6">How PULSE Works</h2>

                <div className="space-y-8">
                  {/* Intro */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
                    <p className="text-slate-300 leading-relaxed">
                      PULSE is modeled after the human brain. The <strong className="text-sky-400">Hippocampus</strong> stores
                      and consolidates memories. The <strong className="text-sky-400">Corpus Callosum</strong> enforces
                      governance across hemispheres. The <strong className="text-sky-400">Prefrontal Cortex</strong> manages
                      task planning and execution. Multiple agents operate as neurons in this system — each specialized, all
                      connected through shared infrastructure.
                    </p>
                  </div>

                  {/* Architecture Diagram */}
                  <div>
                    <h3 className="text-lg font-semibold text-slate-200 mb-4">Architecture Overview</h3>
                    <ArchitectureDiagram />
                  </div>

                  {/* Key Subsystems */}
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-6">
                      <h4 className="text-sky-400 font-semibold mb-3">Brain Pipeline</h4>
                      <p className="text-slate-400 text-sm leading-relaxed">
                        <strong className="text-slate-300">Capture</strong> signed agent logs →{' '}
                        <strong className="text-slate-300">Bridge</strong> extracts knowledge via 62+ patterns with
                        salience scoring →{' '}
                        <strong className="text-slate-300">Store</strong> in 9 Hippocampus regions →{' '}
                        <strong className="text-slate-300">Consolidate</strong> every 6h (dedup, pattern mine, schema
                        promote) →{' '}
                        <strong className="text-slate-300">Boot</strong> briefing injects compressed intelligence into
                        every agent session.
                      </p>
                    </div>

                    <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-6">
                      <h4 className="text-sky-400 font-semibold mb-3">Constitutional Governance</h4>
                      <p className="text-slate-400 text-sm leading-relaxed">
                        The Constitution is hash-locked (SHA-256 in .env). Tampering kills the orchestrator. 4
                        immutable Tier 0 laws + 10 Sacred Laws enforced via HMAC-SHA256 signing, compliance
                        validators, and pre-commit hooks. Governance is silent — users see work, not ceremony.
                      </p>
                    </div>

                    <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-6">
                      <h4 className="text-sky-400 font-semibold mb-3">Swarm Coordination</h4>
                      <p className="text-slate-400 text-sm leading-relaxed">
                        The ASOP protocol manages a shared task board. Tasks are decomposed by complexity tier (fast,
                        standard, premium) and claimed atomically by agents. Background workers poll every 5s,
                        heartbeat every 30s, and auto-release stale claims after 5 minutes.
                      </p>
                    </div>

                    <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-6">
                      <h4 className="text-sky-400 font-semibold mb-3">Knowledge Graph</h4>
                      <p className="text-slate-400 text-sm leading-relaxed">
                        362+ nodes with 6 edge types (CAUSES, PREVENTS, REQUIRES, LEADS_TO, SIMILAR_TO, CONTRADICTS).
                        The graph connects lessons to failures, patterns to decisions, and evidence to schemas. The
                        prediction daemon uses it to score failure risks with confidence decay.
                      </p>
                    </div>
                  </div>

                  {/* Package Structure */}
                  <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
                    <h3 className="text-lg font-semibold text-slate-200 mb-4">Package Structure</h3>
                    <pre className="bg-slate-900/90 border border-slate-700/50 rounded-xl p-4 text-sm font-mono text-slate-300 overflow-x-auto leading-relaxed">
{`pulse/
├── core/         # brain_utils, config, paths, crypto
├── brain/        # search, query, save, boot, extraction
├── agents/       # claude, gemini, codex, grok wrappers
├── workers/      # headless task execution daemons
├── tasks/        # dispatcher, relay, decomposer
├── daemons/      # orchestrator, bridge, neural, consolidation
├── graph/        # knowledge graph build + query
├── api/          # REST endpoints (/v1/brain/*, /v1/system/*)
├── admin/        # 30 maintenance + audit tools
├── cli/          # status, swarm, manage, agent commands
└── config/       # brain_config.json, knowledge_anchors.json`}
                    </pre>
                  </div>
                </div>
              </motion.div>
            </section>

            {/* FAQ Link */}
            <div className="bg-sky-500/10 border border-sky-400/30 rounded-2xl p-8 text-center">
              <h2 className="text-2xl font-bold text-sky-400 mb-3">Have Questions?</h2>
              <p className="text-slate-400 mb-4">Check our comprehensive FAQ for answers to common questions.</p>
              <a href="/faq" className="inline-block px-8 py-3 rounded-xl bg-gradient-to-r from-sky-500 to-cyan-500 text-slate-950 font-semibold hover:shadow-sky-400/75 hover:-translate-y-1 transition-all duration-200">
                View FAQ →
              </a>
            </div>
          </main>
        </div>
      </div>
    </div>
  );
}
