/* global React */
const { useState: useStateP, useEffect: useEffectP, useRef: useRefP } = React;

/* ============================================
   Shared internal-page section header
   ============================================ */
function PageHeader({ eyebrow, title, lead }) {
  return (
    <section style={{ paddingTop: 'clamp(140px, 22vh, 200px)', paddingBottom: 80 }}>
      <div className="container">
        <div className="eyebrow" style={{ marginBottom: 24 }}>{eyebrow}</div>
        <h1 className="serif hero-h1" style={{
          fontSize: 'clamp(56px, 9vw, 128px)',
          lineHeight: 0.98,
          letterSpacing: '-0.03em',
          marginBottom: 32,
          paddingBottom: '0.06em',
          maxWidth: 1100,
          textWrap: 'balance',
        }}>{title}</h1>
        {lead && <p style={{ fontSize: 19, lineHeight: 1.55, color: 'var(--text-secondary)', maxWidth: 680 }}>{lead}</p>}
      </div>
    </section>
  );
}

/* ============================================
   AGENT SECTION — alternating problem/solution
   ============================================ */
function AgentSection({ index, sector, status, name, problem, solution, metrics, stack, mockup, hue, deployment = 'PRIVATE CLOUD' }) {
  const reverse = index % 2 === 1;
  const bg = index % 2 === 0 ? 'base' : 'elevated';
  return (
    <section data-bg={bg} style={{ paddingTop: 'clamp(80px, 14vh, 140px)', paddingBottom: 'clamp(80px, 14vh, 140px)', position: 'relative', overflow: 'hidden' }}>
      <div className="container">
        {/* Section index marker + sector + status meta strip */}
        <div className="agent-meta-strip" style={{
          display: 'flex',
          alignItems: 'baseline',
          gap: 24,
          paddingBottom: 20,
          borderBottom: '1px solid var(--border-glass)',
          marginBottom: 36,
          flexWrap: 'wrap',
        }}>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-tertiary)', letterSpacing: '0.14em' }}>
            AGENT 0{index + 1} / 06
          </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: status === 'PRODUCTION' ? '#A8E8C5' : '#E8D4A8', letterSpacing: '0.12em' }}>STATUS · {status}</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}</span>
        </div>

        {/* 200px name moment */}
        <h2 className="serif agent-name-moment" style={{
          fontSize: 'clamp(72px, 14vw, 200px)',
          lineHeight: 0.92,
          letterSpacing: '-0.04em',
          marginBottom: 56,
          paddingBottom: '0.05em',
          color: 'var(--text-primary)',
          margin: 0,
          textWrap: 'pretty',
        }}>{name}</h2>

        {/* Hairline separator */}
        <div style={{ height: 1, background: 'var(--border-glass)', margin: '0 0 56px' }} />

        {/* Body grid: text + mockup */}
        <div className="agent-row" style={{
          display: 'grid',
          gridTemplateColumns: '1fr 1fr',
          gap: 80,
          alignItems: 'flex-start',
          direction: reverse ? 'rtl' : 'ltr',
          marginBottom: 64,
        }}>
          <div style={{ direction: 'ltr' }}>
            <div style={{ marginBottom: 32 }}>
              <div className="eyebrow" style={{ marginBottom: 12 }}>THE PROBLEM</div>
              <p style={{ fontSize: 17, lineHeight: 1.55, color: 'var(--text-secondary)' }}>{problem}</p>
            </div>
            <div style={{ marginBottom: 0 }}>
              <div className="eyebrow" style={{ marginBottom: 12 }}>OUR AGENT</div>
              <p style={{ fontSize: 17, lineHeight: 1.55, color: 'var(--text-primary)' }}>{solution}</p>
            </div>
          </div>

          <div style={{ direction: 'ltr', position: 'relative' }}>
            <div aria-hidden="true" style={{
              position: 'absolute',
              inset: '-12%',
              background: `radial-gradient(ellipse, hsla(${hue}, 60%, 70%, 0.18), transparent 60%)`,
              pointerEvents: 'none',
            }} />
            <div style={{ position: 'relative', display: 'flex', justifyContent: 'center' }}>
              {mockup}
            </div>
          </div>
        </div>

        {/* Hairline-separated metrics row */}
        <div className="agent-metrics-row" style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(3, 1fr)',
          borderTop: '1px solid var(--border-glass)',
          borderBottom: '1px solid var(--border-glass)',
          marginBottom: 36,
        }}>
          {metrics.map((m, i) => (
            <div key={m} style={{
              padding: '24px 28px',
              borderLeft: i > 0 ? '1px solid var(--border-glass)' : 'none',
            }}>
              <div className="eyebrow" style={{ marginBottom: 10 }}>OUTCOME 0{i + 1}</div>
              <div className="serif agent-metric-num" style={{ fontSize: 'clamp(22px, 2.4vw, 32px)', lineHeight: 1.1, letterSpacing: '-0.015em', color: 'var(--accent-ice-bright)' }}>{m}</div>
            </div>
          ))}
        </div>

        {/* Stack chips + CTA */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 24 }}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {stack.map(s => <span key={s} className="chip">{s}</span>)}
          </div>
          <a href="Work.html" className="interactive" style={{
            fontFamily: 'var(--font-mono)',
            fontSize: 12,
            textTransform: 'uppercase',
            letterSpacing: '0.12em',
            color: 'var(--accent-ice)',
            borderBottom: '1px solid var(--accent-ice)',
            paddingBottom: 4,
          }}>View case study →</a>
        </div>
      </div>
    </section>
  );
}

