// pages/home-core.jsx — How It Works + Feature Grid + Integrations

function FlowDiagram() {
  const cx = 200, bw = 210, bh = 60;
  return (
    <svg viewBox="0 0 400 470" style={{ width: '100%', maxWidth: '400px', display: 'block', margin: '0 auto' }}>
      <defs>
        <radialGradient id="fglow" cx="50%" cy="50%" r="60%">
          <stop offset="0%" stopColor="#6366f1" stopOpacity="0.06" />
          <stop offset="100%" stopColor="#6366f1" stopOpacity="0" />
        </radialGradient>
        <marker id="arrow" markerWidth="6" markerHeight="6" refX="3" refY="3" orient="auto">
          <path d="M0,0 L6,3 L0,6 Z" fill="var(--color-border-hover)" />
        </marker>
      </defs>
      <rect width="400" height="470" fill="url(#fglow)" rx="12" />

      {/* Node 1 — Agent */}
      <rect x={cx-bw/2} y={20} width={bw} height={bh} rx="8" fill="var(--color-surface)" stroke="var(--color-border)" strokeWidth="1" />
      <text x={cx} y={44} textAnchor="middle" fill="var(--color-text)" fontSize="12.5" fontWeight="600" fontFamily="var(--font-sans)">Your Agent / App</text>
      <text x={cx} y={62} textAnchor="middle" fill="var(--color-muted)" fontSize="10" fontFamily="var(--font-mono)">any framework</text>

      {/* Connector 1 */}
      <line x1={cx} y1={80} x2={cx} y2={140} stroke="var(--color-border-hover)" strokeWidth="1.5" strokeDasharray="6 4" markerEnd="url(#arrow)">
        <animate attributeName="stroke-dashoffset" from="0" to="-30" dur="1.5s" repeatCount="indefinite" />
      </line>
      <text x={cx+14} y={110} fill="var(--color-muted)" fontSize="10" fontFamily="var(--font-mono)">Unix socket + HMAC</text>

      {/* Node 2 — Daemon (brand) */}
      <rect x={cx-bw/2-8} y={142} width={bw+16} height={72} rx="8" fill="rgba(99,102,241,0.06)" stroke="rgba(99,102,241,0.35)" strokeWidth="1" />
      <text x={cx} y={168} textAnchor="middle" fill="var(--color-text)" fontSize="12.5" fontWeight="700" fontFamily="var(--font-sans)">Vela Daemon</text>
      <text x={cx} y={185} textAnchor="middle" fill="var(--color-brand-400)" fontSize="10" fontFamily="var(--font-mono)">Rust / Tokio</text>
      <text x={cx} y={202} textAnchor="middle" fill="var(--color-muted)" fontSize="9" fontFamily="var(--font-mono)">policy.yaml · intrusion_rules.toml</text>

      {/* Connector 2 */}
      <line x1={cx} y1={214} x2={cx} y2={272} stroke="var(--color-border-hover)" strokeWidth="1.5" strokeDasharray="6 4" markerEnd="url(#arrow)">
        <animate attributeName="stroke-dashoffset" from="0" to="-30" dur="1.5s" begin="0.5s" repeatCount="indefinite" />
      </line>
      <text x={cx+14} y={237} fill="var(--color-muted)" fontSize="10" fontFamily="var(--font-mono)">spawn · warmed pool</text>
      <text x={cx+14} y={252} fill="var(--color-brand-400)" fontSize="10" fontFamily="var(--font-mono)">~150ms p50</text>

      {/* Node 3 — Firecracker VM */}
      <rect x={cx-bw/2} y={274} width={bw} height={72} rx="8" fill="var(--color-surface)" stroke="var(--color-border)" strokeWidth="1" />
      <text x={cx} y={300} textAnchor="middle" fill="var(--color-text)" fontSize="12.5" fontWeight="600" fontFamily="var(--font-sans)">Firecracker VM</text>
      <text x={cx} y={318} textAnchor="middle" fill="var(--color-muted)" fontSize="10" fontFamily="var(--font-mono)">KVM · isolated kernel</text>
      <text x={cx} y={334} textAnchor="middle" fill="var(--color-muted)" fontSize="9.5" fontFamily="var(--font-mono)">python3 / bash / node</text>

      {/* Connector 3 */}
      <line x1={cx} y1={346} x2={cx} y2={394} stroke="var(--color-border-hover)" strokeWidth="1.5" strokeDasharray="6 4" markerEnd="url(#arrow)">
        <animate attributeName="stroke-dashoffset" from="0" to="-30" dur="1.5s" begin="1s" repeatCount="indefinite" />
      </line>

      {/* Node 4 — Output */}
      <rect x={cx-bw/2} y={396} width={bw} height={62} rx="8" fill="var(--color-surface)" stroke="var(--color-border)" strokeWidth="1" />
      <text x={cx} y={420} textAnchor="middle" fill="var(--color-text)" fontSize="12" fontWeight="600" fontFamily="var(--font-sans)">Structured Response</text>
      <text x={cx} y={438} textAnchor="middle" fill="var(--color-brand-400)" fontSize="9.5" fontFamily="var(--font-mono)">JSON · JSONL · Prometheus · Webhook</text>
    </svg>
  );
}

