/* global React */
const { useState: useStateA, useEffect: useEffectA, useRef: useRefA } = React;

/* Shared media-query hook */
function useMatchMedia(query) {
  const [matches, setMatches] = useStateA(() =>
    typeof window !== 'undefined' && window.matchMedia ? window.matchMedia(query).matches : false
  );
  useEffectA(() => {
    if (!window.matchMedia) return;
    const mq = window.matchMedia(query);
    const onChange = () => setMatches(mq.matches);
    onChange();
    if (mq.addEventListener) mq.addEventListener('change', onChange);
    else mq.addListener(onChange);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener('change', onChange);
      else mq.removeListener(onChange);
    };
  }, [query]);
  return matches;
}

/* ============================================
   FEATURED AGENTS — TRADING CARD CAROUSEL
   ============================================ */
function AgentsCarousel() {
  const [ref, seen] = window.useReveal(0.15);
  const isMobile = useMatchMedia('(max-width: 767px)');
  const agents = [
    { id: 'Müştəri', version: 'v2.4', deployment: 'PRIVATE CLOUD', kind: 'kyc',
      sector: 'Banking', title: 'Retail KYC, decided in 90 seconds.',
      capabilities: ['NLP', 'Az/Ru/En', 'Vision', 'Sanctions API'], hue: 215 },
    { id: 'Sığorta', version: 'v1.8', deployment: 'PRIVATE CLOUD', kind: 'claims',
      sector: 'Insurance', title: 'Hospital docs to triage queue, end-to-end.',
      capabilities: ['Custom NER', 'RAG', 'Az medical', 'Graph fraud'], hue: 220 },
    { id: 'Neft-AI', version: 'v3.1', deployment: 'ON-PREMISE', kind: 'neft',
      sector: 'Oil & Gas', title: 'A 40-year corpus, queryable in three seconds.',
      capabilities: ['Multilingual', 'Hybrid search', 'PDF', 'Citations'], hue: 210 },
    { id: 'Enerji', version: 'v1.2', deployment: 'PRIVATE CLOUD', kind: 'enerji',
      sector: 'Energy', title: '72-hour grid load, 8% sharper than baseline.',
      capabilities: ['TFT', 'Satellite CV', 'MLflow', 'K8s'], hue: 225 },
    { id: 'Fintex', version: 'v2.0', deployment: 'PRIVATE CLOUD', kind: 'fintex',
      sector: 'Fintech', title: 'Sub-50ms fraud decisions with reasons.',
      capabilities: ['GNN', 'LLM explain', 'Redis', 'Kafka'], hue: 230 },
    { id: 'Vizual', version: 'v1.4', deployment: 'EDGE · AIR-GAPPED', kind: 'vizual',
      sector: 'Industrial CV', title: 'Defects flagged in real time, on-camera.',
      capabilities: ['YOLO', 'ONNX', 'Edge', 'Reports'], hue: 205 },
  ];
  const [active, setActive] = useStateA(0);
  return (
    <section ref={ref} id="agents" style={{ paddingTop: 120, paddingBottom: 140 }}>
      <div className="container">
        <div className={`section-hairline`} style={{ marginBottom: 60, transform: seen ? 'scaleX(1)' : 'scaleX(0)', transition: 'transform 1200ms var(--ease-out-expo)' }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 60, gap: 40, flexWrap: 'wrap' }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 16 }}>FEATURED AGENTS — IN PRODUCTION</div>
            <h2 className="serif section-h2" style={{ fontSize: 'clamp(40px, 5vw, 64px)', letterSpacing: '-0.025em', lineHeight: 1.05 }}>
              Six agents. <em style={{ color: 'var(--accent-ice)', fontStyle: 'italic' }}>Every one</em> deployed.
            </h2>
          </div>
          <div className="agent-nav-btns" style={{ display: 'flex', gap: 8 }}>
            <button onClick={() => setActive(a => Math.max(0, a - 1))} className="glass" style={{ width: 44, height: 44, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M9 2L4 7l5 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
            </button>
            <button onClick={() => setActive(a => Math.min(agents.length - 3, a + 1))} className="glass" style={{ width: 44, height: 44, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M5 2l5 5-5 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
            </button>
          </div>
        </div>

        <div className={isMobile ? 'agent-carousel-wrap-mobile' : ''} style={{
          overflowX: isMobile ? 'auto' : 'hidden',
          overflowY: 'hidden',
          margin: '0 -8px',
          scrollSnapType: isMobile ? 'x mandatory' : 'none',
          WebkitOverflowScrolling: 'touch',
        }}>
          <div className="agent-carousel-track" style={{
            display: 'flex',
            gap: 20,
            transform: isMobile ? 'none' : `translateX(calc(${-active} * (33.333% + 6.66px)))`,
            transition: isMobile ? 'none' : 'transform 600ms var(--ease-out-expo)',
            padding: '0 8px',
          }}>
            {agents.map((a, i) => <AgentCard key={a.id} {...a} />)}
          </div>
        </div>
      </div>
    </section>
  );
}

function AgentCard({ id, version, deployment, sector, title, capabilities, hue, kind }) {
  const [hovered, setHovered] = useStateA(false);
  return (
    <div
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      className="agent-card"
      style={{
        flex: '0 0 calc(33.333% - 14px)',
        minHeight: 460,
        borderRadius: 20,
        padding: '24px 26px 28px',
        display: 'flex',
        flexDirection: 'column',
        position: 'relative',
        background: `linear-gradient(180deg, hsla(${hue}, 50%, 14%, 0.4), rgba(8, 12, 20, 0.5))`,
        border: '1px solid var(--border-glass)',
        backdropFilter: 'blur(18px)',
        WebkitBackdropFilter: 'blur(18px)',
        transform: hovered ? 'translateY(-4px)' : 'translateY(0)',
        boxShadow: hovered
          ? `inset 0 1px 0 0 rgba(220, 235, 255, 0.14), 0 28px 56px -16px rgba(0,0,0,0.6), 0 4px 24px -2px hsla(${hue}, 60%, 70%, 0.28)`
          : 'inset 0 1px 0 0 rgba(220, 235, 255, 0.06)',
        transition: 'transform 600ms var(--ease-out-expo), box-shadow 600ms ease',
      }}
    >
      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'var(--text-secondary)' }}>{id}</span>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-tertiary)' }}>{version}</span>
      </div>

      {/* Visual area — sector-specific mini mock with hover crossfade */}
      <div className="agent-card-thumb" style={{
        position: 'relative',
        height: 180,
        margin: '0 -10px 20px',
        borderRadius: 10,
        overflow: 'hidden',
        background: `radial-gradient(circle at 30% 40%, hsla(${hue}, 60%, 70%, 0.14), transparent 60%), linear-gradient(135deg, rgba(8,12,20,0.7), rgba(4,6,10,0.6))`,
        border: '1px solid var(--border-glass)',
      }}>
        <div className="agent-thumb-base" style={{ position: 'absolute', inset: 0 }}>
          <AgentMini kind={kind} hue={hue} hover={hovered} />
        </div>
        <div className="agent-thumb-detail">
          <AgentMiniDetail kind={kind} hue={hue} />
        </div>
      </div>

      {/* Title */}
      <h3 className="serif" style={{ fontSize: 24, lineHeight: 1.15, letterSpacing: '-0.015em', marginBottom: 'auto', minHeight: 84 }}>
        {title}
      </h3>

      {/* Deployment chip */}
      <div style={{
        marginTop: 20,
        display: 'flex',
        alignItems: 'center',
        gap: 8,
        paddingBottom: 12,
        borderBottom: '1px solid var(--border-glass)',
      }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--text-tertiary)', letterSpacing: '0.14em' }}>DEPLOY</span>
        <span style={{ width: 1, height: 8, background: 'var(--border-glass)' }} />
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: `hsla(${hue}, 60%, 80%, 0.95)`, letterSpacing: '0.08em' }}>{deployment}</span>
      </div>

      {/* Sector + capability chips */}
      <div style={{ marginTop: 14, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
        <span className="chip ice">{sector}</span>
        {capabilities.slice(0, 3).map(c => <span key={c} className="chip">{c}</span>)}
      </div>
    </div>
  );
}

