// diagrams.jsx — five coded SVG diagrams, one visual system
// All use theme tokens (var(--rs-...)) so they adapt to dark/light.

const { useEffect, useRef, useState } = React;

// =================================================================
// 1) FLYWHEEL — Device → Data → AI → Monetization
// =================================================================
function Flywheel({ size = 560 }) {
  const nodes = [
    { label: 'Device',      sub: 'Network',       n: '01', a: -90 },
    { label: 'Data',        sub: 'Acquisition',   n: '02', a: 0 },
    { label: 'AI',          sub: 'Optimization',  n: '03', a: 90 },
    { label: 'Continuous',  sub: 'Monetization',  n: '04', a: 180 },
  ];
  const cx = 260, cy = 260, r = 180, nr = 34;
  const pt = (a, rad = r) => [cx + rad * Math.cos((a - 90) * Math.PI / 180), cy + rad * Math.sin((a - 90) * Math.PI / 180)];
  const [activeIdx, setActiveIdx] = useState(null);
  // label positioning per quadrant (anchor + dx/dy offsets from node center)
  const labelPos = [
    { anchor: 'middle', dx:  0, dy: -58 }, // top
    { anchor: 'start',  dx: 52, dy:   0 }, // right
    { anchor: 'middle', dx:  0, dy:  70 }, // bottom
    { anchor: 'end',    dx: -52, dy:  0 }, // left
  ];

  return (
    <svg className="dg dg-flywheel" viewBox="0 0 520 520" fill="none" aria-label="Commercial flywheel">
      <defs>
        <marker id="dgArrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="8" markerHeight="8" orient="auto">
          <path d="M0 0 L10 5 L0 10 Z" fill="var(--rs-red)"/>
        </marker>
        <filter id="dgGlow" x="-50%" y="-50%" width="200%" height="200%">
          <feGaussianBlur stdDeviation="6" result="b"/>
          <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
        </filter>
      </defs>

      {/* rings */}
      <circle cx={cx} cy={cy} r={r} stroke="var(--rs-hairline)" strokeWidth="1"/>
      <circle cx={cx} cy={cy} r={r - 24} stroke="var(--rs-hairline)" strokeWidth="1" strokeDasharray="2 8" opacity="0.6"/>

      {/* moving red spark */}
      <circle cx={cx} cy={cy} r={r} stroke="var(--rs-red)" strokeWidth="2" strokeDasharray="4 1252" strokeLinecap="round">
        <animate attributeName="stroke-dashoffset" values="0;-1256" dur="10s" repeatCount="indefinite"/>
      </circle>

      {/* connecting arcs */}
      {nodes.map((_, i) => {
        const a1 = nodes[i].a, a2 = nodes[(i + 1) % 4].a;
        const p1 = pt(a1 + 12), p2 = pt(a2 - 12);
        return (
          <path key={i} d={`M ${p1[0]} ${p1[1]} A ${r} ${r} 0 0 1 ${p2[0]} ${p2[1]}`}
                stroke="var(--rs-hairline-2)" strokeWidth="1" fill="none" markerEnd="url(#dgArrow)"/>
        );
      })}

      {/* center */}
      <g textAnchor="middle" fontFamily="JetBrains Mono" fontSize="10" letterSpacing="3" fill="var(--rs-gray-1)">
        <text x={cx} y={cy - 6}>THE</text>
      </g>
      <text x={cx} y={cy + 14} textAnchor="middle" fontFamily="Space Grotesk" fontSize="20" fontWeight="600" fill="var(--rs-red)" letterSpacing="2">FLYWHEEL</text>

      {/* nodes */}
      {nodes.map((n, i) => {
        const [nx, ny] = pt(n.a);
        const active = activeIdx === i;
        const lp = labelPos[i];
        return (
          <g key={i}
             onMouseEnter={() => setActiveIdx(i)} onMouseLeave={() => setActiveIdx(null)}
             style={{ cursor: 'pointer' }}>
            <g transform={`translate(${nx}, ${ny})`}>
              <circle r={nr + 6} fill="var(--rs-ink)" opacity={active ? 1 : 0}/>
              <circle r={nr} fill="var(--rs-ink)" stroke="var(--rs-red)" strokeWidth={active ? 2 : 1.5}
                      filter={active ? 'url(#dgGlow)' : undefined}/>
              <text y="-3" textAnchor="middle" fontFamily="Space Grotesk" fontSize="20" fontWeight="600"
                    fill="var(--rs-red)" letterSpacing="1">{n.n}</text>
              <text y="14" textAnchor="middle" fontFamily="JetBrains Mono" fontSize="8" letterSpacing="2"
                    fill="var(--rs-gray-2)">NODE</text>
            </g>
            <g transform={`translate(${nx + lp.dx}, ${ny + lp.dy})`}>
              <text textAnchor={lp.anchor} fontFamily="Space Grotesk" fontSize="15" fontWeight="600"
                    fill="var(--rs-white)">{n.label}</text>
              <text y="17" textAnchor={lp.anchor} fontFamily="Inter" fontSize="12.5"
                    fill={active ? 'var(--rs-red)' : 'var(--rs-cream)'}>{n.sub}</text>
            </g>
          </g>
        );
      })}
    </svg>
  );
}

