// pages/features.jsx

const TOKEN_CODE = `vela aegis-generate-token \\
  --allow-file /tmp \\
  --allow-file /data/uploads \\
  --allow-network false \\
  --allow-syscall read \\
  --max-memory-mb 256 \\
  --max-timeout-ms 30000 \\
  --expires-in-seconds 3600`;

const POLICY_CODE = `# policy.yaml
deny_patterns:
  - "rm -rf"
  - "curl\\\\s+https?://"
  - "wget"
  - "chmod.*777"
  - "nc\\\\s+-"   # netcat

require_approval_for:
  - pattern: "sudo"
    reason: "privilege escalation requires human review"
  - pattern: "pip install"
    reason: "package installation must be pre-approved"

max_timeout_ms: 15000`;

const ALERT_CODE = `{
  "execution_id": "a1b2c3d4",
  "alerts": [
    {
      "severity": "HIGH",
      "rule_id": "sensitive_file_access",
      "description": "Process attempted to access /etc/shadow"
    },
    {
      "severity": "CRITICAL",
      "rule_id": "syscall_rate_spike",
      "description": "Syscall rate exceeded 847/s (limit: 500/s)"
    }
  ]
}`;

const TELEMETRY_CODE = `{"record":{
  "execution_id":"a1b2c3",
  "timestamp_ms":1748649600000,
  "command":["python3","-c","..."],
  "exit_code":0,
  "duration_ms":187,
  "events":[
    "RequestReceived",
    "TokenValidated",
    "PolicyChecked",
    "VMAssigned",
    "CommandFinished"
  ],
  "memory_consumed_mb":42
},"degraded_policy":false,"alerts":[]}`;

const API_ENDPOINTS = [
  { method: 'POST', path: '/execute',        desc: 'Submit code for execution' },
  { method: 'GET',  path: '/executions',     desc: 'List recent executions' },
  { method: 'GET',  path: '/executions/:id', desc: 'Get execution details + telemetry' },
  { method: 'GET',  path: '/health',         desc: 'Health check with execution counters' },
  { method: 'GET',  path: '/metrics',        desc: 'Prometheus metrics (text format)' },
];

const METHOD_COLORS = { POST: 'var(--color-green)', GET: 'var(--color-blue)', DELETE: 'var(--color-red)' };

function FeatureSection({ flip, badge, icon: Icon, title, children, right }) {
  return (
    <section style={{ padding: '6rem 0', borderBottom: '1px solid var(--color-border)' }}>
      <div className="container">
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))',
          gap: '4rem', alignItems: 'center',
        }}>
          {/* Text side */}
          <AnimEl style={{ order: flip ? 2 : 1 }}>
            <span className="badge badge-brand" style={{ marginBottom: '1.25rem' }}>
              {Icon && <Icon size={12} style={{ marginRight: '0.3rem' }} />}{badge}
            </span>
            <h2 style={{ fontSize: 'clamp(1.5rem, 3.5vw, 2rem)', fontWeight: 700, lineHeight: 1.2, marginBottom: '1.25rem', letterSpacing: '-0.02em' }}>{title}</h2>
            {children}
          </AnimEl>

          {/* Visual side */}
          <AnimEl delay={1} style={{ order: flip ? 1 : 2 }}>
            {right}
          </AnimEl>
        </div>
      </div>
    </section>
  );
}

