/* Prism design system — AI Architecture Blueprint lead-magnet page */
const { useState: useS2 } = React;

/* Override Logo to use the same PNG asset as the rest of insideprism.com */
function Logo({ size = 28, showWord = true, tone = 'ink' }) {
  const wordColor = tone === 'light' ? '#fff' : 'var(--ink-900)';
  const imgH = size * 2;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: size * 0.34 }}>
      <img src="/assets/logo.png" height={imgH} alt="" aria-hidden="true"
        style={{ display: 'block', filter: tone === 'light'
          ? 'brightness(0) invert(1) opacity(0.9)'
          : 'drop-shadow(1px 0 0 rgba(180,155,255,1)) drop-shadow(-1px 0 0 rgba(110,215,230,1)) drop-shadow(0 1px 0 rgba(255,186,71,1)) drop-shadow(0 -1px 0 rgba(180,155,255,1)) drop-shadow(1px 1px 0 rgba(110,215,230,0.9)) drop-shadow(-1px -1px 0 rgba(255,186,71,0.9)) drop-shadow(1px -1px 0 rgba(180,155,255,0.9)) drop-shadow(-1px 1px 0 rgba(110,215,230,0.9))'
        }} />
      {showWord && <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: size * 0.74, letterSpacing: '-0.03em', color: wordColor }}>Prism</span>}
    </span>
  );
}

/* Custom checkbox — replaces the native browser checkbox with a themed one */
function PrismCheckbox({ checked, onChange, children }) {
  const [h, setH] = useS2(false);
  return (
    <label
      onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ display: 'flex', alignItems: 'flex-start', gap: 10, cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--ink-500)', lineHeight: 1.45 }}>
      <span style={{ position: 'relative', flexShrink: 0, width: 19, height: 19, marginTop: 1 }}>
        <input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked)}
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0, cursor: 'pointer', margin: 0 }} />
        <span aria-hidden="true" style={{
          position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
          borderRadius: 6, border: `1.5px solid ${checked ? 'var(--accent)' : (h ? 'var(--ink-400)' : 'var(--line-strong)')}`,
          background: checked ? 'var(--accent)' : 'var(--surface)',
          boxShadow: checked ? '0 2px 8px rgba(91,91,240,0.30)' : 'none',
          transition: 'all var(--dur-base) var(--ease-out)',
        }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none"
            style={{ opacity: checked ? 1 : 0, transform: checked ? 'scale(1)' : 'scale(0.4)', transition: 'all var(--dur-base) var(--ease-out)' }}>
            <polyline points="20 6 9 17 4 12" stroke="#fff" strokeWidth="3.4" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </span>
      </span>
      <span>{children}</span>
    </label>
  );
}

const MAXW2 = 1140;
const container2 = { maxWidth: MAXW2, margin: '0 auto', padding: '0 clamp(20px,5vw,48px)' };

/* ---------------- Nav ---------------- */
function BlueprintNav() {
  return (
    <header style={{ position: 'fixed', top: 0, left: 0, right: 0, zIndex: 50 }}>
      <div style={{ ...container2, paddingTop: 16, paddingBottom: 16 }}>
        <nav style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
          background: 'var(--glass-fill-strong)', backdropFilter: 'blur(16px) saturate(140%)', WebkitBackdropFilter: 'blur(16px) saturate(140%)',
          border: '1px solid var(--glass-border)', borderRadius: 'var(--r-pill)', padding: '10px 16px 10px 22px', boxShadow: 'var(--shadow-sm)' }}>
          <a href="/" style={{ display: 'inline-flex', flexShrink: 0 }}><Logo size={26} /></a>
          <div style={{ display: 'flex', alignItems: 'center', gap: 20, minWidth: 0 }}>
            <a href="/tools/" className="veles-nav-link" style={{ fontFamily: 'var(--font-mono)', fontSize: 12.5, fontWeight: 500, color: 'var(--ink-500)', textDecoration: 'none', flexShrink: 0 }}>Tools</a>
            <a href="/vault/" className="veles-nav-link" style={{ fontFamily: 'var(--font-mono)', fontSize: 12.5, fontWeight: 500, color: 'var(--ink-500)', textDecoration: 'none', flexShrink: 0 }}>Vault</a>
            <Badge variant="accent" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '100%' }}>AI Architecture Blueprint</Badge>
          </div>
        </nav>
      </div>
    </header>
  );
}