// =================================================================
// 2) PLATFORM LAYER STACK — 4 layers
// =================================================================
function LayerStack() {
  const layers = [
    { n: '04', label: 'Applications & Monetization', sub: 'NOVA AI · content · commerce · lifecycle services',           accent: true },
    { n: '03', label: 'AI Engine',                   sub: 'Generative AI, optimization, targeting, measurement' },
    { n: '02', label: 'Edge & Data Layer',           sub: 'On-device compute, privacy-first collection, normalization' },
    { n: '01', label: 'Terminal Layer',              sub: 'Smart terminals, screens, nodes, robotics, sensors' },
  ];
  const [hov, setHov] = useState(null);
  return (
    <div className="dg-stack">
      {layers.map((l, i) => (
        <div key={l.n}
             className={'dg-stack__layer' + (l.accent ? ' is-accent' : '') + (hov === i ? ' is-hov' : '')}
             onMouseEnter={() => setHov(i)}
             onMouseLeave={() => setHov(null)}>
          <div className="dg-stack__layer-num">{l.n}</div>
          <div className="dg-stack__layer-body">
            <div className="dg-stack__layer-label">{l.label}</div>
            <div className="dg-stack__layer-sub">{l.sub}</div>
          </div>
          <div className="dg-stack__layer-marks" aria-hidden="true">
            <span/><span/><span/><span/><span/><span/><span/><span/>
          </div>
        </div>
      ))}
      <div className="dg-stack__axis" aria-hidden="true">
        <span>Physical</span>
        <span>Digital</span>
      </div>
    </div>
  );
}

// =================================================================
// 3) THREE-TIER DISTRIBUTION — Node / Sentry / Cavalry
// =================================================================
function ThreeTier() {
  const tiers = [
    { n: 'I',   label: 'Node Layer',     desc: 'Fixed physical endpoints — screens, terminals, kiosks',  count: 'Thousands',     dots: 28, density: 'dense' },
    { n: 'II',  label: 'Sentry Layer',   desc: 'Scheduled deployments — campaigns, activations, pop-ups', count: 'Hundreds',     dots: 12, density: 'mid' },
    { n: 'III', label: 'Cavalry Layer',  desc: 'Mobile robotic units — sweeping coverage, event bursts', count: 'Dozens',       dots: 4,  density: 'sparse' },
  ];
  return (
    <div className="dg-tier">
      {tiers.map((t, i) => (
        <div key={t.n} className={'dg-tier__col dg-tier__col--' + t.density}>
          <div className="dg-tier__hdr">
            <span className="dg-tier__roman">{t.n}</span>
            <div>
              <div className="dg-tier__label">{t.label}</div>
              <div className="dg-tier__count">{t.count}</div>
            </div>
          </div>
          <p className="dg-tier__desc">{t.desc}</p>
          <div className="dg-tier__matrix" aria-hidden="true">
            {Array.from({ length: t.dots }).map((_, j) => (
              <span key={j} style={{ animationDelay: (j * 120) + 'ms' }}/>
            ))}
          </div>
        </div>
      ))}
      <div className="dg-tier__axis" aria-hidden="true">
        <div>Fixed ↔ Mobile</div>
        <div>Continuous ↔ Burst</div>
      </div>
    </div>
  );
}

