/* global React */
const { useState: useStateW, useEffect: useEffectW, useRef: useRefW } = React;

function CaseCover({ hue, kind }) {
  // Three abstract glass cover artworks — passport, geology, document stack
  if (kind === 'passport') return (
    <svg viewBox="0 0 600 400" preserveAspectRatio="xMidYMid slice" style={{ width: '100%', height: '100%' }}>
      <defs>
        <radialGradient id="cv1Glow" cx="0.5" cy="0.4">
          <stop offset="0%" stopColor={`hsla(${hue}, 70%, 70%, 0.4)`} />
          <stop offset="100%" stopColor="transparent" />
        </radialGradient>
        <linearGradient id="cv1Pp" x1="0" x2="1" y1="0" y2="1">
          <stop offset="0%" stopColor="rgba(220,235,255,0.25)" />
          <stop offset="100%" stopColor="rgba(168,197,232,0.08)" />
        </linearGradient>
      </defs>
      <rect width="600" height="400" fill="url(#cv1Glow)" />
      {/* dossier behind */}
      <g transform="translate(140 220) rotate(-4)">
        <rect width="320" height="180" rx="10" fill="rgba(168,197,232,0.07)" stroke="rgba(168,197,232,0.3)" />
        <line x1="20" x2="240" y1="32" y2="32" stroke="rgba(168,197,232,0.3)" />
        <line x1="20" x2="280" y1="50" y2="50" stroke="rgba(168,197,232,0.2)" />
        {/* gauge */}
        <circle cx="260" cy="120" r="36" fill="none" stroke="rgba(168,197,232,0.15)" strokeWidth="5" />
        <path d="M 260 84 A 36 36 0 0 1 296 120" fill="none" stroke="#A8C5E8" strokeWidth="5" strokeLinecap="round" />
        <text x="260" y="125" textAnchor="middle" fontFamily="var(--font-serif)" fontSize="18" fill="#C4DBF0">0.12</text>
      </g>
      {/* passport floating */}
      <g transform="translate(150 60) rotate(8)" style={{ filter: 'drop-shadow(0 24px 40px rgba(0,0,0,0.5))' }}>
        <rect width="220" height="160" rx="8" fill="url(#cv1Pp)" stroke="rgba(220,235,255,0.5)" strokeWidth="1.5" />
        <text x="110" y="40" textAnchor="middle" fontFamily="var(--font-serif)" fontSize="14" fill="rgba(220,235,255,0.7)" letterSpacing="2">PASSPORT</text>
        <circle cx="110" cy="85" r="20" fill="none" stroke="rgba(220,235,255,0.4)" />
        <text x="110" y="135" textAnchor="middle" fontFamily="monospace" fontSize="9" fill="rgba(220,235,255,0.5)">P&lt;AZE ALIYEV&lt;&lt;RAUF</text>
      </g>
    </svg>
  );
  if (kind === 'geology') return (
    <svg viewBox="0 0 600 400" preserveAspectRatio="xMidYMid slice" style={{ width: '100%', height: '100%' }}>
      <defs>
        <linearGradient id="cv2Strata" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="rgba(168,197,232,0.05)" />
          <stop offset="100%" stopColor="rgba(168,197,232,0.25)" />
        </linearGradient>
      </defs>
      <rect width="600" height="400" fill="rgba(12,20,48,0.3)" />
      {/* strata bands */}
      {[60, 110, 160, 210, 260, 310].map((y, i) => (
        <path key={i} d={`M 0 ${y} Q 150 ${y - 15 + (i%2)*30} 300 ${y} T 600 ${y - 10}`}
              stroke={`rgba(168,197,232,${0.15 + i*0.05})`} strokeWidth="1.5" fill="none" />
      ))}
      <path d="M 0 60 Q 150 45 300 60 T 600 50 L 600 360 Q 450 380 300 360 T 0 350 Z" fill="url(#cv2Strata)" opacity="0.4" />
      {/* data points threading */}
      {[[80,90],[180,140],[280,160],[380,210],[470,180],[540,260]].map(([x,y],i) => (
        <g key={i}>
          <circle cx={x} cy={y} r="5" fill="#C4DBF0" />
          <circle cx={x} cy={y} r="12" fill="none" stroke="#A8C5E8" opacity="0.4" />
        </g>
      ))}
      <path d="M 80 90 L 180 140 L 280 160 L 380 210 L 470 180 L 540 260" stroke="#A8C5E8" strokeWidth="1.5" fill="none" strokeDasharray="3 4" />
      <text x="40" y="40" fontFamily="monospace" fontSize="10" fill="rgba(168,197,232,0.6)" letterSpacing="2">SEISMIC · 1987–2024</text>
    </svg>
  );
  if (kind === 'docs') return (
    <svg viewBox="0 0 600 400" preserveAspectRatio="xMidYMid slice" style={{ width: '100%', height: '100%' }}>
      <defs>
        <linearGradient id="cv3Doc" x1="0" x2="1" y1="0" y2="1">
          <stop offset="0%" stopColor="rgba(220,235,255,0.18)" />
          <stop offset="100%" stopColor="rgba(168,197,232,0.05)" />
        </linearGradient>
      </defs>
      {[0,1,2,3,4].map(i => (
        <g key={i} transform={`translate(${180 + i*8} ${80 + i*14}) rotate(${(i-2)*2})`} style={{ filter: 'drop-shadow(0 12px 24px rgba(0,0,0,0.4))' }}>
          <rect width="240" height="220" rx="8" fill="url(#cv3Doc)" stroke="rgba(220,235,255,0.4)" strokeWidth="1.2" />
          <line x1="20" x2="160" y1="36" y2="36" stroke="rgba(168,197,232,0.4)" strokeWidth="1.5" />
          <line x1="20" x2="200" y1="56" y2="56" stroke="rgba(168,197,232,0.25)" />
          <line x1="20" x2="180" y1="72" y2="72" stroke="rgba(168,197,232,0.25)" />
          <line x1="20" x2="200" y1="88" y2="88" stroke="rgba(168,197,232,0.25)" />
          {/* status tag */}
          <rect x="160" y="20" width="60" height="20" rx="10" fill={i===0?'rgba(168,232,197,0.2)':i===1?'rgba(232,212,168,0.15)':'rgba(168,197,232,0.1)'} stroke={i===0?'#A8E8C5':i===1?'#E8D4A8':'rgba(168,197,232,0.3)'} />
          <text x="190" y="34" textAnchor="middle" fontFamily="monospace" fontSize="8" fill={i===0?'#A8E8C5':i===1?'#E8D4A8':'rgba(168,197,232,0.7)'}>
            {i===0?'FAST':i===1?'INV':'STD'}
          </text>
        </g>
      ))}
    </svg>
  );
  return null;
}