/* ---------------- Email form (posts to Beehiiv + tags the lead) ---------------- */
function BlueprintEmailForm({ onDone }) {
  const [email, setEmail] = useS2(''), [wantsNewsletter, setWantsNewsletter] = useS2(true), [state, setState] = useS2('idle');
  const valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

  const submit = async (e) => {
    e.preventDefault();
    if (!valid) { setState('error'); return; }
    setState('loading');
    try {
      await fetch('/api/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      await fetch('/api/tag-subscriber', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, tag: wantsNewsletter ? 'veles-blueprint-newsletter' : 'veles-blueprint-only' }),
      });
    } catch (err) { /* silent fail — still move the reader forward */ }
    setState('done');
    onDone && onDone(email);
  };

  if (state === 'done') {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, background: 'var(--positive-tint)', borderRadius: 'var(--r-pill)', padding: '14px 22px', fontFamily: 'var(--font-body)', color: 'var(--positive)', fontWeight: 600, fontSize: 15 }}>
        <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--positive)', color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, flex: 'none' }}>✓</span>
        Check your inbox — the Blueprint is on its way.
      </div>
    );
  }

  const err = state === 'error';
  return (
    <div>
      <form onSubmit={submit} style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'var(--surface)', borderRadius: 'var(--r-pill)', padding: '7px 7px 7px 20px', border: `1px solid ${err ? 'var(--negative)' : 'var(--line)'}`, boxShadow: 'var(--shadow-md)' }}>
        <input type="email" value={email} onChange={(e) => { setEmail(e.target.value); if (err) setState('idle'); }} placeholder="you@company.com" required
          style={{ flex: 1, minWidth: 0, border: 'none', outline: 'none', background: 'transparent', fontFamily: 'var(--font-body)', fontSize: 16, color: 'var(--ink-800)' }} />
        <button type="submit" disabled={state === 'loading'} style={{ flex: 'none', border: 'none', borderRadius: 'var(--r-pill)', cursor: 'pointer', background: 'var(--ink-900)', color: '#fff', fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 15, padding: '12px 22px', whiteSpace: 'nowrap' }}>
          {state === 'loading' ? 'Sending…' : 'Get the Blueprint →'}
        </button>
      </form>
      <div style={{ marginTop: 14 }}>
        <PrismCheckbox checked={wantsNewsletter} onChange={setWantsNewsletter}>
          Also send me weekly insights on Sovereign AI &amp; infrastructure
        </PrismCheckbox>
      </div>
      <p style={{ margin: '10px 4px 0', fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.04em', color: err ? 'var(--negative)' : 'var(--ink-500)' }}>
        {err ? 'Please enter a valid email address.' : 'Free · one-time download · unsubscribe anytime'}
      </p>
    </div>
  );
}

