// Features grid, Use cases, Code playground, Pricing, Quote, Compliance, Final CTA, Footer
const { useState: uS2, useEffect: uE2 } = React;

function Features() {
  const items = [
    { icon: <Icon.Layers />, title: 'Quantum-safe key exchange', body: 'Mint an ML-KEM-768 keypair and exchange a shared secret in one call. Use the raw 32-byte secret or a HKDF-derived AES-256 key — your choice.', detail: 'Encapsulate, decapsulate, and derive endpoints map cleanly onto the NIST FIPS 203 standard. Drop in wherever your application needs a forward-secret session key.' },
    { icon: <Icon.Sig />, title: 'Long-lived digital signatures', body: 'Sign transactions, contracts, or audit events with ML-DSA-65 today. Verifiable decades from now — no key migration when the classical floor falls.', detail: 'Stateful signing with managed keys, and a stateless verify endpoint your downstream consumers can call without an account. Batch signing keeps high-volume pipelines fast.' },
    { icon: <Icon.Key />, title: 'Encrypted vault, by tenant', body: 'Every secret is sealed with AES-256-GCM and bound to the row that owns it. A leaked database snapshot is useless without the master key, and you can prove tenant isolation to an auditor in seconds.', detail: 'Identity-bound AEAD means swapping ciphertext between rows always fails. Master keys live in operator-only storage and never touch a customer payload.' },
    { icon: <Icon.Refresh />, title: 'Always-on audit trail', body: 'Every create, rotate, delete, and webhook change is recorded with actor, target, outcome, and metadata. Hand your auditor a SQL query and the evidence answers itself.', detail: 'Audit writes are bounded so the request path always stays fast. The trail is immutable from the API side — append-only and timestamped.' },
    { icon: <Icon.Shield />, title: 'Webhooks you can trust', body: 'Subscribe to vault events and we deliver them signed, retried, and SSRF-guarded. Internal IPs, cloud metadata services, and DNS rebinding attacks are blocked before we ever connect.', detail: 'Each delivery carries an HMAC-SHA256 signature over the payload. Failed deliveries retry with backoff and are visible in the dashboard for triage.' },
    { icon: <Icon.Bolt />, title: 'Hardened runtime', body: 'The API process refuses to be debugged, dumped, or attached. Master-key bytes never reach disk or a core file — guaranteed by kernel-level hardening, verified with real adversarial probes.', detail: 'Memory-safe Rust top to bottom, with the only unsafe code isolated in a single audited hardening crate.' },
  ];
  return (
    <section className="section" id="features">
      <div className="shell">
        <div className="section-header">
          <span className="eyebrow">Core platform</span>
          <h2>Six capabilities. Built to outlast classical cryptography.</h2>
        </div>
        <div className="grid grid-3">
          {items.map((it, i) => (
            <div key={i} className="feature">
              <div className="feature-icon">{it.icon}</div>
              <h3>{it.title}</h3>
              <p>{it.body}</p>
              <div className="feature-detail">{it.detail}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function UseCases() {
  const items = [
    { num: '01', icon: <Icon.Globe />, title: 'Service-to-service envelopes', body: 'Wrap data keys with quantum-safe key exchange between microservices. Producers get a public key; consumers decapsulate locally. api4pqc handles the keys; your payload stays in your perimeter.' },
    { num: '02', icon: <Icon.Card />, title: 'Long-lived signed records', body: 'Sign transactions, contracts, or audit events with ML-DSA-65 today. The signature stays verifiable as long as you keep the public key — across regulator audits, decades of retention, and the eventual quantum transition.' },
    { num: '03', icon: <Icon.User />, title: 'Document signing for regulated industries', body: 'Defence, healthcare, and finance teams that need NIST-finalized signing without standing up their own HSM. Plug api4pqc in, sign through one API, satisfy your compliance team.' },
    { num: '04', icon: <Icon.Db />, title: 'Harvest-now-decrypt-later defence', body: 'Wrap classical TLS-protected data in a quantum-safe envelope at rest. Even if today’s transport key is captured and stored, the underlying data stays sealed against tomorrow’s quantum decryptor.' },
  ];
  return (
    <section className="section">
      <div className="shell">
        <div className="section-header">
          <span className="eyebrow">Use cases</span>
          <h2>Where teams put api4pqc to work.</h2>
        </div>
        <div>
          {items.map((it, i) => (
            <div key={i} className="use-case">
              <div style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
                <div style={{ width: 40, height: 40, borderRadius: 10, border: '1px solid var(--line)', display: 'grid', placeItems: 'center', color: 'var(--accent-deep)', background: 'var(--accent-soft)', flexShrink: 0 }}>
                  {it.icon}
                </div>
                <div>
                  <div className="use-case-num">{it.num}</div>
                  <h3>{it.title}</h3>
                </div>
              </div>
              <p>{it.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Playground() {
  const [endpoint, setEndpoint] = uS2('encrypt');
  const [responseOpen, setResponseOpen] = uS2(false);
  // Tabs map onto real endpoints: KEM encapsulate, sign, verify.
  const endpoints = [
    { id: 'encrypt', label: 'Encapsulate', path: '/v1/kem/encapsulate', icon: <Icon.Lock size={13} /> },
    { id: 'sign',    label: 'Sign',        path: '/v1/sign',            icon: <Icon.Sig size={13} /> },
    { id: 'verify',  label: 'Verify',      path: '/v1/verify',          icon: <Icon.Check size={13} /> },
  ];
  uE2(() => { setResponseOpen(false); }, [endpoint]);

  return (
    <section className="section dark">
      <div className="shell">
        <div className="section-header">
          <span className="eyebrow">Developer experience</span>
          <h2 style={{ color: '#f4f7fb' }}>Real endpoints. Real responses. Any language.</h2>
          <p className="lede">Inspect the request and response shape, copy the call, drop in your API key, and ship — in any language that can speak HTTP.</p>
        </div>

        <div style={{ display: 'flex', gap: 8, marginBottom: 20, flexWrap: 'wrap' }}>
          {endpoints.map(e => (
            <button
              key={e.id}
              onClick={() => setEndpoint(e.id)}
              style={{
                display: 'inline-flex', gap: 8, alignItems: 'center',
                padding: '10px 16px',
                fontFamily: 'var(--mono)', fontSize: 12.5,
                borderRadius: 8,
                border: '1px solid ' + (endpoint === e.id ? 'var(--accent-2)' : '#1f3149'),
                background: endpoint === e.id ? 'rgba(6, 182, 196, 0.08)' : 'transparent',
                color: endpoint === e.id ? 'var(--accent-2)' : '#8b97a8',
                transition: 'all 160ms',
              }}
            >
              {e.icon}
              <span style={{ color: endpoint === e.id ? 'var(--accent-2)' : '#6b7a90' }}>POST</span>
              {e.path}
            </button>
          ))}
        </div>

        <CodeWindow
          samples={CODE_SAMPLES.playground[endpoint]}
          defaultLang="curl"
          langs={['curl', 'js', 'py', 'go']}
          runnable
          onRun={() => setResponseOpen(true)}
          response={{ endpoint, body: PLAYGROUND_RESPONSES[endpoint], duration: 'sandbox' }}
          responseOpen={responseOpen}
        />
      </div>
    </section>
  );
}

function Pricing() {
  const [annual, setAnnual] = uS2(true);
  const [thumbStyle, setThumbStyle] = uS2({ left: 4, width: 80 });
  const monthlyRef = uR();
  const annualRef = uR();
  uE2(() => {
    const target = annual ? annualRef.current : monthlyRef.current;
    if (target) {
      setThumbStyle({ left: target.offsetLeft, width: target.offsetWidth });
    }
  }, [annual]);

  const tiers = [
    {
      name: 'Free',
      price: '$0',
      unit: '/forever',
      desc: 'Build, prototype, and validate.',
      feats: ['60 requests / minute', 'ML-KEM-768 + ML-DSA-65', 'Up to 50 vault keys', '1 webhook subscription', 'Email support'],
      cta: 'Start free',
      featured: false,
    },
    {
      name: 'Starter',
      price: annual ? '$80' : '$99',
      unit: '/month',
      desc: 'For steady production workloads.',
      feats: ['600 requests / minute', 'Up to 500 vault keys', '10 webhook subscriptions', 'Audit trail SQL access', 'Master-key rotation runbook', 'Email + chat support'],
      cta: 'Talk to us',
      featured: true,
      savings: annual ? 'Save 20% annually' : null,
    },
    {
      name: 'Growth',
      price: 'Custom',
      unit: '',
      desc: 'For high-volume and regulated rollouts.',
      feats: ['6,000+ requests / minute', 'Per-tier vault key cap on request', 'Unlimited webhooks', 'Priority rotation support', 'Compliance evidence package', 'Dedicated Slack channel'],
      cta: 'Contact sales',
      featured: false,
    },
  ];

  return (
    <section className="section muted" id="pricing">
      <div className="shell">
        <div className="section-header center">
          <span className="eyebrow">Pricing</span>
          <h2>Predictable plans. Scale without surprises.</h2>
          <p className="lede" style={{ textAlign: 'center' }}>Pick a plan that fits your throughput. No per-call meters, no infrastructure markups — just a clean monthly subscription with the headroom your team actually uses.</p>
          <div style={{ marginTop: 24 }}>
            <div className="toggle-pill">
              <div className="toggle-thumb" style={thumbStyle} />
              <button ref={monthlyRef} onClick={() => setAnnual(false)} className={!annual ? 'active' : ''}>Monthly</button>
              <button ref={annualRef} onClick={() => setAnnual(true)} className={annual ? 'active' : ''}>
                Annual <span className="save-badge">−20%</span>
              </button>
            </div>
          </div>
        </div>
        <div className="grid grid-3">
          {tiers.map((t, i) => (
            <div key={i} className={`price-card ${t.featured ? 'featured' : ''}`}>
              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
                  <span style={{ fontSize: 13, fontFamily: 'var(--mono)', letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>{t.name}</span>
                  {t.savings && <span style={{ fontSize: 11, fontFamily: 'var(--mono)', color: 'var(--accent-deep)', background: 'var(--accent-soft)', padding: '3px 8px', borderRadius: 4 }}>{t.savings}</span>}
                </div>
                <div className="price-amount">
                  {t.price}<span className="unit">{t.unit}</span>
                </div>
                <p style={{ color: 'var(--ink-3)', fontSize: 14, marginTop: 8 }}>{t.desc}</p>
              </div>
              <a href="#" className={`btn ${t.featured ? 'btn-primary' : 'btn-ghost'}`} style={{ justifyContent: 'center' }}>
                {t.cta} <Icon.Arrow />
              </a>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12, paddingTop: 8, borderTop: '1px solid var(--line)' }}>
                {t.feats.map((f, j) => (
                  <div key={j} className="price-feat">
                    <Icon.Check size={14} />
                    <span>{f}</span>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Quote() {
  return (
    <section className="section">
      <div className="shell" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80, alignItems: 'center' }}>
        <div>
          <span className="eyebrow">Why api4pqc</span>
          <p className="quote" style={{ marginTop: 24 }}>
            "Post-quantum cryptography should be a checkbox, not a six-month engineering project. api4pqc gives you the primitives, the audit trail, and the rotation story — all behind one API."
          </p>
          <div className="quote-attr">
            <div className="quote-avatar">VS</div>
            <div>
              <div style={{ fontWeight: 500, color: 'var(--ink)' }}>Vikas Swaminathan, founder</div>
              <div style={{ color: 'var(--ink-4)', fontSize: 13 }}>api4pqc.com</div>
            </div>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          <Stat val="ML-KEM-768" label="NIST FIPS 203 ready" />
          <Stat val="ML-DSA-65"  label="NIST FIPS 204 ready" />
          <Stat val="0 sec"      label="Downtime on rotation" />
          <Stat val="100%"       label="State changes audited" />
        </div>
      </div>
    </section>
  );
}

function Stat({ val, label }) {
  return (
    <div style={{ border: '1px solid var(--line)', borderRadius: 12, padding: 24, background: 'white' }}>
      <div style={{ fontSize: 32, fontWeight: 450, letterSpacing: '-0.025em', color: 'var(--ink)' }}>{val}</div>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-4)', marginTop: 6 }}>{label}</div>
    </div>
  );
}

function Compliance() {
  const items = [
    { label: 'NIST',     name: 'FIPS 203 + 204',         body: 'ML-KEM-768 and ML-DSA-65 live across the API — interoperable with any standards-conformant client.' },
    { label: 'AEAD',     name: 'Encryption at rest',     body: 'Every secret is sealed with identity-bound AES-256-GCM. A stolen snapshot is useless without the master key.' },
    { label: 'Audit',    name: 'Immutable trail',        body: 'Every state change is logged with actor, target, outcome, and metadata — your evidence package, ready on demand.' },
    { label: 'Runtime',  name: 'Hardened by default',    body: 'The API process refuses debugger attaches, memory dumps, and core files. Master keys never leave operator-controlled memory.' },
  ];
  return (
    <section className="section muted">
      <div className="shell">
        <div className="section-header">
          <span className="eyebrow">Security & compliance</span>
          <h2>Built for regulated workloads.</h2>
          <p className="lede">NIST-finalized post-quantum algorithms, identity-bound encryption at rest, an immutable audit trail, and a hardened runtime — every layer designed so your security and compliance teams say yes on the first review.</p>
        </div>
        <div className="badge-row">
          {items.map((it, i) => (
            <div key={i} className="badge">
              <span className="label">{it.label}</span>
              <h4>{it.name}</h4>
              <p>{it.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function FinalCTA() {
  return (
    <section className="cta-final">
      <LatticeBackgroundDark />
      <div className="shell" style={{ position: 'relative', zIndex: 2 }}>
        <span className="eyebrow" style={{ color: 'var(--accent-2)' }}>
          <span style={{ background: 'var(--accent-2)' }} />
          Get ahead of the migration
        </span>
        <h2 style={{ marginTop: 18 }}>Mint your first<br />post-quantum key today.</h2>
        <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 36, flexWrap: 'wrap' }}>
          <a href="mailto:hello@api4pqc.com?subject=api4pqc%20-%20sandbox%20access" className="btn btn-accent" style={{ background: 'white', color: 'var(--ink)' }}>
            Request sandbox <Icon.Arrow />
          </a>
          <a href="mailto:hello@api4pqc.com?subject=api4pqc%20-%20architect%20call" className="btn btn-ghost" style={{ borderColor: '#2a3b52', color: '#e8eef5' }}>
            Talk to an architect
          </a>
        </div>
        <div style={{ marginTop: 28, fontFamily: 'var(--mono)', fontSize: 12, color: '#6b7a90' }}>
          Sandbox keys provisioned within one business day
        </div>
      </div>
    </section>
  );
}

function LatticeBackgroundDark() {
  return (
    <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.4, pointerEvents: 'none' }} viewBox="0 0 1280 600" preserveAspectRatio="xMidYMid slice">
      <defs>
        <radialGradient id="darkDot" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#06b6c4" stopOpacity="0.7" />
          <stop offset="100%" stopColor="#06b6c4" stopOpacity="0" />
        </radialGradient>
      </defs>
      {Array.from({ length: 80 }).map((_, i) => {
        const x = (i * 137) % 1280;
        const y = ((i * 89) % 540) + 30;
        const delay = (i * 80) % 4000;
        return (
          <circle key={i} cx={x} cy={y} r="2" fill="#06b6c4" opacity="0.4">
            <animate attributeName="r" values="1;5;1" dur="3.6s" begin={`${delay}ms`} repeatCount="indefinite" />
            <animate attributeName="opacity" values="0.1;0.6;0.1" dur="3.6s" begin={`${delay}ms`} repeatCount="indefinite" />
          </circle>
        );
      })}
    </svg>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div className="shell" style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', gap: 48 }}>
        <div>
          <a href="/" className="brand" style={{ color: 'white' }} aria-label="api4pqc home">
            <span className="brand-mark" style={{ background: 'white', color: 'var(--ink)' }}><Icon.Logo size={16} /></span>
            api4pqc
            <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: '#6b7a90', fontWeight: 400, marginLeft: 2, letterSpacing: '0.04em' }}>.com</span>
          </a>
          <p style={{ marginTop: 16, fontSize: 13.5, color: '#8b97a8', maxWidth: '36ch', lineHeight: 1.6 }}>
            Quantum-safe keys, delivered as a service. Mint, rotate, sign, verify — auditable on every state change.
          </p>
          <div style={{ marginTop: 24, display: 'flex', gap: 14 }}>
            <a href="https://github.com/vikasswaminh/PQCSAAS" style={{ color: '#8b97a8' }} aria-label="GitHub"><Icon.Github size={18} /></a>
          </div>
        </div>
        <div>
          <h4>Platform</h4>
          <ul>
            <li><a href="#features">KEM (ML-KEM-768)</a></li>
            <li><a href="#features">Signing (ML-DSA-65)</a></li>
            <li><a href="#features">Vault & rotation</a></li>
            <li><a href="#features">Webhooks</a></li>
          </ul>
        </div>
        <div>
          <h4>Developers</h4>
          <ul>
            <li><a href="https://docs.api4pqc.com">Documentation</a></li>
            <li><a href="https://docs.api4pqc.com/quickstart">Quickstart</a></li>
            <li><a href="https://docs.api4pqc.com/api">API reference</a></li>
            <li><a href="https://status.api4pqc.com">Status</a></li>
          </ul>
        </div>
        <div>
          <h4>Trust</h4>
          <ul>
            <li><a href="mailto:security@api4pqc.com">Security contact</a></li>
            <li><a href="/.well-known/security.txt">security.txt</a></li>
            <li><a href="mailto:security@api4pqc.com?subject=api4pqc%20-%20responsible%20disclosure">Responsible disclosure</a></li>
            <li><a href="mailto:hello@api4pqc.com">Contact</a></li>
          </ul>
        </div>
      </div>
      <div className="shell">
        <div className="footer-bottom">
          <span>© 2026 api4pqc.com</span>
          <span>NIST FIPS 203 + 204 · Audited by design</span>
        </div>
      </div>
    </footer>
  );
}

window.Features = Features;
window.UseCases = UseCases;
window.Playground = Playground;
window.Pricing = Pricing;
window.Quote = Quote;
window.Compliance = Compliance;
window.FinalCTA = FinalCTA;
window.Footer = Footer;