const PRIMITIVES = [
  {
    n: '01', title: 'Micro-VM isolation',
    text: 'Firecracker boots a fresh VM from a pre-warmed pool. Your host OS is never touched. Each run is hermetically sealed.',
  },
  {
    n: '02', title: 'Capability tokens',
    text: 'HMAC-SHA256 signed tokens declare exactly what each caller can do: which paths, network access, memory limit, timeout.',
  },
  {
    n: '03', title: 'Full audit trail',
    text: 'Every execution event is written to an append-only JSONL log, broadcast to a live stream socket, queryable by ID.',
  },
];

function HowItWorksSection() {
  return (
    <section style={{ padding: '7rem 0', background: 'var(--color-bg)' }}>
      <div className="container">
        <AnimEl style={{ marginBottom: '4rem' }}>
          <SectionHeader
            eyebrow="How it works"
            title="Three primitives.<br/>Unlimited control."
            sub="Vela stacks hardware isolation, cryptographic authorization, and structured observability into one cohesive runtime."
          />
        </AnimEl>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: '4rem', alignItems: 'center' }}>
          <AnimEl>
            <FlowDiagram />
          </AnimEl>

          <div style={{ display: 'flex', flexDirection: 'column', gap: '2rem' }}>
            {PRIMITIVES.map((p, i) => (
              <AnimEl key={p.n} delay={i + 1} style={{ display: 'flex', gap: '1.25rem' }}>
                <span style={{
                  fontFamily: 'var(--font-mono)', fontSize: '0.75rem', fontWeight: 700,
                  color: 'var(--color-brand-400)', background: 'rgba(99,102,241,0.08)',
                  border: '1px solid rgba(99,102,241,0.2)', borderRadius: 'var(--radius-full)',
                  width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                }}>{p.n}</span>
                <div>
                  <h3 style={{ fontWeight: 600, fontSize: '1.0625rem', marginBottom: '0.375rem' }}>{p.title}</h3>
                  <p style={{ color: 'var(--color-muted)', fontSize: '0.9rem', lineHeight: 1.7 }}>{p.text}</p>
                </div>
              </AnimEl>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

const FEATURES = [
  { Icon: IcoShield, title: 'Firecracker isolation', desc: 'Hardware-level VM isolation per execution. ~150ms p50 with pre-warmed pool. Nothing leaks between runs.' },
  { Icon: IcoKey, title: 'Capability tokens', desc: 'HMAC-SHA256 signed tokens grant scoped permissions — filesystem paths, network, syscalls, memory, timeout.' },
  { Icon: IcoScroll, title: 'Policy engine', desc: 'Ship a YAML deny list. Block rm -rf, curl, or any pattern. Require human approval for sensitive operations.' },
  { Icon: IcoAlertTriangle, title: 'Intrusion detection', desc: 'Syscall spikes, /etc/shadow access, private network connections — flagged in real time with structured alerts.' },
  { Icon: IcoBarChart, title: 'Prometheus metrics', desc: '/metrics endpoint. 7 counters ready for Grafana. Rate-limited requests, webhooks, failures — all visible.' },
  { Icon: IcoLayers, title: 'Framework adapters', desc: 'LangChain, LlamaIndex, CrewAI, OpenAI function tools. One import. Drop it into your agent stack today.' },
];

const SECONDARY = [
  'Webhook notifications on completion', 'Per-API-key rate limiting (no Redis)',
  'Execution labels / tags', 'Async Python client (asyncio-native)',
  'JavaScript / Node.js execution', 'VM snapshot restore (fast cold start)',
  '--no-vm mode for CI / dev', 'SQLite-backed execution store',
];

function FeatureGridSection() {
  return (
    <section style={{ padding: '7rem 0', background: 'var(--color-surface)' }}>
      <div className="container">
        <AnimEl style={{ marginBottom: '3.5rem' }}>
          <SectionHeader
            eyebrow="Features"
            title="Everything you need.<br/>Nothing you don't."
            sub="Six carefully designed primitives that compose into a complete secure execution layer."
          />
        </AnimEl>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: '1.25rem', marginBottom: '3rem' }}>
          {FEATURES.map(({ Icon, title, desc }, i) => (
            <AnimEl key={title} delay={(i % 3) + 1}>
              <div className="card card-glow" style={{ height: '100%', cursor: 'default' }}>
                <div style={{ color: 'var(--color-brand-400)', marginBottom: '0.875rem', width: 40, height: 40, background: 'rgba(99,102,241,0.08)', borderRadius: 'var(--radius-md)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon size={20} />
                </div>
                <h3 style={{ fontWeight: 600, fontSize: '1rem', marginBottom: '0.5rem' }}>{title}</h3>
                <p style={{ color: 'var(--color-muted)', fontSize: '0.875rem', lineHeight: 1.7, margin: 0 }}>{desc}</p>
              </div>
            </AnimEl>
          ))}
        </div>

        {/* Secondary features */}
        <AnimEl>
          <div style={{
            background: 'var(--color-bg)', border: '1px solid var(--color-border)',
            borderRadius: 'var(--radius-lg)', padding: '1.5rem 2rem',
            display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: '0.625rem',
          }}>
            {SECONDARY.map(f => (
              <div key={f} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', fontSize: '0.875rem', color: 'var(--color-muted)' }}>
                <IcoCheck size={14} style={{ color: 'var(--color-green)', flexShrink: 0 }} />
                {f}
              </div>
            ))}
          </div>
        </AnimEl>
      </div>
    </section>
  );
}

const INTEGRATIONS = [
  { emoji: '🦜', name: 'LangChain' }, { emoji: '🦙', name: 'LlamaIndex' },
  { emoji: '🤖', name: 'CrewAI' },   { emoji: '✦', name: 'OpenAI' },
  { emoji: '🦀', name: 'Rust' },     { emoji: '🐍', name: 'Python' },
  { emoji: '🔥', name: 'Firecracker' }, { emoji: '📊', name: 'Prometheus' },
  { emoji: '📈', name: 'Grafana' },  { emoji: '🗄️', name: 'SQLite' },
];

function IntegrationsSection() {
  return (
    <section style={{ padding: '6rem 0', background: 'var(--color-bg)' }}>
      <div className="container">
        <AnimEl style={{ marginBottom: '2.5rem' }}>
          <SectionHeader
            eyebrow="Integrations"
            title="Works with the tools you already use"
            sub="One import. Any framework."
          />
        </AnimEl>

        <AnimEl delay={1}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.875rem', justifyContent: 'center', marginBottom: '2.5rem' }}>
            {INTEGRATIONS.map(({ emoji, name }) => (
              <div key={name} style={{
                display: 'flex', alignItems: 'center', gap: '0.5rem',
                background: 'var(--color-surface)', border: '1px solid var(--color-border)',
                borderRadius: 'var(--radius-full)', padding: '0.5rem 1.125rem',
                fontSize: '0.875rem', fontWeight: 500, transition: 'border-color 0.15s',
              }}
                onMouseEnter={e => e.currentTarget.style.borderColor = 'rgba(99,102,241,0.35)'}
                onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--color-border)'}
              >
                <span style={{ fontSize: '1rem' }}>{emoji}</span>
                <span style={{ color: 'var(--color-text)' }}>{name}</span>
              </div>
            ))}
          </div>
        </AnimEl>

        <AnimEl delay={2} style={{ textAlign: 'center' }}>
          <a href="#/integrations" onClick={e => { e.preventDefault(); navigate('/integrations'); }}
            style={{ color: 'var(--color-brand-400)', fontSize: '0.9375rem', fontWeight: 600, textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: '0.375rem' }}
            onMouseEnter={e => e.currentTarget.style.textDecoration = 'underline'}
            onMouseLeave={e => e.currentTarget.style.textDecoration = 'none'}
          >
            See all integrations <IcoArrowRight size={15} />
          </a>
        </AnimEl>
      </div>
    </section>
  );
}

Object.assign(window, { FlowDiagram, HowItWorksSection, FeatureGridSection, IntegrationsSection });