/* ---------------- Hero ---------------- */
function BlueprintHero({ onSubscribed }) {
  return (
    <section style={{ position: 'relative', overflow: 'hidden', minHeight: '100vh', display: 'flex', alignItems: 'center' }}>
      <Mesh intensity={0.95} />
      <div aria-hidden="true" style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: 160, background: 'linear-gradient(to bottom, transparent, var(--paper))', zIndex: 2, pointerEvents: 'none' }} />
      <div style={{ ...container2, position: 'relative', zIndex: 1, paddingTop: 'clamp(120px,14vw,180px)', paddingBottom: 'clamp(72px,12vw,140px)', width: '100%' }}>
        <div style={{ maxWidth: 720 }}>
          <p className="prism-eyebrow" style={{ margin: '0 0 22px' }}>Free download · from the makers of Prism</p>
          <h1 style={{ margin: 0, fontFamily: "'Inter', sans-serif", fontWeight: 600, fontSize: 'clamp(2.6rem,5.6vw,4.4rem)', lineHeight: 1.02, letterSpacing: '-0.04em', fontFeatureSettings: '"ss01", "cv05", "cv11"', color: 'var(--ink-900)' }}>
            Build AI infrastructure that's yours — not a vendor's.
          </h1>
          <p style={{ margin: '24px 0 0', maxWidth: 560, fontFamily: 'var(--font-body)', fontSize: 18, lineHeight: 1.6, color: 'var(--ink-600)' }}>
            A practical blueprint for designing secure, sovereign AI systems: local LLMs, LangGraph orchestration, and the architecture decisions that keep your data off someone else's servers.
          </p>
          <div style={{ maxWidth: 480, margin: '34px 0 0' }}>
            <BlueprintEmailForm onDone={onSubscribed} />
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- What's inside ---------------- */
const B_GLYPHS = {
  privacy: (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" aria-hidden="true">
      <path d="M11 2 L19 5.5 V11 C19 15.5 15.5 18.7 11 20 C6.5 18.7 3 15.5 3 11 V5.5 Z" stroke="var(--ink-700)" strokeWidth="1.6" />
      <path d="M8 11 L10.2 13.2 L14.5 8.5" stroke="var(--accent)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  ),
  orchestration: (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" aria-hidden="true">
      <circle cx="5" cy="5" r="2.6" stroke="var(--ink-700)" strokeWidth="1.6" />
      <circle cx="17" cy="5" r="2.6" stroke="var(--ink-700)" strokeWidth="1.6" />
      <circle cx="11" cy="17" r="2.6" fill="var(--accent)" />
      <path d="M7.2 6.4 L10 15" stroke="var(--ink-400)" strokeWidth="1.4" />
      <path d="M14.8 6.4 L12 15" stroke="var(--ink-400)" strokeWidth="1.4" />
    </svg>
  ),
  security: (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" aria-hidden="true">
      <rect x="5" y="10" width="12" height="9" rx="2" stroke="var(--ink-700)" strokeWidth="1.6" />
      <path d="M8 10 V7 a3 3 0 016 0 v3" stroke="var(--ink-700)" strokeWidth="1.6" />
      <circle cx="11" cy="14.2" r="1.4" fill="var(--accent)" />
    </svg>
  ),
};

function BlueprintValueCard({ num, glyph, title, body, hue }) {
  const [h, setH] = useS2(false);
  return (
    <div onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ position: 'relative', overflow: 'hidden', minHeight: 260,
        background: 'var(--glass-fill-strong)', backdropFilter: 'blur(var(--glass-blur)) saturate(var(--glass-saturate))', WebkitBackdropFilter: 'blur(var(--glass-blur)) saturate(var(--glass-saturate))',
        border: '1px solid var(--glass-border)', borderRadius: 'var(--r-xl)', padding: 'var(--sp-7)',
        boxShadow: h ? 'var(--shadow-xl), var(--shadow-inset)' : 'var(--shadow-md), var(--shadow-inset)',
        transform: h ? 'translateY(-6px)' : 'none', transition: 'all var(--dur-base) var(--ease-out)' }}>
      <div aria-hidden="true" style={{ position: 'absolute', top: -70, right: -56, width: 200, height: 200, borderRadius: '50%', background: `radial-gradient(circle at center, ${hue} 0%, transparent 68%)`, filter: 'blur(26px)', opacity: h ? 1 : 0.6, pointerEvents: 'none' }} />
      <span aria-hidden="true" style={{ position: 'absolute', top: -14, right: 14, fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 110, lineHeight: 1, color: 'transparent', WebkitTextStroke: '1.2px rgba(10,11,13,0.07)', pointerEvents: 'none' }}>{num}</span>
      <div style={{ position: 'relative', width: 50, height: 50, borderRadius: 'var(--r-md)', display: 'grid', placeItems: 'center', background: 'var(--surface)', border: '1px solid var(--line)', boxShadow: 'var(--shadow-xs)' }}>{glyph}</div>
      <h3 style={{ position: 'relative', margin: '24px 0 10px', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 21, lineHeight: 1.15, letterSpacing: '-0.02em', color: 'var(--ink-900)' }}>{title}</h3>
      <p style={{ position: 'relative', margin: 0, fontFamily: 'var(--font-body)', fontSize: 15.5, lineHeight: 1.6, color: 'var(--ink-600)' }}>{body}</p>
    </div>
  );
}