/* AgentMini — tiny sector-specific visualizations as the card thumbnail */
function AgentMini({ kind, hue, hover }) {
  const accent = `hsl(${hue}, 60%, 78%)`;
  const accentDim = `hsla(${hue}, 60%, 70%, 0.35)`;

  if (kind === 'kyc') {
    return (
      <svg viewBox="0 0 320 180" style={{ width: '100%', height: '100%' }}>
        {/* Tab strip */}
        {['IDENTITY','LIVENESS','SANCTIONS','INCOME','DECISION'].map((t, i) => (
          <g key={t}>
            <text x={20 + i * 56} y="26" fontFamily="monospace" fontSize="7" fill={i === 2 ? accent : 'rgba(168,197,232,0.4)'} letterSpacing="0.08em">{t}</text>
            {i === 2 && <line x1={16 + i * 56} y1="32" x2={68 + i * 56} y2="32" stroke={accent} strokeWidth="1" />}
          </g>
        ))}
        {/* Sanctions list rows */}
        {[
          ['OFAC SDN', 'CLEAR', '#A8E8C5'],
          ['EU Consolidated', 'CLEAR', '#A8E8C5'],
          ['UN SC', 'CLEAR', '#A8E8C5'],
          ['AZ Watchlist', 'REVIEW', '#E8D4A8'],
        ].map(([list, status, c], i) => (
          <g key={list}>
            <rect x="20" y={48 + i * 22} width="280" height="16" fill="rgba(168,197,232,0.05)" stroke="rgba(168,197,232,0.15)" strokeWidth="0.5" rx="2" />
            <text x="28" y={59 + i * 22} fontFamily="monospace" fontSize="8" fill="rgba(220,235,255,0.85)">{list}</text>
            <text x="290" y={59 + i * 22} textAnchor="end" fontFamily="monospace" fontSize="8" fill={c} letterSpacing="0.08em">{status}</text>
          </g>
        ))}
      </svg>
    );
  }

  if (kind === 'claims') {
    return (
      <svg viewBox="0 0 320 180" style={{ width: '100%', height: '100%' }}>
        {[
          { x: 16, name: 'FAST', n: 23, c: '#A8E8C5' },
          { x: 116, name: 'STD', n: 18, c: accent },
          { x: 216, name: 'INV', n: 6, c: '#E8A8B5' },
        ].map(col => (
          <g key={col.name}>
            <text x={col.x} y="22" fontFamily="monospace" fontSize="8" fill={col.c} letterSpacing="0.1em">{col.name}</text>
            <text x={col.x + 80} y="22" textAnchor="end" fontFamily="monospace" fontSize="8" fill="rgba(168,197,232,0.45)">{col.n}</text>
            <line x1={col.x} y1="28" x2={col.x + 80} y2="28" stroke={col.c} strokeWidth="0.6" />
            {[0, 1, 2].map(i => (
              <g key={i}>
                <rect x={col.x} y={36 + i * 32} width="80" height="26" fill="rgba(168,197,232,0.06)" stroke="rgba(168,197,232,0.18)" strokeWidth="0.5" rx="2" />
                <text x={col.x + 6} y={48 + i * 32} fontFamily="monospace" fontSize="7" fill="rgba(168,197,232,0.5)">CLM-04{81 - i - col.x % 3}</text>
                <text x={col.x + 6} y={58 + i * 32} fontFamily="monospace" fontSize="7" fill={col.c}>{['I21.4','M16.1','C50.9'][i]}</text>
              </g>
            ))}
          </g>
        ))}
      </svg>
    );
  }

  if (kind === 'neft') {
    return (
      <svg viewBox="0 0 320 180" style={{ width: '100%', height: '100%' }}>
        {/* Query bar */}
        <rect x="16" y="14" width="288" height="22" fill="rgba(168,197,232,0.06)" stroke={accent} strokeWidth="0.6" rx="2" />
        <text x="22" y="29" fontFamily="monospace" fontSize="8" fill={accent}>&gt; wells in Bakı-Şamaxı, H₂S &gt; 200ppm</text>
        {/* Citation card */}
        <rect x="16" y="46" width="180" height="120" fill="rgba(168,197,232,0.03)" stroke="rgba(168,197,232,0.18)" strokeWidth="0.5" rx="3" />
        <text x="22" y="60" fontFamily="monospace" fontSize="7" fill={accent}>seismic-204.pdf · p.18</text>
        {[0,1,2,3,4].map(i => (
          <line key={i} x1="22" y1={72 + i * 10} x2={i === 2 ? 130 : 188} y2={72 + i * 10} stroke="rgba(168,197,232,0.22)" strokeWidth="0.6" />
        ))}
        <rect x="22" y={94} width="64" height="8" fill="rgba(168,197,232,0.18)" rx="1" />
        {/* Mini map */}
        <g transform="translate(204, 46)">
          <path d="M 0 60 C 20 30 40 25 60 35 C 80 45 95 40 100 50 L 100 80 L 0 80 Z" fill="rgba(168,197,232,0.06)" stroke={accentDim} strokeWidth="0.6" />
          {[[20,45],[40,38],[60,40],[80,52]].map(([x,y], i) => (
            <circle key={i} cx={x} cy={y} r={i === 0 ? 3 : 2} fill={i === 0 ? '#E8A8B5' : '#E8D4A8'} />
          ))}
          <text x="50" y="100" textAnchor="middle" fontFamily="monospace" fontSize="6" fill="rgba(168,197,232,0.45)">CASPIAN</text>
        </g>
      </svg>
    );
  }

  if (kind === 'enerji') {
    const fc = Array.from({ length: 24 }, (_, i) => 1400 + 600 * Math.sin(i * 0.3) + 100 * Math.cos(i * 0.7));
    const path = fc.map((v, i) => `${i === 0 ? 'M' : 'L'} ${16 + i * 12},${130 - ((v - 800) / 12)}`).join(' ');
    return (
      <svg viewBox="0 0 320 180" style={{ width: '100%', height: '100%' }}>
        <text x="16" y="22" fontFamily="monospace" fontSize="8" fill={accent} letterSpacing="0.1em">72H · MW</text>
        <text x="304" y="22" textAnchor="end" fontFamily="monospace" fontSize="8" fill="rgba(168,197,232,0.5)">err 4.2% ↓</text>
        {[40, 80, 120].map(y => <line key={y} x1="16" x2="304" y1={y} y2={y} stroke="rgba(168,197,232,0.06)" strokeWidth="0.5" />)}
        <path d={path + ` L 304,160 L 16,160 Z`} fill={`hsla(${hue},60%,70%,0.18)`} />
        <path d={path} stroke={accent} strokeWidth="1.4" fill="none" />
        {/* Weather strip */}
        <g transform="translate(16, 152)">
          {[18,21,23,22,19,17,15].map((t, i) => (
            <g key={i}>
              <rect x={i * 42} y="0" width="38" height="22" fill="rgba(168,197,232,0.04)" stroke="rgba(168,197,232,0.15)" strokeWidth="0.4" rx="1" />
              <text x={i * 42 + 6} y="13" fontFamily="monospace" fontSize="7" fill="rgba(168,197,232,0.7)">{t}°</text>
              <text x={i * 42 + 28} y="13" fontFamily="monospace" fontSize="7" fill="rgba(168,197,232,0.4)">{['☼','☼','☁','☁','☂','☂','☁'][i]}</text>
            </g>
          ))}
        </g>
      </svg>
    );
  }

  if (kind === 'fintex') {
    return (
      <svg viewBox="0 0 320 180" style={{ width: '100%', height: '100%' }}>
        <text x="16" y="22" fontFamily="monospace" fontSize="8" fill="#E8A8B5" letterSpacing="0.1em">TX-7782344 · BLOCK · 31MS</text>
        {/* Reason weight bars */}
        {[
          ['VEL_24H_3X', 38, 'velocity 3.1×'],
          ['GEO_ANOMALY', 26, 'IP ≠ card country'],
          ['MCC_NEW', 14, 'new merchant cat'],
          ['AMT_OUTLIER', 12, '92nd %ile'],
          ['TIME_OUTLIER', 7, '03:42 local'],
          ['DEVICE_NEW', 3, 'new fingerprint'],
        ].map(([code, w, label], i) => (
          <g key={code}>
            <text x="16" y={42 + i * 20} fontFamily="monospace" fontSize="7" fill="rgba(168,197,232,0.55)">{code}</text>
            <rect x="16" y={46 + i * 20} width={w * 2.5} height="6" fill="#E8A8B5" opacity={0.65} />
            <text x="304" y={52 + i * 20} textAnchor="end" fontFamily="monospace" fontSize="7" fill="rgba(168,197,232,0.5)">+{w}</text>
          </g>
        ))}
      </svg>
    );
  }

  if (kind === 'vizual') {
    return (
      <svg viewBox="0 0 320 180" style={{ width: '100%', height: '100%' }}>
        {/* fake video frame */}
        <rect x="16" y="14" width="200" height="150" fill="rgba(8,12,20,0.4)" stroke="rgba(168,197,232,0.18)" strokeWidth="0.6" />
        {/* pipe ellipses */}
        <ellipse cx="116" cy="89" rx="80" ry="50" fill="none" stroke="rgba(168,197,232,0.18)" strokeWidth="0.8" />
        <ellipse cx="116" cy="89" rx="50" ry="32" fill="none" stroke="rgba(168,197,232,0.12)" strokeWidth="0.6" />
        {/* defect boxes */}
        <rect x="44" y="52" width="42" height="22" fill="none" stroke="#E8A8B5" strokeWidth="1" />
        <text x="44" y="48" fontFamily="monospace" fontSize="6" fill="#E8A8B5">CRACK 0.94</text>
        <rect x="120" y="100" width="50" height="32" fill="none" stroke="#E8D4A8" strokeWidth="1" />
        <text x="120" y="96" fontFamily="monospace" fontSize="6" fill="#E8D4A8">CORROSION 0.78</text>
        {/* timestamp */}
        <text x="22" y="160" fontFamily="monospace" fontSize="6" fill="rgba(168,197,232,0.5)">REC · 00:14:22 · cam-04</text>
        {/* report sidebar */}
        <g transform="translate(228, 14)">
          <text x="0" y="10" fontFamily="monospace" fontSize="7" fill={accent} letterSpacing="0.1em">REPORT</text>
          {[['L1','#E8A8B5','Crack'],['L2','#E8D4A8','Corrosion'],['OK','#A8E8C5','Weld']].map(([sev, c, l], i) => (
            <g key={i}>
              <rect x="0" y={20 + i * 28} width="76" height="22" fill="rgba(168,197,232,0.04)" stroke="rgba(168,197,232,0.15)" strokeWidth="0.5" rx="2" />
              <text x="6" y={34 + i * 28} fontFamily="monospace" fontSize="7" fill={c}>{sev}</text>
              <text x="22" y={34 + i * 28} fontFamily="monospace" fontSize="7" fill="rgba(168,197,232,0.7)">{l}</text>
            </g>
          ))}
        </g>
      </svg>
    );
  }

  return null;
}