// =================================================================
// 4) EXPANSION MAP — Middle East → GCC → Europe → NA
// =================================================================
function ExpansionMap() {
  // rough normalized coords on a 1000x500 cylindrical-ish canvas
  // labelSide controls which side the callout sits on so neighbors don't collide
  // tier 'operating' = in-market entity / second site; 'network' = commercial centres in the platform's network scope
  // Coordinates are stylised (not pixel-accurate cartographic projection)
  // but compass directions and rough relative positions are kept faithful.
  // tier 'hub' = mega city, larger dot, anchors the regional constellation.
  // tier 'network' = supporting commercial centre, smaller dot.
  const points = [
    // Middle East
    { x: 625, y: 278, city: 'Riyadh',         region: 'KSA · HQ',          tier: 'hub',     active: true, labelSide: 'right' },
    { x: 598, y: 290, city: 'Jeddah',         region: 'KSA · second site', tier: 'network',               labelSide: 'left'  },
    { x: 655, y: 270, city: 'Dubai',          region: 'UAE',               tier: 'network',               labelSide: 'right' },
    { x: 645, y: 272, city: 'Doha',           region: 'Qatar',             tier: 'network',               labelSide: 'right' },
    { x: 630, y: 250, city: 'Kuwait City',    region: 'Kuwait',            tier: 'network',               labelSide: 'right' },
    { x: 635, y: 260, city: 'Manama',         region: 'Bahrain',           tier: 'network',               labelSide: 'right' },
    { x: 685, y: 282, city: 'Muscat',         region: 'Oman',              tier: 'network',               labelSide: 'right' },
    // EU + Türkiye
    { x: 470, y: 142, city: 'London',         region: 'UK',                tier: 'hub',                   labelSide: 'left'  },
    { x: 490, y: 160, city: 'Paris',          region: 'France',            tier: 'hub',                   labelSide: 'left'  },
    { x: 510, y: 128, city: 'Berlin',         region: 'Germany',           tier: 'hub',                   labelSide: 'right' },
    { x: 540, y: 182, city: 'Istanbul',       region: 'Türkiye',           tier: 'network',               labelSide: 'right' },
    { x: 512, y: 186, city: 'Rome',           region: 'Italy',             tier: 'network',               labelSide: 'right' },
    { x: 458, y: 198, city: 'Madrid',         region: 'Spain',             tier: 'network',               labelSide: 'left'  },
    // North America
    { x: 252, y: 170, city: 'New York',       region: 'USA',               tier: 'hub',                   labelSide: 'right' },
    { x: 130, y: 195, city: 'San Francisco',  region: 'USA',               tier: 'hub',                   labelSide: 'left'  },
    { x: 264, y: 160, city: 'Boston',         region: 'USA',               tier: 'network',               labelSide: 'right' },
    { x: 212, y: 167, city: 'Chicago',        region: 'USA',               tier: 'network',               labelSide: 'left'  },
    { x: 236, y: 158, city: 'Toronto',        region: 'Canada',            tier: 'network',               labelSide: 'left'  },
    { x: 130, y: 130, city: 'Vancouver',      region: 'Canada',            tier: 'network',               labelSide: 'left'  },
    // Asia · Pacific
    { x: 868, y: 232, city: 'Hong Kong',      region: 'Hong Kong SAR',     tier: 'hub',                   labelSide: 'right' },
    { x: 935, y: 200, city: 'Tokyo',          region: 'Japan',             tier: 'hub',                   labelSide: 'right' },
    { x: 838, y: 290, city: 'Singapore',      region: 'Singapore',         tier: 'hub',                   labelSide: 'left'  },
    { x: 905, y: 188, city: 'Seoul',          region: 'Korea',             tier: 'network',               labelSide: 'left'  },
    { x: 815, y: 268, city: 'Bangkok',        region: 'Thailand',          tier: 'network',               labelSide: 'left'  },
    { x: 762, y: 248, city: 'Mumbai',         region: 'India',             tier: 'network',               labelSide: 'left'  },
  ];
  const [hov, setHov] = useState(null);

  // Region zones — neutral geographic context (no phase implication)
  const zones = [
    { x:  90, y:  90, w: 260, h: 170, label: 'N · AMERICAS', code: '40°N / 100°W' },
    { x: 420, y:  80, w: 190, h: 160, label: 'EU',           code: '48°N / 015°E' },
    { x: 540, y: 200, w: 180, h: 130, label: 'MENA · GCC',   code: '24°N / 045°E', primary: true },
    { x: 750, y: 150, w: 200, h: 170, label: 'ASIA · PAC',   code: '35°N / 115°E' },
  ];

  return (
    <svg className="dg-map" viewBox="0 0 1000 500" fill="none" aria-label="Global expansion map">
      {/* fine grid — minor ticks */}
      <g opacity="0.35">
        {Array.from({ length: 21 }).map((_, i) => (
          <line key={'h'+i} x1="0" y1={i * 25} x2="1000" y2={i * 25} stroke="var(--rs-hairline)" strokeWidth="1"/>
        ))}
        {Array.from({ length: 41 }).map((_, i) => (
          <line key={'v'+i} x1={i * 25} y1="0" x2={i * 25} y2="500" stroke="var(--rs-hairline)" strokeWidth="1"/>
        ))}
      </g>
      {/* major grid — dotted */}
      <g opacity="0.7">
        {Array.from({ length: 5 }).map((_, i) => (
          <line key={'H'+i} x1="0" y1={(i + 1) * 100} x2="1000" y2={(i + 1) * 100}
                stroke="var(--rs-hairline-2)" strokeWidth="1" strokeDasharray="2 6"/>
        ))}
        {Array.from({ length: 9 }).map((_, i) => (
          <line key={'V'+i} x1={(i + 1) * 100} y1="0" x2={(i + 1) * 100} y2="500"
                stroke="var(--rs-hairline-2)" strokeWidth="1" strokeDasharray="2 6"/>
        ))}
      </g>

      {/* region zones */}
      {zones.map((z) => (
        <g key={z.label}>
          <rect x={z.x} y={z.y} width={z.w} height={z.h}
                fill={z.primary ? 'var(--rs-red)' : 'var(--rs-white)'}
                opacity={z.primary ? 0.05 : 0.025}
                stroke={z.primary ? 'var(--rs-red)' : 'var(--rs-hairline-2)'}
                strokeWidth="1" strokeDasharray={z.primary ? '0' : '4 4'}/>
          {/* corner L-brackets */}
          {[
            [z.x, z.y, 1, 1], [z.x + z.w, z.y, -1, 1],
            [z.x, z.y + z.h, 1, -1], [z.x + z.w, z.y + z.h, -1, -1],
          ].map(([bx, by, sx, sy], bi) => (
            <path key={bi}
                  d={`M ${bx} ${by + sy * 8} L ${bx} ${by} L ${bx + sx * 8} ${by}`}
                  stroke={z.primary ? 'var(--rs-red)' : 'var(--rs-hairline-2)'}
                  strokeWidth="1.5" fill="none"/>
          ))}
          <text x={z.x + 10} y={z.y + 18}
                fontFamily="JetBrains Mono" fontSize="10" letterSpacing="2.5"
                fill={z.primary ? 'var(--rs-red)' : 'var(--rs-gray-1)'}>
            {z.label}
          </text>
          <text x={z.x + 10} y={z.y + z.h - 10}
                fontFamily="JetBrains Mono" fontSize="9" letterSpacing="1.5"
                fill="var(--rs-gray-2)" opacity="0.7">
            {z.code}
          </text>
        </g>
      ))}

      {/* equator + prime meridian reference lines */}
      <line x1="0" y1="250" x2="1000" y2="250" stroke="var(--rs-hairline-2)" strokeWidth="1" opacity="0.6"/>
      <line x1="460" y1="0" x2="460" y2="500" stroke="var(--rs-hairline-2)" strokeWidth="1" opacity="0.6"/>
      <text x="8" y="246" fontFamily="JetBrains Mono" fontSize="9" letterSpacing="2" fill="var(--rs-gray-2)">00°N</text>
      <text x="464" y="12" fontFamily="JetBrains Mono" fontSize="9" letterSpacing="2" fill="var(--rs-gray-2)">000°E</text>

      {/* Inter-region connecting arcs — a chain of four hubs (NYC → Paris →
          Riyadh → Hong Kong) sketched as long shallow curves. They tie the four
          regional constellations into one global network, but no city is the
          centre and there's no directional flow / arrow / pulsing — just
          quiet connective tissue. */}
      <g fill="none" stroke="var(--rs-red)" strokeWidth="1" opacity="0.5" strokeDasharray="4 5">
        <path d="M 252 170 Q 370 92  490 160"/>      {/* NYC → Paris    (transatlantic) */}
        <path d="M 490 160 Q 575 220 625 278"/>      {/* Paris → Riyadh */}
        <path d="M 625 278 Q 745 268 868 232"/>      {/* Riyadh → Hong Kong */}
      </g>

      {/* Regional radial constellations — short arcs from each region's core
          city to its neighbours. Each region stands as its own constellation;
          the inter-region arcs above are the bridges between them. */}
      <g fill="none" stroke="var(--rs-red)" strokeWidth="0.9" opacity="0.55">
        {/* MENA · GCC — radiating from Riyadh, all neighbours east / NE except Jeddah */}
        <path d="M 625 278 Q 612 286 598 290"/>      {/* Riyadh → Jeddah  (SW) */}
        <path d="M 625 278 Q 642 272 655 270"/>      {/* Riyadh → Dubai   (E) */}
        <path d="M 625 278 Q 632 272 645 272"/>      {/* Riyadh → Doha    (E) */}
        <path d="M 625 278 Q 627 264 630 250"/>      {/* Riyadh → Kuwait  (N) */}
        <path d="M 625 278 Q 630 268 635 260"/>      {/* Riyadh → Manama  (NE) */}
        <path d="M 625 278 Q 655 282 685 282"/>      {/* Riyadh → Muscat  (E) */}

        {/* EU — radiating from Paris */}
        <path d="M 490 160 Q 478 150 470 142"/>      {/* Paris → London   (NW) */}
        <path d="M 490 160 Q 502 142 510 128"/>      {/* Paris → Berlin   (NE) */}
        <path d="M 490 160 Q 472 180 458 198"/>      {/* Paris → Madrid   (SW) */}
        <path d="M 490 160 Q 504 175 512 186"/>      {/* Paris → Rome     (SE) */}
        <path d="M 490 160 Q 518 168 540 182"/>      {/* Paris → Istanbul (E) */}

        {/* North America — radiating from New York */}
        <path d="M 252 170 Q 258 164 264 160"/>      {/* NYC → Boston     (NE) */}
        <path d="M 252 170 Q 232 168 212 167"/>      {/* NYC → Chicago    (W) */}
        <path d="M 252 170 Q 244 162 236 158"/>      {/* NYC → Toronto    (NW) */}
        <path d="M 252 170 Q 191 145 130 130"/>      {/* NYC → Vancouver  (far NW) */}
        <path d="M 252 170 Q 191 195 130 195"/>      {/* NYC → SF         (far SW) */}

        {/* Asia · Pacific — radiating from Hong Kong */}
        <path d="M 868 232 Q 902 220 935 200"/>      {/* HK → Tokyo       (NE) */}
        <path d="M 868 232 Q 888 210 905 188"/>      {/* HK → Seoul       (N) */}
        <path d="M 868 232 Q 855 262 838 290"/>      {/* HK → Singapore   (S) */}
        <path d="M 868 232 Q 842 252 815 268"/>      {/* HK → Bangkok     (SW) */}
        <path d="M 868 232 Q 815 240 762 248"/>      {/* HK → Mumbai      (W) */}
      </g>

      {/* soft acknowledgment of the operating cluster (Riyadh + Jeddah) — a single
          static halo, not a pulsing anchor */}
      <circle cx="612" cy="284" r="32" fill="var(--rs-red)" opacity="0.08"/>

      {/* points */}
      {points.map((p, i) => {
        const hovered = hov === i;
        const anyHov = hov !== null;
        const isHub = p.tier === 'hub';
        const dotColor = 'var(--rs-red)';
        const baseOp = isHub ? 1 : 0.7;
        // when any point is hovered, dim the others so labels don't collide
        const groupOp = anyHov && !hovered ? 0.35 : 1;
        // default label shown only for the active anchor (Riyadh); on hover, ONLY the hovered label shows
        const showLabel = hovered || (p.active && !anyHov);
        const leftSide = p.labelSide === 'left';
        return (
          <g key={i} transform={`translate(${p.x}, ${p.y})`}
             onMouseEnter={() => setHov(i)} onMouseLeave={() => setHov(null)}
             style={{ cursor: 'pointer', transition: 'opacity 220ms ease' }} opacity={groupOp}>
            <circle r={hovered ? 9 : (isHub ? 5 : 3)} fill={dotColor} opacity={baseOp}/>
            <circle r={hovered ? 15 : (isHub ? 10 : 7)} fill="none" stroke={dotColor} strokeWidth="1.25" opacity={baseOp * 0.7}/>
            {showLabel && (
              <g transform={`translate(${leftSide ? -14 : 14}, -4)`}>
                <text textAnchor={leftSide ? 'end' : 'start'}
                      fontFamily="Space Grotesk" fontSize="13" fontWeight="600" fill="var(--rs-white)">{p.city}</text>
                <text y="14" textAnchor={leftSide ? 'end' : 'start'}
                      fontFamily="JetBrains Mono" fontSize="9" letterSpacing="2" fill="var(--rs-red)">{p.region}</text>
              </g>
            )}
          </g>
        );
      })}

      {/* legend */}
      <g transform="translate(40, 440)" fontFamily="JetBrains Mono" fontSize="10" letterSpacing="2" fill="var(--rs-gray-1)">
        <g><circle cx="6" cy="0" r="5" fill="var(--rs-red)"/><text x="18" y="4">REGIONAL HUB · mega city</text></g>
        <g transform="translate(310, 0)"><circle cx="6" cy="0" r="3" fill="var(--rs-red)" opacity="0.7"/><text x="18" y="4">NETWORK SCOPE · commercial centres</text></g>
      </g>
    </svg>
  );
}