function BlueprintContents() {
  const items = [
    ['01', B_GLYPHS.privacy, 'Run private, local LLMs', "How to keep inference on infrastructure you control — no data leaking to a third-party API.", 'var(--iris-lavender)'],
    ['02', B_GLYPHS.orchestration, 'Orchestrate with LangGraph', 'Patterns for wiring multi-step AI workflows that stay observable and debuggable in production.', 'var(--iris-sky)'],
    ['03', B_GLYPHS.security, 'Get the security tradeoffs right', "The architecture decisions most teams get wrong — and the ones that actually matter.", 'var(--iris-mint)'],
  ];
  return (
    <section style={{ ...container2, paddingTop: 'var(--section-y)', paddingBottom: 'var(--section-y)' }}>
      <div style={{ maxWidth: 620, marginBottom: 'clamp(36px,5vw,64px)' }}>
        <p className="prism-eyebrow" style={{ margin: '0 0 16px' }}>What's inside</p>
        <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 'clamp(2rem,3.4vw,3rem)', lineHeight: 1.08, letterSpacing: '-0.03em', color: 'var(--ink-900)' }}>
          Three decisions that make or break sovereign AI.
        </h2>
      </div>
      <div style={{ position: 'relative' }}>
        <div aria-hidden="true" className="prism-mesh" style={{ position: 'absolute', inset: '-12% -6%', zIndex: 0, opacity: 0.55, pointerEvents: 'none' }} />
        <div style={{ position: 'relative', zIndex: 1, display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(264px,1fr))', gap: 'clamp(16px,2.4vw,28px)' }}>
          {items.map((it) => <BlueprintValueCard key={it[0]} num={it[0]} glyph={it[1]} title={it[2]} body={it[3]} hue={it[4]} />)}
        </div>
      </div>
    </section>
  );
}

/* ---------------- Closing CTA ---------------- */
function BlueprintClosingCTA({ onSubscribed }) {
  return (
    <section style={{ position: 'relative', overflow: 'hidden', background: 'var(--ink-900)' }}>
      <div aria-hidden="true" className="prism-mesh" style={{ position: 'absolute', inset: '-20%', zIndex: 0, opacity: 0.32, mixBlendMode: 'screen', filter: 'blur(50px)' }} />
      <div style={{ ...container2, position: 'relative', zIndex: 1, paddingTop: 'clamp(64px,8vw,120px)', paddingBottom: 'clamp(64px,8vw,120px)', textAlign: 'center' }}>
        <h2 style={{ margin: '0 auto', maxWidth: '18ch', fontFamily: "'Inter', sans-serif", fontWeight: 600, fontSize: 'clamp(2.2rem,4vw,3.4rem)', lineHeight: 1.02, letterSpacing: '-0.04em', color: '#fff' }}>
          Get the Blueprint, free.
        </h2>
        <p style={{ margin: '18px auto 0', maxWidth: 480, fontFamily: 'var(--font-body)', fontSize: 17, lineHeight: 1.55, color: 'var(--on-ink-mid)' }}>
          One download. No spam. Unsubscribe anytime.
        </p>
        <div style={{ maxWidth: 460, margin: '32px auto 0', textAlign: 'left' }}>
          <BlueprintEmailForm onDone={onSubscribed} />
        </div>
      </div>
    </section>
  );
}

/* ---------------- Footer ---------------- */
function BlueprintFooter() {
  return (
    <footer style={{ background: 'var(--ink-900)', borderTop: '1px solid rgba(255,255,255,0.08)' }}>
      <div style={{ ...container2, paddingTop: 48, paddingBottom: 48, display: 'flex', flexWrap: 'wrap', gap: 28, alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <a href="/" style={{ display: 'inline-flex' }}><Logo tone="light" size={24} /></a>
          <p style={{ margin: '14px 0 0', fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--on-ink-low)', maxWidth: 320 }}>A free resource from The Prism — AI &amp; finance, every Tuesday.</p>
        </div>
        <div style={{ display: 'flex', gap: 28, flexWrap: 'wrap' }}>
          {['Back to insideprism.com', 'Privacy'].map((l, i) => (
            <a key={l} href={i === 0 ? '/' : '#'} style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--on-ink-mid)', textDecoration: 'none' }}>{l}</a>
          ))}
        </div>
      </div>
      <div style={{ ...container2, paddingBottom: 32 }}>
        <div style={{ borderTop: '1px solid rgba(255,255,255,0.08)', paddingTop: 22, fontFamily: 'var(--font-mono)', fontSize: 11.5, letterSpacing: '0.06em', color: 'var(--on-ink-low)' }}>
          © 2026 The Prism
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { BlueprintNav, BlueprintEmailForm, BlueprintHero, BlueprintContents, BlueprintClosingCTA, BlueprintFooter });