/* AgentMiniDetail — overlay revealed on card hover.
   Each kind exposes one extra UI element that signals depth. */
function AgentMiniDetail({ kind, hue }) {
  const accent = `hsl(${hue}, 60%, 78%)`;
  const common = { position: 'absolute', inset: 0 };
  const chip = (text, color, top, right) => (
    <div style={{
      position: 'absolute', top, right,
      padding: '5px 9px',
      fontFamily: 'var(--font-mono)', fontSize: 9,
      letterSpacing: '0.12em',
      color,
      background: 'rgba(4,6,10,0.78)',
      border: `1px solid ${color}`,
      borderRadius: 3,
      backdropFilter: 'blur(6px)',
      WebkitBackdropFilter: 'blur(6px)',
    }}>{text}</div>
  );
  if (kind === 'kyc') {
    return <div style={common}>{chip('DECISION · APPROVE', '#A8E8C5', 12, 12)}{chip('CONF 0.94', accent, 40, 12)}</div>;
  }
  if (kind === 'claims') {
    return <div style={common}>{chip('→ REVIEWER · S.A.', accent, 12, 12)}{chip('SLA 04:12', '#E8D4A8', 40, 12)}</div>;
  }
  if (kind === 'neft') {
    return <div style={common}>{chip('CITED · p.18 · §4.2', accent, 12, 12)}{chip('LATENCY 2.4s', '#A8E8C5', 40, 12)}</div>;
  }
  if (kind === 'enerji') {
    return <div style={common}>{chip('CONF BAND ±3.1%', accent, 12, 12)}{chip('PEAK +08:00', '#E8D4A8', 40, 12)}</div>;
  }
  if (kind === 'fintex') {
    return <div style={common}>{chip('REASON · VEL_24H_3X', '#E8A8B5', 12, 12)}{chip('AUDIT TX-7782344', accent, 40, 12)}</div>;
  }
  if (kind === 'vizual') {
    return <div style={common}>{chip('FRAME 00:14:22', accent, 12, 12)}{chip('SEV L1 · CRACK 0.94', '#E8A8B5', 40, 12)}</div>;
  }
  return null;
}

/* ============================================
   CODAGE METHOD — scroll-driven, rAF-throttled
   480vh sticky pin, 4 panels, animated active hairline,
   staggered artifact crossfade, reduced-motion fallback.
   ============================================ */