function CaseStudy({ index, sector, deployment, region, headline, quote, kind, hue, workflow, built, evaluation, metrics, stack, archKind }) {
  const bg = index % 2 === 0 ? 'base' : 'elevated';
  return (
    <section data-bg={bg} style={{ paddingTop: 'clamp(80px, 14vh, 140px)', paddingBottom: 'clamp(80px, 14vh, 140px)' }}>
      <div className="container">
        {/* Meta strip */}
        <div className="case-meta-strip" style={{
          display: 'flex', alignItems: 'baseline',
          gap: 20, paddingBottom: 24,
          borderBottom: '1px solid var(--border-glass)',
          marginBottom: 48, flexWrap: 'wrap',
        }}>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-tertiary)', letterSpacing: '0.14em' }}>CASE STUDY 0{index + 1} / 03</span>
          <span style={{ width: 1, height: 12, background: 'var(--border-glass)' }} />
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--accent-ice)', letterSpacing: '0.12em' }}>{sector}</span>
          <span style={{ width: 1, height: 12, background: 'var(--border-glass)' }} />
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-secondary)', letterSpacing: '0.12em' }}>REGION · {region.toUpperCase()}</span>
          <span style={{ width: 1, height: 12, background: 'var(--border-glass)' }} />
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-secondary)', letterSpacing: '0.12em' }}>DEPLOY · {deployment.toUpperCase()}</span>
        </div>

        {/* Massive headline */}
        <h2 className="serif case-headline" style={{
          fontSize: 'clamp(48px, 8vw, 120px)',
          letterSpacing: '-0.035em',
          lineHeight: 0.92,
          marginBottom: 48,
          paddingBottom: '0.05em',
          textWrap: 'pretty',
        }}>{headline}</h2>

        {/* Cover */}
        <div className="case-cover" style={{
          borderRadius: 16,
          overflow: 'hidden',
          marginBottom: 64,
          minHeight: 360,
          position: 'relative',
          border: '1px solid var(--border-glass)',
        }}>
          <CaseCover kind={kind} hue={hue} />
        </div>

        {/* Workflow / Built / Eval — stacked editorial sections */}
        <div className="case-section" style={{ marginBottom: 48 }}>
          <div className="case-grid" style={{ display: 'grid', gridTemplateColumns: '180px 1fr', gap: 48, padding: '24px 0', borderTop: '1px solid var(--border-glass)' }}>
            <div className="eyebrow">THE WORKFLOW WE TARGETED</div>
            <p style={{ fontSize: 17, lineHeight: 1.6, color: 'var(--text-primary)', maxWidth: 720, margin: 0 }}>{workflow}</p>
          </div>
          <div className="case-grid" style={{ display: 'grid', gridTemplateColumns: '180px 1fr', gap: 48, padding: '24px 0', borderTop: '1px solid var(--border-glass)' }}>
            <div className="eyebrow">WHAT WE BUILT</div>
            <p style={{ fontSize: 17, lineHeight: 1.6, color: 'var(--text-secondary)', maxWidth: 720, margin: 0 }}>{built}</p>
          </div>
          <div className="case-grid" style={{ display: 'grid', gridTemplateColumns: '180px 1fr', gap: 48, padding: '24px 0', borderTop: '1px solid var(--border-glass)', borderBottom: '1px solid var(--border-glass)' }}>
            <div className="eyebrow">HOW WE EVALUATED IT</div>
            <p style={{ fontSize: 17, lineHeight: 1.6, color: 'var(--text-secondary)', maxWidth: 720, margin: 0 }}>{evaluation}</p>
          </div>
        </div>

        {/* Pull quote moment */}
        <div className="case-pullquote" style={{
          padding: 'clamp(40px, 6vw, 80px) 0',
          margin: '24px 0 56px',
          borderTop: '1px solid var(--border-glass)',
          borderBottom: '1px solid var(--border-glass)',
        }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-tertiary)', letterSpacing: '0.14em', marginBottom: 24 }}>FROM THE CLIENT</div>
          <blockquote className="serif" style={{
            fontStyle: 'italic',
            fontSize: 'clamp(28px, 4.4vw, 64px)',
            lineHeight: 1.1,
            letterSpacing: '-0.025em',
            color: 'var(--text-primary)',
            margin: 0,
            maxWidth: '95%',
          }}>"{quote}"</blockquote>
        </div>

        {/* Outcome metrics — wide hairline-separated row */}
        <div className="case-metrics-row" style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(3, 1fr)',
          borderTop: '1px solid var(--border-glass)',
          borderBottom: '1px solid var(--border-glass)',
          marginBottom: 64,
        }}>
          {metrics.map(([n, l], i) => (
            <div key={l} style={{
              padding: '32px 28px',
              borderLeft: i > 0 ? '1px solid var(--border-glass)' : 'none',
            }}>
              <div className="eyebrow" style={{ marginBottom: 16 }}>OUTCOME 0{i + 1}</div>
              <div className="serif case-metric-num" style={{ fontSize: 'clamp(40px, 5vw, 72px)', color: 'var(--accent-ice)', lineHeight: 1, letterSpacing: '-0.025em' }}>{n}</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--text-tertiary)', marginTop: 14 }}>{l}</div>
            </div>
          ))}
        </div>

        {/* Architecture diagram */}
        <CaseArchitectureFrame archKind={archKind} />

        {/* Stack */}
        <div>
          <div className="eyebrow" style={{ marginBottom: 16 }}>STACK</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {stack.map(s => <span key={s} className="chip">{s}</span>)}
          </div>
        </div>
      </div>
    </section>
  );
}

