/* =====================================================================
   Future Consulting — hero visual variants
   - <OrbitalHero/>     literal logo motif: rotating elliptical orbits + nodes
   - <NetworkHero/>     self-building connected network graph
   - <FusionDiagram/>   the radial layered viz used on Fusion section
   ===================================================================== */

const { useEffect, useRef, useState } = React;

/* ---------------------------------------------------------------- */
/*  ORBITAL HERO — literal logo motif                                */
/* ---------------------------------------------------------------- */
function OrbitalHero() {
  const [t, setT] = useState(0);
  useEffect(() => {
    let raf, start = performance.now();
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const tick = (now) => {
      setT((now - start) / 1000);
      if (!reduced) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  // Orbit definitions: rx, ry, tilt, speed, opacity, nodeCount
  const orbits = [
    { rx: 240, ry: 80,  tilt: -22, speed: 0.10, op: 0.45, nodes: 1 },
    { rx: 200, ry: 130, tilt: 35,  speed: 0.14, op: 0.55, nodes: 2 },
    { rx: 170, ry: 60,  tilt: -55, speed: 0.18, op: 0.40, nodes: 1 },
    { rx: 120, ry: 100, tilt: 12,  speed: 0.22, op: 0.65, nodes: 1 },
  ];

  return (
    <div className="orbital-hero">
      {/* concentric pulse rings (background) */}
      <div className="orbit-pulse" style={{ width: 200, height: 200, animationDelay: '0s' }} />
      <div className="orbit-pulse" style={{ width: 320, height: 320, animationDelay: '1s' }} />
      <div className="orbit-pulse" style={{ width: 480, height: 480, animationDelay: '2s' }} />

      <svg className="orbital-svg" viewBox="-300 -300 600 600" aria-hidden="true">
        <defs>
          <linearGradient id="orb-grad" x1="-1" y1="-1" x2="1" y2="1">
            <stop offset="0" stopColor="#A8F0D4" stopOpacity="0.9"/>
            <stop offset="0.5" stopColor="#85E6C6" stopOpacity="0.5"/>
            <stop offset="1" stopColor="#4FC9A1" stopOpacity="0.2"/>
          </linearGradient>
          <radialGradient id="core-grad">
            <stop offset="0" stopColor="#A8F0D4" stopOpacity="0.9"/>
            <stop offset="0.6" stopColor="#85E6C6" stopOpacity="0.3"/>
            <stop offset="1" stopColor="#85E6C6" stopOpacity="0"/>
          </radialGradient>
          <filter id="glow">
            <feGaussianBlur stdDeviation="3" result="b"/>
            <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
          </filter>
        </defs>

        {/* core glow */}
        <circle cx="0" cy="0" r="80" fill="url(#core-grad)"/>

        {/* orbital ellipses (static) */}
        {orbits.map((o, i) => (
          <g key={i} transform={`rotate(${o.tilt})`}>
            <ellipse cx="0" cy="0" rx={o.rx} ry={o.ry} fill="none"
              stroke="url(#orb-grad)" strokeWidth="1" opacity={o.op}/>
          </g>
        ))}

        {/* orbiting nodes */}
        {orbits.map((o, i) => (
          <g key={'n' + i} transform={`rotate(${o.tilt})`}>
            {Array.from({ length: o.nodes }).map((_, n) => {
              const phase = (t * o.speed * Math.PI * 2) + (n * (Math.PI * 2 / o.nodes)) + i * 0.7;
              const x = Math.cos(phase) * o.rx;
              const y = Math.sin(phase) * o.ry;
              return (
                <g key={n} transform={`translate(${x} ${y})`}>
                  <circle r="3.5" fill="#A8F0D4" filter="url(#glow)"/>
                  <circle r="1.5" fill="#FFFFFF"/>
                </g>
              );
            })}
          </g>
        ))}

        {/* central X (the mark's heart) */}
        <g opacity="0.95">
          <path d="M-22 -22 L22 22 M22 -22 L-22 22"
            stroke="#A8F0D4" strokeWidth="3" strokeLinecap="round" filter="url(#glow)"/>
        </g>

        {/* small static center dot */}
        <circle cx="0" cy="0" r="4" fill="#FFFFFF"/>
      </svg>

      {/* Telemetry chips floating around */}
      <div className="orb-chip orb-chip-1">
        <span className="dot"/> <span className="mono">SYS · sync</span>
      </div>
      <div className="orb-chip orb-chip-2">
        <span className="mono">99.98%</span> <span className="meta">uptime</span>
      </div>
      <div className="orb-chip orb-chip-3">
        <span className="mono">AI · ops</span> <span className="dot"/>
      </div>
    </div>
  );
}

/* ---------------------------------------------------------------- */
/*  NETWORK HERO — self-building connected graph                     */
/* ---------------------------------------------------------------- */
function NetworkHero() {
  const canvasRef = useRef(null);
  const buildRef = useRef(0);

  // Pre-computed node positions (so layout is stable, not random per render)
  const nodes = [
    // central (the org)
    { x: 0,    y: 0,    r: 6, label: 'CORE',          tier: 0, delay: 0 },
    // tier 1 orbit
    { x: -160, y: -90,  r: 4, label: 'INFRA',         tier: 1, delay: 200 },
    { x:  170, y: -60,  r: 4, label: 'AI',            tier: 1, delay: 320 },
    { x: -100, y:  140, r: 4, label: 'OPS',           tier: 1, delay: 440 },
    { x:  150, y:  130, r: 4, label: 'SYSTEMS',       tier: 1, delay: 560 },
    { x:    0, y: -180, r: 4, label: 'AV',            tier: 1, delay: 680 },
    // tier 2
    { x: -240, y: -180, r: 3, label: 'cloud',         tier: 2, delay: 900 },
    { x: -240, y:    0, r: 3, label: 'security',      tier: 2, delay: 1000 },
    { x: -200, y:  220, r: 3, label: 'monitoring',    tier: 2, delay: 1100 },
    { x:   60, y:  230, r: 3, label: 'workflow',      tier: 2, delay: 1200 },
    { x:  240, y:  200, r: 3, label: 'integration',   tier: 2, delay: 1300 },
    { x:  260, y:   30, r: 3, label: 'agents',        tier: 2, delay: 1400 },
    { x:  240, y: -160, r: 3, label: 'analytics',     tier: 2, delay: 1500 },
    { x:   70, y: -240, r: 3, label: 'collab',        tier: 2, delay: 1600 },
    { x: -100, y: -240, r: 3, label: 'rooms',         tier: 2, delay: 1700 },
  ];

  const edges = [
    // tier 0 → 1
    [0, 1], [0, 2], [0, 3], [0, 4], [0, 5],
    // tier 1 → 2
    [1, 6], [1, 7], [1, 8],
    [2, 12], [2, 11],
    [3, 8], [3, 9],
    [4, 9], [4, 10], [4, 11],
    [5, 13], [5, 14],
    // intra-ring
    [1, 5], [2, 5], [3, 4],
  ];

  useEffect(() => {
    const c = canvasRef.current;
    if (!c) return;
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const dpr = Math.min(window.devicePixelRatio || 1, 2);

    const resize = () => {
      const r = c.getBoundingClientRect();
      c.width = r.width * dpr;
      c.height = r.height * dpr;
    };
    resize();
    window.addEventListener('resize', resize);

    const start = performance.now();
    let raf;
    const draw = (now) => {
      const elapsed = now - start;
      buildRef.current = elapsed;
      const r = c.getBoundingClientRect();
      const ctx = c.getContext('2d');
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      ctx.clearRect(0, 0, r.width, r.height);
      ctx.translate(r.width / 2, r.height / 2);

      const scale = Math.min(r.width, r.height) / 600;
      ctx.scale(scale, scale);

      // edges first
      edges.forEach(([a, b], i) => {
        const A = nodes[a]; const B = nodes[b];
        const startMs = Math.max(A.delay, B.delay);
        const drawMs = 600;
        const p = Math.min(1, Math.max(0, (elapsed - startMs) / drawMs));
        if (p <= 0) return;
        ctx.beginPath();
        ctx.moveTo(A.x, A.y);
        ctx.lineTo(A.x + (B.x - A.x) * p, A.y + (B.y - A.y) * p);
        ctx.strokeStyle = `rgba(133, 230, 198, ${0.08 + 0.18 * p})`;
        ctx.lineWidth = A.tier === 0 || B.tier === 0 ? 1.0 : 0.6;
        ctx.stroke();

        // pulse along the edge
        if (!reduced && p === 1) {
          const pulseT = ((elapsed - startMs - drawMs) / 1800 + i * 0.13) % 1;
          if (pulseT > 0 && pulseT < 1) {
            const px = A.x + (B.x - A.x) * pulseT;
            const py = A.y + (B.y - A.y) * pulseT;
            ctx.beginPath();
            ctx.arc(px, py, 1.6, 0, Math.PI * 2);
            ctx.fillStyle = 'rgba(168, 240, 212, 0.9)';
            ctx.fill();
          }
        }
      });

      // nodes on top
      nodes.forEach((n) => {
        const p = Math.min(1, Math.max(0, (elapsed - n.delay) / 400));
        if (p <= 0) return;
        const r = n.r * p;
        // glow
        if (n.tier <= 1) {
          const grd = ctx.createRadialGradient(n.x, n.y, 0, n.x, n.y, r * 4);
          grd.addColorStop(0, `rgba(133, 230, 198, ${0.30 * p})`);
          grd.addColorStop(1, 'rgba(133, 230, 198, 0)');
          ctx.fillStyle = grd;
          ctx.beginPath(); ctx.arc(n.x, n.y, r * 4, 0, Math.PI * 2); ctx.fill();
        }
        // dot
        ctx.beginPath();
        ctx.arc(n.x, n.y, r, 0, Math.PI * 2);
        ctx.fillStyle = n.tier === 0 ? '#A8F0D4' : (n.tier === 1 ? '#85E6C6' : 'rgba(180, 190, 205, 0.9)');
        ctx.fill();

        // label for tier 1
        if (n.tier === 1 && p > 0.5) {
          ctx.font = '500 10px JetBrains Mono, monospace';
          ctx.fillStyle = `rgba(180, 190, 205, ${(p - 0.5) * 2})`;
          ctx.textAlign = 'center';
          ctx.fillText(n.label, n.x, n.y - n.r - 10);
        }
      });

      // soft pulse at center
      if (!reduced) {
        const pulse = (Math.sin(elapsed / 1000) + 1) / 2;
        const grd = ctx.createRadialGradient(0, 0, 0, 0, 0, 60);
        grd.addColorStop(0, `rgba(133, 230, 198, ${0.10 + 0.10 * pulse})`);
        grd.addColorStop(1, 'rgba(133, 230, 198, 0)');
        ctx.fillStyle = grd;
        ctx.beginPath(); ctx.arc(0, 0, 60, 0, Math.PI * 2); ctx.fill();
      }

      raf = requestAnimationFrame(draw);
    };
    raf = requestAnimationFrame(draw);
    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', resize); };
  }, []);

  return (
    <div className="network-hero">
      <canvas ref={canvasRef} className="network-canvas"/>
      <div className="orb-chip orb-chip-1">
        <span className="dot"/> <span className="mono">graph · live</span>
      </div>
      <div className="orb-chip orb-chip-2">
        <span className="mono">15 nodes</span> <span className="meta">· 19 edges</span>
      </div>
      <div className="orb-chip orb-chip-3">
        <span className="mono">orchestrated</span> <span className="dot"/>
      </div>
    </div>
  );
}

/* ---------------------------------------------------------------- */
/*  FUSION DIAGRAM — radial layered viz (used inside Fusion section) */
/* ---------------------------------------------------------------- */
function FusionDiagram({ active = 0, onSelect, layers }) {
  // 4 concentric rings, the active one mints up
  const labels = (layers && layers.length >= 4) ? layers : ['infra', 'systems', 'intelligence', 'operations'];
  return (
    <svg className="fusion-svg" viewBox="-260 -260 520 520" aria-hidden="true">
      <defs>
        <radialGradient id="fcore">
          <stop offset="0" stopColor="#A8F0D4" stopOpacity="0.5"/>
          <stop offset="1" stopColor="#A8F0D4" stopOpacity="0"/>
        </radialGradient>
        <filter id="fglow"><feGaussianBlur stdDeviation="2"/></filter>
      </defs>

      {/* radial grid */}
      {[60, 110, 170, 230].map((r, i) => (
        <circle key={i} cx="0" cy="0" r={r} fill="none"
          stroke={i === active ? 'rgba(133, 230, 198, 0.7)' : 'rgba(255,255,255,0.10)'}
          strokeWidth={i === active ? 1.5 : 1}
          strokeDasharray={i === active ? '0' : '2 6'}
        />
      ))}

      {/* radial spokes */}
      {Array.from({ length: 12 }).map((_, i) => {
        const a = (i / 12) * Math.PI * 2;
        const x = Math.cos(a) * 230, y = Math.sin(a) * 230;
        return <line key={i} x1="0" y1="0" x2={x} y2={y} stroke="rgba(255,255,255,0.05)" strokeWidth="0.5"/>;
      })}

      {/* nodes on each ring */}
      {[60, 110, 170, 230].map((r, ring) => {
        const count = 4 + ring * 2;
        return Array.from({ length: count }).map((_, i) => {
          const a = (i / count) * Math.PI * 2 + ring * 0.3;
          const x = Math.cos(a) * r, y = Math.sin(a) * r;
          const isActive = ring === active;
          return (
            <g key={`${ring}-${i}`} onClick={() => onSelect && onSelect(ring)} style={{cursor: 'pointer'}}>
              <circle cx={x} cy={y} r={isActive ? 4 : 2}
                fill={isActive ? '#A8F0D4' : 'rgba(180, 190, 205, 0.5)'}
                filter={isActive ? 'url(#fglow)' : undefined}
              />
            </g>
          );
        });
      })}

      {/* core */}
      <circle cx="0" cy="0" r="80" fill="url(#fcore)"/>
      <circle cx="0" cy="0" r="6" fill="#A8F0D4"/>
      <text x="0" y="42" textAnchor="middle"
        fontFamily="JetBrains Mono, monospace" fontSize="9" fill="rgba(180, 190, 205, 0.8)"
        letterSpacing="2">FUSION</text>

      {/* active layer label */}
      <text x="0" y="-242" textAnchor="middle"
        fontFamily="JetBrains Mono, monospace" fontSize="10" fill="#A8F0D4"
        letterSpacing="2">
        {labels[active].toUpperCase()}
      </text>
    </svg>
  );
}

Object.assign(window, { OrbitalHero, NetworkHero, FusionDiagram });