function useReducedMotion() {
  const [reduced, setReduced] = useStateA(() =>
    typeof window !== 'undefined' && window.matchMedia
      ? window.matchMedia('(prefers-reduced-motion: reduce)').matches
      : false);
  useEffectA(() => {
    if (!window.matchMedia) return;
    const mq = window.matchMedia('(prefers-reduced-motion: reduce)');
    const on = () => setReduced(mq.matches);
    mq.addEventListener ? mq.addEventListener('change', on) : mq.addListener(on);
    return () => { mq.removeEventListener ? mq.removeEventListener('change', on) : mq.removeListener(on); };
  }, []);
  return reduced;
}

function MethodSection() {
  const sectionRef = useRefA(null);
  const [progress, setProgress] = useStateA(0);
  const isMobile = useMatchMedia('(max-width: 767px)');
  const reduceMotion = useReducedMotion();

  useEffectA(() => {
    if (isMobile || reduceMotion) return;
    const el = sectionRef.current;
    if (!el) return;
    let raf = 0;
    let pending = false;
    const compute = () => {
      pending = false;
      const rect = el.getBoundingClientRect();
      const vh = window.innerHeight;
      const total = rect.height - vh;
      const scrolled = -rect.top;
      const p = Math.max(0, Math.min(1, scrolled / Math.max(1, total)));
      setProgress(p);
    };
    const onScroll = () => {
      if (pending) return;
      pending = true;
      raf = requestAnimationFrame(compute);
    };
    compute();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, [isMobile, reduceMotion]);

  const steps = [
    { label: 'DISCOVER', title: 'Find the real problem.', desc: 'Two weeks. Operators, data, edge cases.' },
    { label: 'PROTOTYPE', title: 'Build the thinnest cut.', desc: 'A working agent on real data — no slides.' },
    { label: 'PRODUCTION', title: 'Ship to operators.', desc: 'Hardened, monitored, audit-ready.' },
    { label: 'OPERATE', title: 'Stay in the loop.', desc: 'Drift, retraining, ongoing tuning.' },
  ];

  // Map progress (0..1) into a continuous step index, clamped to last step.
  // We give each step a 1/N slice and pick the floor — same math as before but
  // now we have 4× the scroll distance so each slice is a full viewport.
  const stepIndex = Math.min(steps.length - 1, Math.floor(progress * steps.length));
  // For the progress hairline next to the active step, derive a 0..1 sub-progress
  const activeStep = stepIndex;

  /* ============ Reduced motion fallback ============ */
  if (reduceMotion && !isMobile) {
    return (
      <section ref={sectionRef} data-bg="elevated" style={{ paddingTop: 80, paddingBottom: 100 }}>
        <div className="container">
          <div className="section-hairline" style={{ marginBottom: 32, transform: 'scaleX(1)' }} />
          <div style={{ marginBottom: 48 }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>THE CODAGE METHOD</div>
            <h2 className="serif section-h2" style={{ fontSize: 'clamp(40px, 5vw, 64px)', letterSpacing: '-0.025em', lineHeight: 1.05, maxWidth: 700 }}>
              How an idea becomes <em style={{ color: 'var(--accent-ice)', fontStyle: 'italic' }}>a deployed agent</em>.
            </h2>
          </div>
          {steps.map((s, i) => (
            <div key={s.label} style={{
              display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 60,
              alignItems: 'center', padding: '40px 0', borderTop: '1px solid var(--border-glass)',
            }}>
              <div style={{ position: 'relative', height: 320 }}>
                <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  {i === 0 && <ArtifactLens />}
                  {i === 1 && <ArtifactBlueprint />}
                  {i === 2 && <ArtifactRack />}
                  {i === 3 && <ArtifactDashboard />}
                </div>
              </div>
              <div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 18, marginBottom: 12 }}>
                  <span className="serif" style={{ color: 'var(--accent-ice)', fontSize: 28 }}>0{i + 1}</span>
                  <div className="eyebrow">{s.label}</div>
                </div>
                <h3 className="serif" style={{ fontSize: 32, letterSpacing: '-0.02em', lineHeight: 1.1, marginBottom: 8 }}>{s.title}</h3>
                <p style={{ color: 'var(--text-secondary)', fontSize: 16 }}>{s.desc}</p>
              </div>
            </div>
          ))}
        </div>
      </section>
    );
  }

  /* ============ Mobile: scroll-snap full-screen panels ============ */
  if (isMobile) {
    return (
      <section ref={sectionRef} data-bg="elevated" style={{ position: 'relative' }}>
        <div className="container" style={{ paddingTop: 80, paddingBottom: 24 }}>
          <div className="eyebrow" style={{ marginBottom: 16 }}>THE CODAGE METHOD</div>
          <h2 className="serif section-h2" style={{ fontSize: 'clamp(32px, 7vw, 40px)', letterSpacing: '-0.025em', lineHeight: 1.05 }}>
            How an idea becomes <em style={{ color: 'var(--accent-ice)', fontStyle: 'italic' }}>a deployed agent</em>.
          </h2>
        </div>
        <div className="method-mobile-track" style={{ scrollSnapType: 'y mandatory', WebkitOverflowScrolling: 'touch' }}>
          {steps.map((s, i) => (
            <MethodMobilePanel key={s.label} step={s} index={i} total={steps.length} />
          ))}
        </div>
      </section>
    );
  }

  /* ============ Desktop: 480vh sticky scroll-pinned ============ */
  return (
    <section ref={sectionRef} data-bg="elevated" style={{ height: '480vh', position: 'relative' }}>
      <div style={{
        position: 'sticky',
        top: 0,
        height: '100vh',
        display: 'flex',
        alignItems: 'center',
      }}>
        <div className="container" style={{ width: '100%', position: 'relative' }}>
          <div className="section-hairline" style={{ marginBottom: 32, transform: 'scaleX(1)' }} />
          <div style={{ marginBottom: 48 }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>THE CODAGE METHOD</div>
            <h2 className="serif section-h2" style={{ fontSize: 'clamp(40px, 5vw, 64px)', letterSpacing: '-0.025em', lineHeight: 1.05, maxWidth: 700 }}>
              How an idea becomes <em style={{ color: 'var(--accent-ice)', fontStyle: 'italic' }}>a deployed agent</em>.
            </h2>
          </div>

          <div className="method-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 60, alignItems: 'center' }}>
            {/* visual stage */}
            <div className="method-artifact-stage" style={{ position: 'relative', height: 380 }}>
              {steps.map((s, i) => (
                <MethodArtifact
                  key={s.label}
                  index={i}
                  active={activeStep === i}
                  past={i < activeStep}
                />
              ))}
            </div>

            {/* steps list */}
            <div>
              {steps.map((s, i) => {
                const isActive = activeStep === i;
                return (
                  <div key={s.label} data-method-step={i} data-active={isActive ? 'true' : 'false'} style={{
                    padding: '22px 0',
                    borderBottom: '1px solid var(--border-glass)',
                    color: isActive ? 'rgba(238,242,248,1)' : 'rgba(238,242,248,0.32)',
                    transform: isActive ? 'scale(1.04)' : 'scale(1)',
                    transformOrigin: 'left center',
                    transition: 'color 500ms var(--ease-out-expo), transform 500ms var(--ease-out-expo)',
                    display: 'grid',
                    gridTemplateColumns: '56px 1fr',
                    gap: 20,
                    alignItems: 'baseline',
                    position: 'relative',
                  }}>
                    {/* active hairline — 8px to the left of the step number */}
                    <span aria-hidden="true" style={{
                      position: 'absolute',
                      left: -16,
                      top: '50%',
                      width: 24,
                      height: 1,
                      background: 'var(--accent-ice)',
                      transformOrigin: 'left center',
                      transform: isActive ? 'scaleX(1)' : 'scaleX(0)',
                      transition: 'transform 200ms var(--ease-out-expo) 80ms',
                      boxShadow: '0 0 6px rgba(168,197,232,0.7)',
                    }} />
                    <span className="serif" style={{
                      color: isActive ? 'var(--accent-ice-bright)' : 'var(--accent-ice)',
                      fontSize: 28,
                      lineHeight: 1,
                      transition: 'color 400ms ease',
                    }}>0{i + 1}</span>
                    <div>
                      <div className="eyebrow" style={{ marginBottom: 8, color: isActive ? 'var(--accent-ice)' : 'rgba(168,197,232,0.45)', transition: 'color 400ms ease' }}>{s.label}</div>
                      <h3 className="serif" style={{ fontSize: 28, letterSpacing: '-0.02em', lineHeight: 1.1, marginBottom: 6 }}>{s.title}</h3>
                      <p style={{ color: isActive ? 'var(--text-secondary)' : 'inherit', fontSize: 15 }}>{s.desc}</p>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* 4-dot vertical progress indicator on right edge */}
          <div aria-hidden="true" style={{
            position: 'absolute',
            top: '50%',
            right: 0,
            transform: 'translate(0, -50%)',
            display: 'flex',
            flexDirection: 'column',
            gap: 14,
            padding: '10px 0',
          }}>
            {steps.map((_, i) => {
              const isActive = activeStep === i;
              const isPast = i < activeStep;
              return (
                <span key={i} style={{
                  width: isActive ? 10 : 6,
                  height: isActive ? 10 : 6,
                  borderRadius: '50%',
                  background: isActive ? 'var(--accent-ice)' : (isPast ? 'rgba(168,197,232,0.55)' : 'transparent'),
                  border: isActive ? '1px solid var(--accent-ice)' : '1px solid rgba(168,197,232,0.35)',
                  boxShadow: isActive ? '0 0 8px rgba(168,197,232,0.7)' : 'none',
                  transition: 'width 300ms var(--ease-out-expo), height 300ms var(--ease-out-expo), background 300ms ease, box-shadow 300ms ease',
                }} />
              );
            })}
          </div>
        </div>
      </div>
    </section>
  );
}

/* Mobile panel — full-viewport with progress bar */
function MethodMobilePanel({ step, index, total }) {
  const fillPct = ((index + 1) / total) * 100;
  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex',
      flexDirection: 'column',
      padding: '32px 0 40px',
      scrollSnapAlign: 'start',
      position: 'relative',
    }}>
      {/* Progress strip */}
      <div className="container" style={{
        display: 'flex',
        alignItems: 'center',
        gap: 14,
        marginBottom: 20,
      }}>
        <span className="eyebrow" style={{ flexShrink: 0 }}>{step.label}</span>
        <div style={{ flex: 1, height: 1, background: 'rgba(168,197,232,0.18)', position: 'relative', overflow: 'hidden' }}>
          <div style={{
            position: 'absolute', inset: 0,
            background: 'var(--accent-ice)',
            boxShadow: '0 0 6px rgba(168,197,232,0.6)',
            transformOrigin: 'left center',
            transform: `scaleX(${fillPct / 100})`,
            transition: 'transform 400ms var(--ease-out-expo)',
          }} />
        </div>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-tertiary)', letterSpacing: '0.1em', flexShrink: 0 }}>
          0{index + 1} / 0{total}
        </span>
      </div>

      <div style={{ flex: '0 0 50vh', position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '40vh' }}>
        <MethodArtifact index={index} active={true} past={false} forceFull />
      </div>
      <div className="container" style={{ flex: '1 1 auto', display: 'flex', flexDirection: 'column', justifyContent: 'flex-start', paddingTop: 24 }}>
        <h3 className="serif" style={{ fontSize: 32, letterSpacing: '-0.02em', lineHeight: 1.1, marginBottom: 10 }}>{step.title}</h3>
        <p style={{ color: 'var(--text-secondary)', fontSize: 16, lineHeight: 1.55 }}>{step.desc}</p>
      </div>
    </div>
  );
}