/* Reveal-driven wrapper for architecture diagrams */
function CaseArchitectureFrame({ archKind }) {
  const ref = useRefW(null);
  const [seen, setSeen] = useStateW(false);
  useEffectW(() => {
    if (!ref.current) return;
    if (typeof IntersectionObserver === 'undefined') { setSeen(true); return; }
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } }, { threshold: 0.15 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return (
    <div ref={ref} style={{ marginBottom: 48 }} className={seen ? 'diagrams-in' : ''}>
      <div className="eyebrow" style={{ marginBottom: 20 }}>ARCHITECTURE</div>
      <div style={{
        padding: 28,
        border: '1px solid var(--border-glass)',
        borderRadius: 12,
        background: 'rgba(168,197,232,0.02)',
        overflow: 'auto',
      }}>
        <CaseArchitecture kind={archKind} />
      </div>
    </div>
  );
}

/* ============================================
   Case study architecture diagrams (3 distinct)
   ============================================ */
function CaseArchitecture({ kind }) {
  if (kind === 'mustari') {
    return (
      <svg viewBox="0 0 1100 320" style={{ width: '100%', height: 'auto', minWidth: 700 }}>
        <text x="20" y="20" fontFamily="monospace" fontSize="10" fill="var(--accent-ice)" letterSpacing="0.12em">MÜŞTƏRİ · KYC PIPELINE · PRIVATE CLOUD</text>
        {/* Pipeline boxes */}
        {[
          { x: 30, y: 140, w: 130, h: 60, l: 'CLIENT API', s: 'mTLS · OAuth' },
          { x: 200, y: 140, w: 130, h: 60, l: 'OCR', s: 'AZ/RU/EN · 247ms' },
          { x: 370, y: 140, w: 130, h: 60, l: 'LIVENESS', s: 'ONNX · in-VPC' },
          { x: 540, y: 140, w: 130, h: 60, l: 'SANCTIONS', s: 'OFAC/EU/UN/AZ', accent: true },
          { x: 710, y: 140, w: 130, h: 60, l: 'RISK MODEL', s: 'GBM + LLM explain' },
          { x: 880, y: 140, w: 180, h: 60, l: 'DOSSIER · WORM', s: 'audit log + sign', accent: true },
        ].map((b, i) => (
          <g key={i}>
            <rect x={b.x} y={b.y} width={b.w} height={b.h} fill={b.accent ? 'rgba(168,197,232,0.1)' : 'rgba(168,197,232,0.04)'} stroke={b.accent ? 'var(--accent-ice)' : 'rgba(168,197,232,0.3)'} strokeWidth="0.8" />
            <text x={b.x + b.w / 2} y={b.y + 26} textAnchor="middle" fontFamily="monospace" fontSize="10" fill="var(--accent-ice)" letterSpacing="0.1em">{b.l}</text>
            <text x={b.x + b.w / 2} y={b.y + 42} textAnchor="middle" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.55)">{b.s}</text>
          </g>
        ))}
        {/* Connectors */}
        {[160, 330, 500, 670, 840].map((x, i) => (
          <line key={i} className="path-draw" data-delay={i + 1} x1={x} y1={170} x2={x + 40} y2={170} stroke="rgba(168,197,232,0.5)" strokeWidth="0.8" markerEnd="url(#arrowM)" />
        ))}
        <defs>
          <marker id="arrowM" viewBox="0 0 8 8" refX="6" refY="4" markerWidth="6" markerHeight="6" orient="auto">
            <path d="M 0 0 L 8 4 L 0 8 z" fill="rgba(168,197,232,0.6)" />
          </marker>
        </defs>
        {/* Async branch — sanctions L2 */}
        <path d="M 605 200 L 605 240 L 540 240 L 540 280 L 1060 280" stroke="rgba(232,212,168,0.5)" strokeWidth="0.6" strokeDasharray="3,3" fill="none" />
        <text x="540" y="262" fontFamily="monospace" fontSize="9" fill="rgba(232,212,168,0.7)" letterSpacing="0.1em">L2 REVIEW · ASYNC</text>
        {/* SLA */}
        <text x="20" y="60" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.5)" letterSpacing="0.1em">END-TO-END SLA · 90s p95</text>
        <text x="20" y="78" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.4)">Throughput · 12k applications/day</text>
        <text x="20" y="96" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.4)">Eval set · 24k labeled · weekly regression</text>
      </svg>
    );
  }
  if (kind === 'neft') {
    return (
      <svg viewBox="0 0 1100 320" style={{ width: '100%', height: 'auto', minWidth: 700 }}>
        <text x="20" y="20" fontFamily="monospace" fontSize="10" fill="var(--accent-ice)" letterSpacing="0.12em">NEFT-AI · HYBRID-SEARCH RAG · ON-PREM</text>
        {/* Index lane */}
        <text x="20" y="56" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.5)" letterSpacing="0.12em">INDEX (BATCH)</text>
        {[
          { x: 30, y: 70, l: 'PDF CORPUS', s: '218k · scanned' },
          { x: 220, y: 70, l: 'OCR + CLEAN', s: 'AZ/RU · post-2018' },
          { x: 410, y: 70, l: 'CHUNK + EMBED', s: 'multilingual · 1024d', accent: true },
          { x: 600, y: 70, l: 'pgvector', s: 'CMK · WORM' },
        ].map((b, i) => (
          <g key={i}>
            <rect x={b.x} y={b.y} width={150} height={50} fill={b.accent ? 'rgba(168,197,232,0.1)' : 'rgba(168,197,232,0.04)'} stroke={b.accent ? 'var(--accent-ice)' : 'rgba(168,197,232,0.3)'} strokeWidth="0.8" />
            <text x={b.x + 75} y={b.y + 22} textAnchor="middle" fontFamily="monospace" fontSize="10" fill="var(--accent-ice)" letterSpacing="0.1em">{b.l}</text>
            <text x={b.x + 75} y={b.y + 38} textAnchor="middle" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.55)">{b.s}</text>
          </g>
        ))}
        {[180, 370, 560].map((x, i) => (
          <line key={i} className="path-draw" data-delay={i + 1} x1={x} y1={95} x2={x + 40} y2={95} stroke="rgba(168,197,232,0.5)" strokeWidth="0.8" markerEnd="url(#arrowN)" />
        ))}

        {/* Query lane */}
        <text x="20" y="170" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.5)" letterSpacing="0.12em">QUERY (REAL-TIME)</text>
        {[
          { x: 30, y: 184, l: 'GEOLOGIST', s: 'NL query · AZ/RU/EN' },
          { x: 220, y: 184, l: 'BM25 · VECTOR', s: 'top-50 each', accent: true },
          { x: 410, y: 184, l: 'RERANK', s: 'cross-encoder · top-14' },
          { x: 600, y: 184, l: 'LLM ANSWER', s: 'cited · refusal-aware' },
          { x: 790, y: 184, l: 'CITATIONS', s: 'pdf · page-anchored' },
        ].map((b, i) => (
          <g key={i}>
            <rect x={b.x} y={b.y} width={150} height={50} fill={b.accent ? 'rgba(168,197,232,0.1)' : 'rgba(168,197,232,0.04)'} stroke={b.accent ? 'var(--accent-ice)' : 'rgba(168,197,232,0.3)'} strokeWidth="0.8" />
            <text x={b.x + 75} y={b.y + 22} textAnchor="middle" fontFamily="monospace" fontSize="10" fill="var(--accent-ice)" letterSpacing="0.1em">{b.l}</text>
            <text x={b.x + 75} y={b.y + 38} textAnchor="middle" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.55)">{b.s}</text>
          </g>
        ))}
        {[180, 370, 560, 750].map((x, i) => (
          <line key={i} className="path-draw" data-delay={i + 2} x1={x} y1={209} x2={x + 40} y2={209} stroke="rgba(168,197,232,0.5)" strokeWidth="0.8" markerEnd="url(#arrowN)" />
        ))}
        {/* Retrieval -> Index */}
        <line x1="295" y1="184" x2="295" y2="120" stroke="rgba(168,197,232,0.4)" strokeWidth="0.6" strokeDasharray="3,3" />
        <text x="305" y="155" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.55)">retrieve</text>

        <defs>
          <marker id="arrowN" viewBox="0 0 8 8" refX="6" refY="4" markerWidth="6" markerHeight="6" orient="auto">
            <path d="M 0 0 L 8 4 L 0 8 z" fill="rgba(168,197,232,0.6)" />
          </marker>
        </defs>
        <text x="20" y="280" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.5)" letterSpacing="0.1em">P95 LATENCY · 2.6s · CORPUS · 40 YEARS</text>
        <text x="20" y="296" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.4)">EVAL · 320 expert-graded queries · weekly</text>
      </svg>
    );
  }
  if (kind === 'sigorta') {
    return (
      <svg viewBox="0 0 1100 320" style={{ width: '100%', height: 'auto', minWidth: 700 }}>
        <text x="20" y="20" fontFamily="monospace" fontSize="10" fill="var(--accent-ice)" letterSpacing="0.12em">SIĞORTA · CLAIMS TRIAGE · PRIVATE CLOUD</text>
        {/* Inputs row */}
        {[
          { x: 30, y: 60, l: 'CLAIM PDF', s: 'scanned · AZ' },
          { x: 30, y: 140, l: 'POLICY DB', s: 'RDBMS · CMK' },
          { x: 30, y: 220, l: 'PROVIDER GRAPH', s: 'historical · 8yr' },
        ].map((b, i) => (
          <g key={i}>
            <rect x={b.x} y={b.y} width={140} height={50} fill="rgba(168,197,232,0.04)" stroke="rgba(168,197,232,0.3)" strokeWidth="0.8" />
            <text x={b.x + 70} y={b.y + 22} textAnchor="middle" fontFamily="monospace" fontSize="10" fill="var(--accent-ice)" letterSpacing="0.1em">{b.l}</text>
            <text x={b.x + 70} y={b.y + 38} textAnchor="middle" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.55)">{b.s}</text>
          </g>
        ))}

        {/* Processors */}
        {[
          { x: 230, y: 60, l: 'NER · AZ MEDICAL', s: 'ICD + dates + names', accent: true },
          { x: 230, y: 140, l: 'POLICY RAG', s: 'contract Q&A' },
          { x: 230, y: 220, l: 'GRAPH FRAUD', s: 'clique scoring', accent: true },
        ].map((b, i) => (
          <g key={i}>
            <rect x={b.x} y={b.y} width={170} height={50} fill={b.accent ? 'rgba(168,197,232,0.1)' : 'rgba(168,197,232,0.04)'} stroke={b.accent ? 'var(--accent-ice)' : 'rgba(168,197,232,0.3)'} strokeWidth="0.8" />
            <text x={b.x + 85} y={b.y + 22} textAnchor="middle" fontFamily="monospace" fontSize="10" fill="var(--accent-ice)" letterSpacing="0.1em">{b.l}</text>
            <text x={b.x + 85} y={b.y + 38} textAnchor="middle" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.55)">{b.s}</text>
          </g>
        ))}

        {/* Connectors from inputs to processors */}
        {[60, 140, 220].map((y, i) => (
          <line key={i} className="path-draw" data-delay={i + 1} x1={170} y1={y + 25} x2={230} y2={y + 25} stroke="rgba(168,197,232,0.5)" strokeWidth="0.8" markerEnd="url(#arrowS)" />
        ))}

        {/* Triage router */}
        <rect x="450" y="120" width="160" height="80" fill="rgba(168,197,232,0.12)" stroke="var(--accent-ice)" strokeWidth="1.2" />
        <text x="530" y="148" textAnchor="middle" fontFamily="monospace" fontSize="11" fill="var(--accent-ice-bright)" letterSpacing="0.12em">TRIAGE ROUTER</text>
        <text x="530" y="164" textAnchor="middle" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.55)">policy + extraction + fraud</text>
        <text x="530" y="180" textAnchor="middle" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.55)">→ queue</text>

        {/* Connectors to router */}
        {[85, 165, 245].map((y, i) => (
          <line key={i} className="path-draw" data-delay={i + 2} x1={400} y1={y} x2={450} y2={155} stroke="rgba(168,197,232,0.5)" strokeWidth="0.8" markerEnd="url(#arrowS)" />
        ))}

        {/* Output queues */}
        {[
          { y: 60, l: 'FAST-TRACK', c: '#A8E8C5' },
          { y: 130, l: 'STANDARD', c: 'var(--accent-ice)' },
          { y: 200, l: 'INVESTIGATE', c: '#E8A8B5' },
        ].map((b, i) => (
          <g key={i}>
            <rect x="680" y={b.y} width="160" height="50" fill={`${b.c === 'var(--accent-ice)' ? 'rgba(168,197,232,0.04)' : 'rgba(168,197,232,0.04)'}`} stroke={b.c} strokeWidth="1" />
            <text x="760" y={b.y + 30} textAnchor="middle" fontFamily="monospace" fontSize="11" fill={b.c} letterSpacing="0.14em">{b.l}</text>
          </g>
        ))}
        {/* router -> queues */}
        {[85, 155, 225].map((y, i) => (
          <line key={i} className="path-draw" data-delay={i + 3} x1={610} y1="160" x2={680} y2={y} stroke="rgba(168,197,232,0.4)" strokeWidth="0.8" markerEnd="url(#arrowS)" />
        ))}

        {/* Audit log */}
        <rect x="900" y="120" width="180" height="80" fill="rgba(168,197,232,0.04)" stroke="rgba(168,197,232,0.3)" strokeWidth="0.8" strokeDasharray="3,2" />
        <text x="990" y="150" textAnchor="middle" fontFamily="monospace" fontSize="10" fill="var(--accent-ice)" letterSpacing="0.12em">AUDIT LOG</text>
        <text x="990" y="166" textAnchor="middle" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.5)">WORM · regulator-ready</text>
        <line x1="840" y1="160" x2="900" y2="160" stroke="rgba(168,197,232,0.4)" strokeWidth="0.6" strokeDasharray="3,2" />

        <defs>
          <marker id="arrowS" viewBox="0 0 8 8" refX="6" refY="4" markerWidth="6" markerHeight="6" orient="auto">
            <path d="M 0 0 L 8 4 L 0 8 z" fill="rgba(168,197,232,0.6)" />
          </marker>
        </defs>

        <text x="20" y="296" fontFamily="monospace" fontSize="9" fill="rgba(168,197,232,0.5)" letterSpacing="0.1em">EVAL · 4,200 historical claims · stratified by sub-line · weekly regression</text>
      </svg>
    );
  }
  return null;
}