function FeaturesPage() {
  useSEO("Features — Vela Runtime", "Explore the isolation and security features of Vela.");
  return (
    <div style={{ paddingTop: '64px', minHeight: '100vh', background: 'var(--color-bg)' }}>
      {/* Hero */}
      <div style={{ padding: '5rem 0 4rem', textAlign: 'center' }} className="bg-hero-glow bg-grid">
        <div className="container">
          <AnimEl>
            <span className="badge badge-brand" style={{ marginBottom: '1.25rem' }}>Features</span>
            <h1 style={{ fontSize: 'clamp(2rem, 5vw, 3rem)', fontWeight: 800, letterSpacing: '-0.03em', marginBottom: '1rem' }}>
              Every feature, explained
            </h1>
            <p style={{ color: 'var(--color-muted)', fontSize: '1.125rem', maxWidth: '500px', margin: '0 auto' }}>
              Vela is not a black box. Here's exactly what it does and why it matters.
            </p>
          </AnimEl>
        </div>
      </div>

      {/* Section 1 — Firecracker */}
      <FeatureSection badge="Isolation" icon={IcoShield} title="Firecracker micro-VM isolation" flip={false}
        right={
          <div style={{ display: 'flex', flexDirection: 'column', gap: '0.875rem' }}>
            {[
              { label: 'p50 latency (warmed pool)', value: '~150ms', ok: true },
              { label: 'Cold start', value: '~900ms', ok: null },
              { label: 'Leaks between executions', value: '0', ok: true },
              { label: 'Shared host kernel', value: 'Never', ok: true },
              { label: 'KVM hardware isolation', value: 'Yes', ok: true },
            ].map(({ label, value, ok }) => (
              <div key={label} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-md)', padding: '0.875rem 1.25rem' }}>
                <span style={{ color: 'var(--color-muted)', fontSize: '0.875rem' }}>{label}</span>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: '0.875rem', fontWeight: 700, color: ok === true ? 'var(--color-green)' : ok === false ? 'var(--color-red)' : 'var(--color-text)' }}>{value}</span>
              </div>
            ))}
          </div>
        }>
        <p style={{ color: 'var(--color-muted)', lineHeight: 1.8, marginBottom: '1rem' }}>
          Vela runs every execution in a fresh Firecracker micro-VM — the same technology that powers AWS Lambda and Fargate. Unlike Docker, Firecracker VMs provide <strong style={{ color: 'var(--color-text)' }}>hardware-level isolation through KVM</strong>. Your host kernel is never shared with untrusted code.
        </p>
        <p style={{ color: 'var(--color-muted)', lineHeight: 1.8 }}>
          Pre-warmed VM pools amortize startup overhead. Configure <code style={{ fontFamily: 'var(--font-mono)', background: 'var(--color-surface)', padding: '0.1em 0.35em', borderRadius: '3px', color: 'var(--color-brand-400)', fontSize: '0.85em', border: '1px solid var(--color-border)' }}>--pool-size 4</code> and p50 drops to ~150ms. When execution finishes, the VM is destroyed — nothing persists between runs.
        </p>
      </FeatureSection>

      {/* Section 2 — Tokens */}
      <FeatureSection badge="Authorization" icon={IcoKey} title="HMAC-SHA256 capability tokens" flip={true}
        right={<CodeBlock code={TOKEN_CODE} lang="bash" filename="generate-token.sh" />}>
        <p style={{ color: 'var(--color-muted)', lineHeight: 1.8, marginBottom: '1rem' }}>
          Capability tokens are HMAC-SHA256 signed JSON payloads that declare exactly what a caller is permitted to do. The daemon verifies the signature before executing anything.
        </p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '0.625rem' }}>
          {['Filesystem paths — exact directory allowlist', 'Network access — boolean on/off', 'Allowed syscalls — per-execution allowlist', 'Memory limit — hard cap in MB', 'Timeout — hard cap in milliseconds', 'Expiry — Unix timestamp; expired tokens rejected'].map(f => (
            <div key={f} style={{ display: 'flex', gap: '0.5rem', alignItems: 'flex-start', fontSize: '0.875rem', color: 'var(--color-muted)' }}>
              <IcoCheck size={14} style={{ color: 'var(--color-brand-400)', flexShrink: 0, marginTop: 2 }} />{f}
            </div>
          ))}
        </div>
      </FeatureSection>

      {/* Section 3 — Policy engine */}
      <FeatureSection badge="Policy" icon={IcoScroll} title="Policy engine" flip={false}
        right={<CodeBlock code={POLICY_CODE} lang="yaml" filename="policy.yaml" />}>
        <p style={{ color: 'var(--color-muted)', lineHeight: 1.8, marginBottom: '1rem' }}>
          Define what's allowed at the organization level — not just per-token. Vela compiles YAML rules at startup into pre-compiled regexes for zero-overhead enforcement.
        </p>
        <p style={{ color: 'var(--color-muted)', lineHeight: 1.8 }}>
          Three decision types: <strong style={{ color: 'var(--color-text)' }}>Allow</strong> (proceed), <strong style={{ color: 'var(--color-text)' }}>Deny</strong> (reject with reason), <strong style={{ color: 'var(--color-text)' }}>RequireApproval</strong>. Connect an external policy service with <code style={{ fontFamily: 'var(--font-mono)', fontSize: '0.85em', color: 'var(--color-brand-400)' }}>--policy-endpoint</code>. Vela fails closed if the endpoint is unreachable.
        </p>
      </FeatureSection>

      {/* Section 4 — Intrusion detection */}
      <FeatureSection badge="Detection" icon={IcoAlertTriangle} title="Intrusion detection" flip={true}
        right={<CodeBlock code={ALERT_CODE} lang="json" filename="alert output" />}>
        <p style={{ color: 'var(--color-muted)', lineHeight: 1.8, marginBottom: '1rem' }}>
          Vela watches every execution for anomalous behavior and attaches alerts to the telemetry record. No configuration required — rules are enabled by default.
        </p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '0.625rem' }}>
          {[
            'Sensitive file access (/etc/shadow, /root/.ssh/*)',
            'Syscall rate spike (>500/s signals exploit)',
            'Private network access (RFC-1918 addresses)',
            'Custom pattern matching (intrusion_rules.toml)',
          ].map(f => (
            <div key={f} style={{ display: 'flex', gap: '0.5rem', alignItems: 'flex-start', fontSize: '0.875rem', color: 'var(--color-muted)' }}>
              <IcoAlertTriangle size={13} style={{ color: 'var(--color-amber)', flexShrink: 0, marginTop: 2 }} />{f}
            </div>
          ))}
        </div>
      </FeatureSection>

      {/* Section 5 — Telemetry */}
      <FeatureSection badge="Observability" icon={IcoActivity} title="Telemetry &amp; audit trail" flip={false}
        right={<CodeBlock code={TELEMETRY_CODE} lang="json" filename="telemetry.jsonl (one line)" />}>
        <p style={{ color: 'var(--color-muted)', lineHeight: 1.8, marginBottom: '1rem' }}>
          Every execution produces a structured telemetry record appended to an append-only JSONL log. Events trace the full lifecycle from request to result.
        </p>
        <p style={{ color: 'var(--color-muted)', lineHeight: 1.8 }}>
          Access three ways: <strong style={{ color: 'var(--color-text)' }}>JSONL log file</strong> (grep/jq/SIEM), <strong style={{ color: 'var(--color-text)' }}>live stream socket</strong> (real-time events), or <code style={{ fontFamily: 'var(--font-mono)', fontSize: '0.85em', color: 'var(--color-brand-400)' }}>vela inspect &lt;id&gt;</code> (CLI lookup). The audit UI visualizes the log with filtering and alert badges.
        </p>
      </FeatureSection>

      {/* Section 6 — Cloud API */}
      <FeatureSection badge="Cloud" icon={IcoGlobe} title="Cloud REST API" flip={true}
        right={
          <div style={{ border: '1px solid var(--color-border)', borderRadius: 'var(--radius-lg)', overflow: 'hidden' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.875rem' }}>
              <thead>
                <tr style={{ background: 'var(--color-surface-2)' }}>
                  <th style={{ padding: '0.75rem 1rem', textAlign: 'left', color: 'var(--color-muted)', fontWeight: 600, fontSize: '0.75rem', textTransform: 'uppercase', letterSpacing: '0.05em', borderBottom: '1px solid var(--color-border)' }}>Method</th>
                  <th style={{ padding: '0.75rem 1rem', textAlign: 'left', color: 'var(--color-muted)', fontWeight: 600, fontSize: '0.75rem', textTransform: 'uppercase', letterSpacing: '0.05em', borderBottom: '1px solid var(--color-border)' }}>Path</th>
                </tr>
              </thead>
              <tbody>
                {API_ENDPOINTS.map((ep, i) => (
                  <tr key={ep.path} style={{ borderBottom: i < API_ENDPOINTS.length - 1 ? '1px solid var(--color-border)' : 'none' }}>
                    <td style={{ padding: '0.75rem 1rem' }}>
                      <span style={{ fontFamily: 'var(--font-mono)', fontSize: '0.75rem', fontWeight: 700, color: METHOD_COLORS[ep.method] || 'var(--color-muted)', background: `${METHOD_COLORS[ep.method] || 'var(--color-muted)'}15`, padding: '0.15em 0.5em', borderRadius: '3px' }}>{ep.method}</span>
                    </td>
                    <td style={{ padding: '0.75rem 1rem' }}>
                      <code style={{ fontFamily: 'var(--font-mono)', fontSize: '0.8rem', color: 'var(--color-text)' }}>{ep.path}</code>
                      <div style={{ color: 'var(--color-muted)', fontSize: '0.75rem', marginTop: '0.15rem' }}>{ep.desc}</div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        }>
        <p style={{ color: 'var(--color-muted)', lineHeight: 1.8, marginBottom: '1rem' }}>
          Run the cloud API server with a single command and a YAML config. SQLite-backed execution store, queue-based worker pool, and API key authentication included.
        </p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '0.625rem' }}>
          {['Webhook notifications on completion', 'Per-API-key rate limiting (no Redis)', 'Execution labels for filtering', 'JavaScript/Node.js execution', 'Prometheus /metrics endpoint (7 counters)'].map(f => (
            <div key={f} style={{ display: 'flex', gap: '0.5rem', fontSize: '0.875rem', color: 'var(--color-muted)' }}>
              <IcoCheck size={14} style={{ color: 'var(--color-green)', flexShrink: 0, marginTop: 2 }} />{f}
            </div>
          ))}
        </div>
      </FeatureSection>
    </div>
  );
}

Object.assign(window, { FeaturesPage });