function MethodArtifact({ index, active, past, forceFull }) {
  // Outgoing leaves first (immediate); incoming arrives 100ms later.
  const isVisible = active || forceFull;
  const opacity = isVisible ? 1 : 0;
  const scale = isVisible ? 1 : 0.95;
  const ty = forceFull ? 0 : (past ? 12 : (active ? 0 : -12));
  // Stagger: incoming gets a 100ms delay, outgoing leaves immediately
  const delay = active ? 100 : 0;
  return (
    <div style={{
      position: 'absolute',
      inset: 0,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      transform: `translateY(${ty}px) scale(${scale})`,
      opacity,
      transition: `transform 400ms var(--ease-out-expo) ${delay}ms, opacity 400ms ease ${delay}ms`,
      zIndex: active ? 5 : 1,
      pointerEvents: active ? 'auto' : 'none',
    }}>
      {index === 0 && <ArtifactLens />}
      {index === 1 && <ArtifactBlueprint />}
      {index === 2 && <ArtifactRack />}
      {index === 3 && <ArtifactDashboard />}
    </div>
  );
}

function GlassWrap({ children }) {
  return (
    <div style={{ width: 360, height: 320, position: 'relative', filter: 'drop-shadow(0 28px 56px rgba(0,0,0,0.55))' }}>
      {children}
    </div>
  );
}

function ArtifactLens() {
  // DISCOVER — stack of transcripts with margin annotations
  return (
    <GlassWrap>
      <svg viewBox="0 0 360 320" style={{ width: '100%', height: '100%' }}>
        <defs>
          <linearGradient id="docGrad" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="rgba(220,235,255,0.16)" />
            <stop offset="100%" stopColor="rgba(168,197,232,0.04)" />
          </linearGradient>
        </defs>
        {/* Three stacked transcript pages with offset */}
        {[
          { x: 40, y: 60, rot: -2 },
          { x: 60, y: 50, rot: 1 },
          { x: 80, y: 40, rot: -1 },
        ].map((p, i) => (
          <g key={i} transform={`translate(${p.x}, ${p.y}) rotate(${p.rot} 110 120)`}>
            <rect x="0" y="0" width="220" height="240" fill="url(#docGrad)" stroke="rgba(220,235,255,0.45)" strokeWidth="1.2" />
          </g>
        ))}
        {/* Top page content */}
        <g transform="translate(80, 40) rotate(-1 110 120)">
          {/* header */}
          <text x="14" y="24" fontFamily="monospace" fontSize="8" fill="rgba(168,197,232,0.7)" letterSpacing="0.1em">INTERVIEW · COMPLIANCE LEAD · 2026-04-08</text>
          <line x1="14" y1="34" x2="206" y2="34" stroke="rgba(168,197,232,0.25)" strokeWidth="0.6" />
          {/* transcript lines — boosted opacity for legibility on dark bg */}
          {Array.from({ length: 9 }).map((_, i) => (
            <line key={i} x1="14" y1={48 + i * 14} x2={i === 3 || i === 6 ? 130 : 200} y2={48 + i * 14} stroke="rgba(220,235,255,0.5)" strokeWidth="0.8" />
          ))}
          {/* annotation arrows in margin */}
          <path d="M 224 76 q 12 4 12 18" stroke="#E8D4A8" strokeWidth="0.8" fill="none" />
          <text x="240" y="70" fontFamily="monospace" fontSize="8" fill="#E8D4A8">L1: 5 days</text>
          <text x="240" y="82" fontFamily="monospace" fontSize="8" fill="rgba(232,212,168,0.6)">manual KYC</text>
          <path d="M 224 132 q 12 4 12 14" stroke="#A8E8C5" strokeWidth="0.8" fill="none" />
          <text x="240" y="126" fontFamily="monospace" fontSize="8" fill="#A8E8C5">automate?</text>
          {/* highlighted span */}
          <rect x="14" y="158" width="120" height="14" fill="rgba(168,197,232,0.32)" />
          <text x="14" y="232" fontFamily="monospace" fontSize="7" fill="rgba(168,197,232,0.65)">17 / 23 transcripts</text>
        </g>
      </svg>
    </GlassWrap>
  );
}