function WorkPageBody() {
  const cases = [
    {
      sector: 'BANKING', deployment: 'Private cloud', region: 'Azerbaijan', kind: 'passport', archKind: 'mustari', hue: 215,
      headline: <>From five days to <em style={{ color: 'var(--accent-ice)', fontStyle: 'italic' }}>ninety seconds.</em></>,
      quote: 'The compliance team stopped being a bottleneck and started being strategic.',
      workflow: 'Retail account opening: applicants submit a passport, a utility bill, and salary statements via the bank\'s mobile app or branch tablets. The compliance reviewer must run identity verification, sanctions screening across four lists, and income validation — historically a 3-to-5-day manual cycle ending in a binary approve/reject.',
      built: 'Müştəri ingests the document set in Azerbaijani, Russian, or English. Multilingual OCR + named-entity extraction emits structured fields; a liveness check runs in-VPC; sanctions screening hits OFAC SDN, EU Consolidated, UN, and the AZ MFA watchlist; a gradient-boosted risk model produces a calibrated score, and an LLM-driven explainer writes the audit-grade dossier — all signed and persisted to WORM storage.',
      evaluation: 'Eval set: 24,000 labeled historical applications stratified by branch, applicant cohort, and document quality. Edge buckets explicitly tested: torn pages, low-light selfies, fuzzy-match sanctions hits, and Russian-only utility bills. We track p95 latency and false-clear rate weekly; every release runs the full regression before deployment.',
      metrics: [['90s', 'p95 processing time'], ['12k', 'Apps/day capacity'], ['94%', 'Compliance accuracy']],
      stack: ['Multilingual OCR', 'Liveness ONNX', 'Sanctions API', 'Azure private cloud', 'Postgres', 'Customer-managed keys'],
    },
    {
      sector: 'OIL & GAS', deployment: 'On-premise', region: 'Azerbaijan', kind: 'geology', archKind: 'neft', hue: 210,
      headline: <>Forty years of seismic data, <em style={{ color: 'var(--accent-ice)', fontStyle: 'italic' }}>queryable in seconds.</em></>,
      quote: 'What used to take three geologists a week now takes one prompt.',
      workflow: 'Exploration geologists answer questions like "show all wells in the Bakı-Şamaxı block with H₂S readings above 200 ppm" by manually opening scanned reports — 40 years of seismic surveys, well logs, and geological assessments split across Russian and Azerbaijani PDFs. The answer typically takes a senior geologist 2-3 days of archive work and is rarely fully complete.',
      built: 'Neft-AI is a hybrid-search RAG agent built on the client\'s on-premise infrastructure. Multilingual embeddings + BM25 over 218k documents, with custom PDF parsing for pre-2010 scans. Cross-encoder reranks the top-50 down to top-14; a refusal-aware LLM answers with page-anchored citations back to the original PDF.',
      evaluation: 'We built a 320-query benchmark, expert-graded by senior geologists across four sub-domains: well logs, seismic interpretation, production decline, and HSE history. Pass criterion: relevance + factual grounding + correct citation. New model versions ship only after matching or exceeding the previous version on every sub-domain.',
      metrics: [['2.6s', 'p95 query latency'], ['40yr', 'Corpus indexed'], ['218k', 'Documents in scope']],
      stack: ['Multilingual embeddings', 'BM25 + vector', 'Custom PDF parsing', 'pgvector on-prem', 'Cross-encoder rerank', 'CMK encryption'],
    },
    {
      sector: 'INSURANCE', deployment: 'Private cloud', region: 'Azerbaijan', kind: 'docs', archKind: 'sigorta', hue: 220,
      headline: <>Triage in minutes. <em style={{ color: 'var(--accent-ice)', fontStyle: 'italic' }}>Fraud signals nobody saw before.</em></>,
      quote: 'We started catching patterns the manual process had been missing for years.',
      workflow: 'Life insurance claims arrive as scanned hospital records and handwritten Azerbaijani forms. The claims team manually extracts policy numbers, beneficiary details, and medical cause-of-event, then cross-references each claim against the policy contract — work that historically took weeks of triage and routinely missed fraud signals across providers.',
      built: 'Sığorta extracts structured claim data with a custom Azerbaijani-medical NER trained on a domain corpus. A policy-contract RAG agent verifies coverage against the underlying contract clauses; a graph fraud detector scores claimant/provider relationships against an 8-year history. A triage router emits one of three queues — fast-track, standard, or investigation — with full reasoning preserved in the audit log.',
      evaluation: 'We held out 4,200 historical claims, stratified by sub-line of business and severity, then back-tested the triage router against the human reviewers\' final decisions. We measure decision concordance, time-to-route, and fraud-signal recall against an investigator-validated subset. The graph-fraud component is re-evaluated every quarter as the provider graph evolves.',
      metrics: [['76%', 'Faster triage'], ['99.2%', 'Extraction accuracy'], ['Top-3', 'Az. insurer deployed']],
      stack: ['Custom NER (Az medical)', 'RAG over policies', 'Graph fraud detection', 'Private cloud · CMK', 'WORM audit log'],
    },
  ];
  return (
    <>
      <PageHeader
        eyebrow="WORK — CASE STUDIES"
        title={<>Three deployments. <em style={{ color: 'var(--accent-ice)', fontStyle: 'italic' }}>Three industries.</em></>}
        lead="What it actually takes to get an AI agent past pilot and into a regulated production environment."
      />
      {cases.map((c, i) => <CaseStudy key={i} index={i} {...c} />)}
    </>
  );
}

Object.assign(window, { CaseStudy, WorkPageBody });