// =================================================================
// 5) EVOLUTION TIMELINE — Trading → Products → Fulfillment → AI → Platform
// =================================================================
function EvolutionTimeline() {
  const stages = [
    { idx: '01', label: 'Device trading',          desc: 'MENA smart-electronics distribution. Earning the right to play.' },
    { idx: '02', label: 'Product definition',      desc: 'Region-tuned terminals and localised hardware capability.' },
    { idx: '03', label: 'Fulfilment & service',    desc: 'Supply-chain integration, local delivery, field service.' },
    { idx: '04', label: 'AI services',             desc: 'NOVA AI — terminals become programmable, measurable media.' },
    { idx: '05', label: 'Platform infrastructure', desc: 'Unified network: devices + data + AI as one platform.', active: true },
  ];
  return (
    <div className="dg-tl">
      <div className="dg-tl__rule" aria-hidden="true"/>
      <div className="dg-tl__row">
        {stages.map((s) => (
          <div key={s.idx} className={'dg-tl__step' + (s.active ? ' is-active' : '')}>
            <div className="dg-tl__year">{s.idx}</div>
            <div className="dg-tl__dot" aria-hidden="true"/>
            <div className="dg-tl__label">{s.label}</div>
            <div className="dg-tl__desc">{s.desc}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { Flywheel, LayerStack, ThreeTier, ExpansionMap, EvolutionTimeline });