function ArtifactBlueprint() {
  // PROTOTYPE — perspective-tilted blueprint with version chip
  return (
    <GlassWrap>
      <svg viewBox="0 0 360 320" style={{ width: '100%', height: '100%' }}>
        <defs>
          <linearGradient id="bpGrad" x1="0" x2="1" y1="0" y2="1">
            <stop offset="0%" stopColor="rgba(168,197,232,0.22)" />
            <stop offset="100%" stopColor="rgba(168,197,232,0.04)" />
          </linearGradient>
        </defs>
        {/* version chip floating top-right */}
        <g>
          <rect x="244" y="20" width="80" height="22" rx="3" fill="rgba(232,212,168,0.12)" stroke="rgba(232,212,168,0.4)" />
          <text x="284" y="35" textAnchor="middle" fontFamily="monospace" fontSize="9" fill="#E8D4A8" letterSpacing="0.1em">v0.3 · DRAFT</text>
        </g>
        {/* 3D-perspective tilt via skew + scale */}
        <g transform="matrix(0.95 -0.18 0.18 0.85 -10 60)">
          <rect x="40" y="40" width="260" height="220" fill="url(#bpGrad)" stroke="rgba(220,235,255,0.55)" strokeWidth="1.5" />
          {/* grid */}
          {[...Array(13)].map((_, i) => (
            <line key={`v${i}`} x1={40 + i * 22} x2={40 + i * 22} y1="40" y2="260" stroke="rgba(168,197,232,0.1)" strokeWidth="0.5" />
          ))}
          {[...Array(11)].map((_, i) => (
            <line key={`h${i}`} x1="40" x2="300" y1={40 + i * 22} y2={40 + i * 22} stroke="rgba(168,197,232,0.1)" strokeWidth="0.5" />
          ))}
          {/* nodes + labels */}
          <circle cx="100" cy="100" r="14" fill="rgba(168,197,232,0.25)" stroke="#A8C5E8" strokeWidth="1.2" />
          <text x="100" y="104" textAnchor="middle" fontFamily="monospace" fontSize="8" fill="#A8C5E8">A</text>
          <circle cx="220" cy="160" r="14" fill="rgba(168,197,232,0.25)" stroke="#A8C5E8" strokeWidth="1.2" />
          <text x="220" y="164" textAnchor="middle" fontFamily="monospace" fontSize="8" fill="#A8C5E8">B</text>
          <circle cx="160" cy="220" r="14" fill="rgba(168,197,232,0.25)" stroke="#A8C5E8" strokeWidth="1.2" />
          <text x="160" y="224" textAnchor="middle" fontFamily="monospace" fontSize="8" fill="#A8C5E8">C</text>
          <line x1="100" y1="100" x2="220" y2="160" stroke="#A8C5E8" strokeWidth="1.2" strokeDasharray="2,2" />
          <line x1="220" y1="160" x2="160" y2="220" stroke="#A8C5E8" strokeWidth="1.2" strokeDasharray="2,2" />
          <text x="60" y="62" fontFamily="monospace" fontSize="8" fill="rgba(168,197,232,0.7)" letterSpacing="0.1em">SKETCH · 03 ITERATIONS</text>
        </g>
      </svg>
    </GlassWrap>
  );
}

function ArtifactRack() {
  // PRODUCTION — server rack with deployment target labels
  const targets = [
    'PRIVATE CLOUD · az-east-1',
    'ON-PREM · client DC',
    'AIR-GAPPED · isolated',
    'EDGE · 12 sites',
  ];
  return (
    <GlassWrap>
      <svg viewBox="0 0 360 320" style={{ width: '100%', height: '100%' }}>
        <defs>
          <linearGradient id="rackGrad" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="rgba(220,235,255,0.2)" />
            <stop offset="100%" stopColor="rgba(168,197,232,0.06)" />
          </linearGradient>
        </defs>
        <rect x="60" y="40" width="160" height="240" fill="url(#rackGrad)" stroke="rgba(220,235,255,0.5)" strokeWidth="1.5" rx="6" />
        {Array.from({ length: 4 }).map((_, i) => (
          <g key={i}>
            <rect x="76" y={60 + i * 56} width="128" height="44" fill="rgba(12,20,48,0.65)" stroke="rgba(168,197,232,0.3)" strokeWidth="0.6" rx="3" />
            {/* unit detail */}
            <rect x="84" y={68 + i * 56} width="44" height="6" fill="rgba(168,197,232,0.35)" rx="1" />
            <rect x="84" y={78 + i * 56} width="68" height="4" fill="rgba(168,197,232,0.18)" rx="1" />
            <rect x="84" y={86 + i * 56} width="32" height="4" fill="rgba(168,197,232,0.18)" rx="1" />
            <circle cx="194" cy={78 + i * 56} r="2.5" fill="#A8E8C5" />
            {/* Connector line out to deployment label */}
            <line x1="220" y1={82 + i * 56} x2="240" y2={82 + i * 56} stroke="rgba(168,197,232,0.4)" strokeWidth="0.8" />
            <text x="244" y={80 + i * 56} fontFamily="monospace" fontSize="8" fill="rgba(168,197,232,0.85)" letterSpacing="0.05em">{targets[i]}</text>
            <text x="244" y={92 + i * 56} fontFamily="monospace" fontSize="7" fill="rgba(168,197,232,0.45)">{['v2.4','v2.4','v2.3','v2.4'][i]} · stable</text>
          </g>
        ))}
      </svg>
    </GlassWrap>
  );
}