function AgentsPageBody() {
  const { MockKYC, MockClaims, MockNeft, MockEnerji, MockFintex, MockVizual } = window;
  const sections = [
    {
      sector: 'BANKING', status: 'PRODUCTION', deployment: 'PRIVATE CLOUD', hue: 215,
      name: 'Müştəri',
      problem: 'Retail banks in Azerbaijan process tens of thousands of new account applications monthly. Manual KYC review takes 3–5 days, document quality is inconsistent, and compliance teams burn out reviewing the same risk patterns over and over.',
      solution: 'Müştəri ingests passport scans, utility bills, and salary statements in Azerbaijani, Russian, and English. It runs liveness-checked face matching, screens against OFAC, EU, and local sanctions lists, and produces a risk-scored compliance dossier in under 90 seconds.',
      metrics: ['87% faster onboarding', '94% compliance accuracy', '12k applications/day capacity'],
      stack: ['Multilingual OCR', 'Liveness detection', 'Sanctions API', 'Azure'],
      mockup: <MockKYC />,
    },
    {
      sector: 'INSURANCE', status: 'PRODUCTION', deployment: 'PRIVATE CLOUD', hue: 220,
      name: 'Sığorta',
      problem: 'Life insurance claims arrive as a mess of PDFs, scanned hospital records, and handwritten Azerbaijani-language forms. Manual triage takes weeks, fraud signals get missed, and legitimate claimants wait while their files sit in queues.',
      solution: 'Sığorta extracts policy numbers, beneficiary details, and medical cause-of-event from hospital documents in Azerbaijani. It cross-references each claim against the underlying policy contract, flags fraud signals, and routes claims into fast-track, standard, or investigation queues.',
      metrics: ['76% faster triage', '99.2% extraction accuracy', 'Deployed at a top-3 Azerbaijani insurer'],
      stack: ['Custom NER (Az medical)', 'RAG over policies', 'Graph fraud detection'],
      mockup: <MockClaims />,
    },
    {
      sector: 'OIL & GAS', status: 'PRODUCTION', deployment: 'ON-PREMISE', hue: 210,
      name: 'Neft-AI',
      problem: 'SOCAR and its partners hold four decades of seismic reports, well logs, and geological surveys — most of it scanned, much of it in Russian and Azerbaijani. Exploration geologists spend days searching documents that should take seconds to query.',
      solution: 'Neft-AI is a RAG agent over a 40-year corpus. It answers natural-language queries like "show all wells in the Bakı-Şamaxı block with H2S readings above 200ppm" in seconds, with citations to the original PDF page.',
      metrics: ['40-year corpus indexed', 'Sub-3s query latency', 'Used by exploration teams'],
      stack: ['Multilingual embeddings', 'Hybrid search (BM25+vector)', 'Custom PDF parsing'],
      mockup: <MockNeft />,
    },
    {
      sector: 'ENERGY', status: 'PILOT', deployment: 'PRIVATE CLOUD', hue: 225,
      name: 'Enerji',
      problem: "Grid operators need accurate 72-hour-ahead hourly load forecasts to balance supply, schedule maintenance, and integrate growing renewable generation. Traditional forecasting underweights weather variance and can't see solar farm output without ground sensors.",
      solution: 'Enerji combines a time-series transformer with weather feeds and a computer vision component that estimates solar farm output from satellite imagery. It produces hourly forecasts 72 hours ahead with calibrated uncertainty bands.',
      metrics: ['8% forecast error reduction', '72-hour horizon', 'Reduced grid balancing costs'],
      stack: ['Temporal Fusion Transformer', 'Satellite CV', 'MLflow on Kubernetes'],
      mockup: <MockEnerji />,
    },
    {
      sector: 'FINTECH', status: 'PRODUCTION', deployment: 'PRIVATE CLOUD', hue: 230,
      name: 'Fintex',
      problem: 'Card-not-present fraud and account-takeover attempts spike during peak retail seasons. Risk teams need decisions in milliseconds and explanations that audit committees and regulators can actually inspect.',
      solution: 'Fintex makes sub-50ms fraud decisions by combining a graph-based behavioral model with an LLM-driven explanation layer. Every block comes with a human-readable reason, every approval comes with a trace.',
      metrics: ['<50ms decision latency', '8M transactions/day', 'In production at a regional payment processor'],
      stack: ['GNN behavioral model', 'LLM explanation layer', 'Redis + Kafka'],
      mockup: <MockFintex />,
    },
    {
      sector: 'INDUSTRIAL CV', status: 'PILOT', deployment: 'EDGE · AIR-GAPPED', hue: 205,
      name: 'Vizual',
      problem: 'Pipeline inspection, manufacturing quality assurance, and infrastructure monitoring all rely on humans staring at hours of footage. Defects get missed, inspections get expensive, and post-incident reviews are limited by how much footage anyone actually watched.',
      solution: "Vizual runs on edge devices alongside industrial cameras, flags anomalies in real time, and generates inspector-ready reports with timestamped evidence. It's audit-ready and deployable in air-gapped environments.",
      metrics: ['Edge-deployable', 'Air-gapped capable', 'Auto-generated reports'],
      stack: ['YOLO-based detection', 'ONNX runtime', 'Inspector report generator'],
      mockup: <MockVizual />,
    },
  ];
  return (
    <>
      <PageHeader
        eyebrow="AGENTS — IN PRODUCTION"
        title={<>Six agents. <em style={{ color: 'var(--accent-ice)', fontStyle: 'italic' }}>Every one</em> deployed.</>}
        lead="Each agent solves one operational problem in one regulated industry, in the languages our clients actually speak."
      />
      {sections.map((s, i) => <AgentSection key={s.name} index={i} {...s} />)}
    </>
  );
}

Object.assign(window, { PageHeader, AgentsPageBody });