function ArtifactDashboard() {
  // OPERATE — regression chart with labeled SLO threshold line
  return (
    <GlassWrap>
      <svg viewBox="0 0 360 320" style={{ width: '100%', height: '100%' }}>
        <rect x="30" y="50" width="300" height="220" fill="rgba(168,197,232,0.06)" stroke="rgba(220,235,255,0.45)" strokeWidth="1.2" rx="8" />
        {/* header strip */}
        <rect x="30" y="50" width="300" height="26" fill="rgba(168,197,232,0.04)" />
        <text x="46" y="68" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.7)" letterSpacing="0.1em">EVAL · v2.4 PROD</text>
        <text x="318" y="68" textAnchor="end" fontFamily="monospace" fontSize="8" fill="rgba(168,197,232,0.45)">2026-04-30 14:22</text>

        {/* y-axis labels */}
        <text x="44" y="100" fontFamily="monospace" fontSize="7" fill="rgba(168,197,232,0.4)">100%</text>
        <text x="44" y="160" fontFamily="monospace" fontSize="7" fill="rgba(168,197,232,0.4)">95%</text>
        <text x="44" y="220" fontFamily="monospace" fontSize="7" fill="rgba(168,197,232,0.4)">90%</text>

        {/* SLO threshold line at 95% */}
        <line x1="60" y1="158" x2="320" y2="158" stroke="#E8D4A8" strokeWidth="0.8" strokeDasharray="3,3" />
        <text x="316" y="154" textAnchor="end" fontFamily="monospace" fontSize="8" fill="#E8D4A8" letterSpacing="0.1em">SLO 95% — pass rate</text>

        {/* Performance line — eval pass rate over 14 versions */}
        {(() => {
          const pts = [180, 175, 160, 168, 155, 148, 152, 142, 138, 145, 138, 130, 125, 120];
          const path = pts.map((y, i) => `${i === 0 ? 'M' : 'L'} ${66 + i * 18} ${y}`).join(' ');
          return (
            <>
              <path d={path + ' L 300 240 L 66 240 Z'} fill="rgba(168,232,197,0.12)" />
              <path d={path} stroke="#A8E8C5" strokeWidth="1.6" fill="none" />
              {pts.map((y, i) => <circle key={i} cx={66 + i * 18} cy={y} r="2" fill="#A8E8C5" />)}
            </>
          );
        })()}

        {/* x-axis version ticks */}
        <text x="66" y="256" fontFamily="monospace" fontSize="7" fill="rgba(168,197,232,0.35)">v2.0</text>
        <text x="180" y="256" fontFamily="monospace" fontSize="7" fill="rgba(168,197,232,0.35)">v2.2</text>
        <text x="300" y="256" textAnchor="end" fontFamily="monospace" fontSize="7" fill="rgba(168,197,232,0.35)">v2.4</text>
      </svg>
    </GlassWrap>
  );
}

/* ============================================
   LAB NOTES PREVIEW
   ============================================ */
function LabNotes() {
  const [ref, seen] = window.useReveal(0.15);
  // Cascade: 1 lead, 2 mid-tier, 5 archive in mono list
  const lead = { date: '2026-04-12', title: 'Tokenizing Azerbaijani: why off-the-shelf tokenizers waste 30% of your context window.', read: '8 min', tag: 'NLP' };
  const mid = [
    { date: '2026-03-28', title: 'Building a multilingual RAG pipeline over forty years of seismic reports.', read: '12 min', tag: 'RAG' },
    { date: '2026-03-09', title: 'Liveness detection on low-bandwidth mobile networks: lessons from the field.', read: '6 min', tag: 'Vision' },
  ];
  const archive = [
    { date: '2026-02-21', title: 'Why we re-architected our fraud detection agent around explanations, not predictions.', read: '10 min' },
    { date: '2026-02-04', title: 'What we learned shipping our first agent into production banking.', read: '7 min' },
    { date: '2026-01-19', title: 'Russian + Azerbaijani medical NER: a benchmark and what it taught us.', read: '9 min' },
    { date: '2026-01-05', title: 'Sub-50ms LLM inference: the engineering behind real-time fraud explanations.', read: '11 min' },
    { date: '2025-12-15', title: 'Glass, code, and the Caspian: notes on building Codage.', read: '5 min' },
  ];

  return (
    <section ref={ref} id="lab" data-bg="elevated" style={{ paddingTop: 120, paddingBottom: 140 }}>
      <div className="container">
        <div className={`section-hairline`} style={{ marginBottom: 56, transform: seen ? 'scaleX(1)' : 'scaleX(0)', transition: 'transform 1200ms var(--ease-out-expo)' }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 48, flexWrap: 'wrap', gap: 20 }}>
          <div className="eyebrow">FROM THE LAB · 8 NOTES</div>
          <a href="Lab.html" className="btn btn-secondary">All notes →</a>
        </div>

        {/* Lead — 96px editorial moment */}
        <a href="Lab.html" className={`lab-lead reveal${seen ? ' in' : ''}`} style={{
          display: 'block',
          marginBottom: 64,
          paddingBottom: 40,
          borderBottom: '1px solid var(--border-glass)',
          transitionDelay: '120ms',
        }}>
          <div style={{ display: 'flex', gap: 14, alignItems: 'baseline', marginBottom: 18 }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--accent-ice)', letterSpacing: '0.12em' }}>{lead.date}</span>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-tertiary)', letterSpacing: '0.12em' }}>· {lead.tag} · {lead.read}</span>
          </div>
          <h3 className="serif lab-lead-title" style={{
            fontSize: 'clamp(40px, 6.5vw, 96px)',
            lineHeight: 0.98,
            letterSpacing: '-0.03em',
            color: 'var(--text-primary)',
            margin: 0,
            maxWidth: '95%',
          }}>{lead.title}</h3>
        </a>

        {/* Mid tier — two posts at 32-48px */}
        <div className={`lab-mid reveal${seen ? ' in' : ''}`} style={{
          display: 'grid',
          gridTemplateColumns: '1fr 1fr',
          gap: 48,
          marginBottom: 64,
          paddingBottom: 48,
          borderBottom: '1px solid var(--border-glass)',
          transitionDelay: '240ms',
        }}>
          {mid.map((p, i) => (
            <a key={i} href="Lab.html" style={{ display: 'block' }}>
              <div style={{ display: 'flex', gap: 12, alignItems: 'baseline', marginBottom: 12 }}>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-tertiary)', letterSpacing: '0.12em' }}>{p.date}</span>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--accent-ice)', letterSpacing: '0.12em' }}>· {p.tag} · {p.read}</span>
              </div>
              <h4 className="serif lab-mid-title" style={{
                fontSize: 'clamp(24px, 3.2vw, 40px)',
                lineHeight: 1.1,
                letterSpacing: '-0.02em',
                color: 'var(--text-primary)',
                margin: 0,
              }}>{p.title}</h4>
            </a>
          ))}
        </div>

        {/* Archive — tight mono list */}
        <div className={`lab-archive reveal${seen ? ' in' : ''}`} style={{
          fontFamily: 'var(--font-mono)',
          fontSize: 12,
          color: 'var(--text-tertiary)',
          transitionDelay: '360ms',
        }}>
          <div style={{ ...{
            fontFamily: 'var(--font-mono)', fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.14em',
          }, marginBottom: 16 }}>ARCHIVE</div>
          {archive.map((p, i) => (
            <a key={i} href="Lab.html" style={{
              display: 'grid',
              gridTemplateColumns: '110px 1fr 80px',
              gap: 24,
              alignItems: 'baseline',
              padding: '12px 0',
              borderTop: i === 0 ? '1px solid var(--border-glass)' : 'none',
              borderBottom: '1px solid var(--border-glass)',
              transition: 'padding 300ms var(--ease-out-expo)',
            }}
            onMouseOver={e => { e.currentTarget.style.paddingLeft = '8px'; e.currentTarget.style.background = 'rgba(168,197,232,0.03)'; }}
            onMouseOut={e => { e.currentTarget.style.paddingLeft = '0'; e.currentTarget.style.background = 'transparent'; }}
            >
              <span style={{ color: 'var(--text-tertiary)' }}>{p.date}</span>
              <span style={{ color: 'var(--text-secondary)', fontFamily: 'var(--font-serif)', fontSize: 15, lineHeight: 1.4 }}>{p.title}</span>
              <span style={{ textAlign: 'right' }}>{p.read}</span>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============================================
   CLOSING CTA
   ============================================ */
function ClosingCTA() {
  const [ref, seen] = window.useReveal(0.2);
  const isMobile = useMatchMedia('(max-width: 767px)');
  return (
    <section ref={ref} className="closing-cta" style={{
      position: 'relative',
      paddingTop: 'clamp(120px, 20vh, 200px)',
      paddingBottom: 'clamp(120px, 20vh, 200px)',
      overflow: 'hidden',
      borderTop: '1px solid var(--border-glass)',
      background: 'linear-gradient(180deg, var(--bg-base) 0%, var(--bg-deep, #04060a) 100%)',
    }}>
      {/* Background brand element — wordmark on desktop, glass C mark on mobile */}
      <div aria-hidden="true" style={{
        position: 'absolute',
        inset: 0,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        pointerEvents: 'none',
      }}>
        {isMobile ? (
          <img
            src="assets/brand/codage-favicon.png"
            alt=""
            className={`closing-mark${seen ? ' breathe' : ''}`}
            style={{
              width: 280,
              height: 280,
              opacity: seen ? undefined : 0,
              transition: 'opacity 1200ms ease',
              filter: 'drop-shadow(0 0 60px rgba(168,197,232,0.18))',
            }}
          />
        ) : (
          <div className={`serif closing-ghost${seen ? ' breathe' : ''}`} style={{
            fontSize: 'clamp(160px, 28vw, 480px)',
            letterSpacing: '-0.04em',
            lineHeight: 0.9,
            color: 'transparent',
            background: 'linear-gradient(180deg, rgba(168,197,232,0.18), rgba(168,197,232,0.04))',
            WebkitBackgroundClip: 'text',
            backgroundClip: 'text',
            fontWeight: 400,
            whiteSpace: 'nowrap',
            opacity: seen ? undefined : 0,
            transition: 'opacity 1200ms ease',
          }}>CODAGE</div>
        )}
      </div>

      {/* Subtle radial glow */}
      <div aria-hidden="true" style={{
        position: 'absolute',
        top: '20%', left: '50%', width: '70%', height: '70%',
        transform: 'translateX(-50%)',
        background: 'radial-gradient(ellipse at center, rgba(168,197,232,0.16), transparent 65%)',
        pointerEvents: 'none',
      }} />

      <div className="container" style={{ position: 'relative', zIndex: 2 }}>
        <div className={`section-hairline reveal${seen ? ' in' : ''}`} style={{ marginBottom: 56, transform: seen ? 'scaleX(1)' : 'scaleX(0)', transition: 'transform 1200ms var(--ease-out-expo)' }} />
        <div className={`reveal${seen ? ' in' : ''}`} style={{ maxWidth: 880 }}>
          <div className="eyebrow" style={{ marginBottom: 28 }}>WORK WITH CODAGE</div>
          <h2 className="serif cta-h2" style={{
            fontSize: 'clamp(44px, 6vw, 88px)',
            letterSpacing: '-0.03em',
            lineHeight: 1.0,
            marginBottom: 28,
            textWrap: 'pretty',
          }}>
            Book a 30-minute <em style={{ color: 'var(--accent-ice)', fontStyle: 'italic' }}>AI Workflow Audit.</em>
          </h2>
          <p style={{ color: 'var(--text-secondary)', fontSize: 'clamp(15px, 1.4vw, 19px)', maxWidth: 640, marginBottom: 44, lineHeight: 1.55 }}>
            We review one of your workflows, estimate automation potential, and tell you whether an AI agent actually makes sense. No deck, no pitch — we either see a clear opportunity or we tell you it's not the right fit yet.
          </p>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
            <a href="https://calendar.app.google/an2mX8SWcKPFcvNK6" target="_blank" rel="noopener noreferrer" className="btn btn-primary">
              Book a workflow audit
              <svg className="arrow-icon" width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M2 7h10m0 0L7 2m5 5L7 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </a>
            <a href="mailto:elgun@codage.az" className="btn btn-secondary">elgun@codage.az</a>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-tertiary)', letterSpacing: '0.12em', marginLeft: 4 }}>· 30 MIN · NO DECK</span>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================
   FOOTER
   ============================================ */
function Footer() {
  return (
    <footer style={{ borderTop: '1px solid var(--border-glass)', paddingTop: 80, paddingBottom: 60, position: 'relative' }}>
      <div className="container">
        <div className="footer-grid" style={{
          display: 'grid',
          gridTemplateColumns: '2fr 1fr 1fr 1fr',
          gap: 60,
          marginBottom: 80,
        }}>
          <div>
            <div style={{ marginBottom: 24 }}>
              <window.CodageWordmark size={36} />
            </div>
            <p style={{ color: 'var(--text-secondary)', fontSize: 15, maxWidth: 360, lineHeight: 1.55 }}>
              An applied AI lab building agents for the languages, regulations, and realities of the Caspian region.
            </p>
          </div>
          <div>
            <div className="eyebrow" style={{ marginBottom: 20 }}>BAKU</div>
            <div style={{ color: 'var(--text-secondary)', fontSize: 14, lineHeight: 1.7 }}>
              Headquarters<br />
              <a href="tel:+994515133777" className="footer-link">+994 51 513 37 77</a>
            </div>
          </div>
          <div>
            <div className="eyebrow" style={{ marginBottom: 20 }}>PARIS</div>
            <div style={{ color: 'var(--text-secondary)', fontSize: 14, lineHeight: 1.7 }}>
              Desk<br />
              <a href="tel:+33744772671" className="footer-link">+33 7 44 77 26 71</a>
            </div>
          </div>
          <div>
            <div className="eyebrow" style={{ marginBottom: 20 }}>CONTACT</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 14, lineHeight: 1.7 }}>
              <a href="mailto:info@codage.az" className="footer-link">info@codage.az</a>
              <a href="mailto:elgun@codage.az" className="footer-link">elgun@codage.az</a>
              <a href="mailto:fatulla@codage.az" className="footer-link">fatulla@codage.az</a>
            </div>
          </div>
        </div>
        <div style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          paddingTop: 32,
          borderTop: '1px solid var(--border-glass)',
          fontFamily: 'var(--font-mono)',
          fontSize: 11,
          textTransform: 'uppercase',
          letterSpacing: '0.1em',
          color: 'var(--text-tertiary)',
          flexWrap: 'wrap',
          gap: 16,
        }}>
          <span>© 2026 Codage · codage.az</span>
          <span>Applied AI Lab · Baku / Paris</span>
          <span>40.4°N · 49.8°E</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { AgentsCarousel, MethodSection, LabNotes, ClosingCTA, Footer });
