/* global React */
// Animated network visualization — used in hero and section backgrounds.

const NetworkBg = ({ density = 'normal', variant = 'hero', animate = true }) => {
  const svgRef = React.useRef(null);
  const rafRef = React.useRef(null);
  const tRef = React.useRef(0);

  // Generate node positions (deterministic per variant)
  const config = React.useMemo(() => {
    const counts = { sparse: 18, normal: 28, dense: 42 };
    const n = counts[density] || 28;
    const seed = variant === 'hero' ? 7 : variant === 'experience' ? 13 : 19;
    const rand = mulberry32(seed);
    const nodes = [];
    for (let i = 0; i < n; i++) {
      nodes.push({
        x: rand() * 100,
        y: rand() * 100,
        r: 1.2 + rand() * 2.4,
        phase: rand() * Math.PI * 2,
        speed: 0.4 + rand() * 0.6,
      });
    }
    // Connect close neighbors
    const edges = [];
    for (let i = 0; i < nodes.length; i++) {
      const dists = [];
      for (let j = 0; j < nodes.length; j++) {
        if (i === j) continue;
        const dx = nodes[i].x - nodes[j].x;
        const dy = nodes[i].y - nodes[j].y;
        dists.push({ j, d: Math.sqrt(dx * dx + dy * dy) });
      }
      dists.sort((a, b) => a.d - b.d);
      const k = 2 + Math.floor(rand() * 2);
      for (let m = 0; m < k; m++) {
        const a = i;
        const b = dists[m].j;
        if (a < b && dists[m].d < 32) {
          edges.push({ a, b, d: dists[m].d, phase: rand() * Math.PI * 2 });
        }
      }
    }
    // Add a few signal pulses along edges
    const pulses = [];
    for (let i = 0; i < Math.min(6, edges.length); i++) {
      const e = edges[Math.floor(rand() * edges.length)];
      pulses.push({ edge: e, offset: rand() * 100, speed: 8 + rand() * 12 });
    }
    return { nodes, edges, pulses };
  }, [density, variant]);

  React.useEffect(() => {
    if (!animate) return;
    let start = performance.now();
    const tick = () => {
      const now = performance.now();
      tRef.current = (now - start) / 1000;
      const svg = svgRef.current;
      if (svg) {
        // Update node pulse circles
        const pulseEls = svg.querySelectorAll('[data-node-pulse]');
        pulseEls.forEach((el, i) => {
          const node = config.nodes[i];
          if (!node) return;
          const t = tRef.current * node.speed + node.phase;
          const scale = 1 + Math.sin(t * 2) * 0.4 + 1.2;
          const op = 0.15 + (Math.sin(t * 2) * 0.5 + 0.5) * 0.35;
          el.setAttribute('r', node.r * scale);
          el.setAttribute('opacity', op);
        });
        // Move pulses along edges
        const pulseDots = svg.querySelectorAll('[data-pulse]');
        pulseDots.forEach((el, i) => {
          const p = config.pulses[i];
          if (!p) return;
          const a = config.nodes[p.edge.a];
          const b = config.nodes[p.edge.b];
          const t = ((tRef.current * p.speed + p.offset) % 100) / 100;
          const x = a.x + (b.x - a.x) * t;
          const y = a.y + (b.y - a.y) * t;
          el.setAttribute('cx', x);
          el.setAttribute('cy', y);
          const fade = Math.sin(t * Math.PI);
          el.setAttribute('opacity', fade);
        });
      }
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [animate, config]);

  const lineColor = variant === 'hero' ? 'rgba(0, 123, 255, 0.18)' : 'rgba(255, 255, 255, 0.10)';
  const lineColorStrong = variant === 'hero' ? 'rgba(77, 168, 255, 0.45)' : 'rgba(255, 255, 255, 0.25)';
  const nodeColor = variant === 'hero' ? '#4DA8FF' : '#FFFFFF';
  const pulseColor = '#00D4FF';

  return (
    <svg
      ref={svgRef}
      viewBox="0 0 100 100"
      preserveAspectRatio="xMidYMid slice"
      style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}
    >
      <defs>
        <radialGradient id={`nodeGlow-${variant}`}>
          <stop offset="0%" stopColor={nodeColor} stopOpacity="0.8" />
          <stop offset="100%" stopColor={nodeColor} stopOpacity="0" />
        </radialGradient>
      </defs>
      {/* Edges */}
      {config.edges.map((e, i) => {
        const a = config.nodes[e.a];
        const b = config.nodes[e.b];
        const strong = i % 4 === 0;
        return (
          <line
            key={`e${i}`}
            x1={a.x} y1={a.y} x2={b.x} y2={b.y}
            stroke={strong ? lineColorStrong : lineColor}
            strokeWidth="0.12"
            vectorEffect="non-scaling-stroke"
          />
        );
      })}
      {/* Node pulse glows */}
      {config.nodes.map((n, i) => (
        <circle
          key={`p${i}`}
          data-node-pulse
          cx={n.x} cy={n.y} r={n.r * 2}
          fill={`url(#nodeGlow-${variant})`}
          opacity="0.3"
        />
      ))}
      {/* Nodes */}
      {config.nodes.map((n, i) => (
        <circle
          key={`n${i}`}
          cx={n.x} cy={n.y} r={n.r * 0.35}
          fill={nodeColor}
          opacity="0.9"
        />
      ))}
      {/* Moving pulses */}
      {config.pulses.map((p, i) => (
        <circle
          key={`pulse${i}`}
          data-pulse
          cx={config.nodes[p.edge.a].x}
          cy={config.nodes[p.edge.a].y}
          r="0.7"
          fill={pulseColor}
          opacity="0"
        >
          <animate attributeName="r" values="0.5;0.9;0.5" dur="1.6s" repeatCount="indefinite" />
        </circle>
      ))}
    </svg>
  );
};

// Concentric ring 5G/coverage motif for hero right side
const HeroViz = () => {
  return (
    <svg viewBox="0 0 520 520" style={{ width: '100%', height: '100%' }}>
      <defs>
        <radialGradient id="hvCenter" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#4DA8FF" stopOpacity="0.6" />
          <stop offset="100%" stopColor="#0A1F44" stopOpacity="0" />
        </radialGradient>
        <linearGradient id="hvRing" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" stopColor="#4DA8FF" stopOpacity="0.7" />
          <stop offset="50%" stopColor="#007BFF" stopOpacity="0.3" />
          <stop offset="100%" stopColor="#00D4FF" stopOpacity="0.05" />
        </linearGradient>
      </defs>

      {/* Background glow */}
      <circle cx="260" cy="260" r="240" fill="url(#hvCenter)" opacity="0.5" />

      {/* Concentric rings — pulsing */}
      {[80, 130, 180, 230].map((r, i) => (
        <g key={r}>
          <circle
            cx="260" cy="260" r={r}
            fill="none"
            stroke="url(#hvRing)"
            strokeWidth="1.2"
            opacity={0.85 - i * 0.15}
          >
            <animate
              attributeName="r"
              values={`${r};${r + 10};${r}`}
              dur={`${4 + i * 0.7}s`}
              repeatCount="indefinite"
              begin={`${i * 0.4}s`}
            />
            <animate
              attributeName="opacity"
              values={`${0.85 - i * 0.15};${0.4 - i * 0.08};${0.85 - i * 0.15}`}
              dur={`${4 + i * 0.7}s`}
              repeatCount="indefinite"
              begin={`${i * 0.4}s`}
            />
          </circle>
        </g>
      ))}

      {/* Outer expanding wave */}
      <circle cx="260" cy="260" r="80" fill="none" stroke="#4DA8FF" strokeWidth="1" opacity="0.6">
        <animate attributeName="r" values="80;260;260" dur="3.2s" repeatCount="indefinite" />
        <animate attributeName="opacity" values="0.6;0;0" dur="3.2s" repeatCount="indefinite" />
      </circle>
      <circle cx="260" cy="260" r="80" fill="none" stroke="#00D4FF" strokeWidth="1" opacity="0.4">
        <animate attributeName="r" values="80;260;260" dur="3.2s" repeatCount="indefinite" begin="1.6s" />
        <animate attributeName="opacity" values="0.4;0;0" dur="3.2s" repeatCount="indefinite" begin="1.6s" />
      </circle>

      {/* Tower silhouette in center */}
      <g transform="translate(260, 260)">
        {/* Mast */}
        <rect x="-1.5" y="-60" width="3" height="100" fill="#fff" opacity="0.9" />
        {/* Cross bars */}
        <rect x="-14" y="-30" width="28" height="2.5" fill="#fff" opacity="0.85" rx="1" />
        <rect x="-10" y="-12" width="20" height="2.5" fill="#fff" opacity="0.85" rx="1" />
        <rect x="-7" y="4" width="14" height="2.5" fill="#fff" opacity="0.85" rx="1" />
        {/* Top antennae */}
        <line x1="0" y1="-60" x2="-12" y2="-78" stroke="#4DA8FF" strokeWidth="2" />
        <line x1="0" y1="-60" x2="12" y2="-78" stroke="#4DA8FF" strokeWidth="2" />
        <line x1="0" y1="-60" x2="0" y2="-82" stroke="#4DA8FF" strokeWidth="2.5" />
        <circle cx="0" cy="-84" r="3" fill="#00D4FF">
          <animate attributeName="opacity" values="1;0.3;1" dur="1.4s" repeatCount="indefinite" />
        </circle>
        <circle cx="-12" cy="-78" r="2" fill="#4DA8FF" opacity="0.9" />
        <circle cx="12" cy="-78" r="2" fill="#4DA8FF" opacity="0.9" />
        {/* Base */}
        <polygon points="-20,40 20,40 12,55 -12,55" fill="rgba(255,255,255,0.5)" stroke="rgba(255,255,255,0.7)" strokeWidth="0.8" />
        {/* Glow at base */}
        <ellipse cx="0" cy="58" rx="36" ry="4" fill="#4DA8FF" opacity="0.25" />
      </g>

      {/* Orbiting data points */}
      <g style={{ transformOrigin: '260px 260px' }}>
        <g>
          <animateTransform
            attributeName="transform"
            type="rotate"
            from="0 260 260"
            to="360 260 260"
            dur="22s"
            repeatCount="indefinite"
          />
          <circle cx="260" cy="80" r="5" fill="#00D4FF" />
          <circle cx="260" cy="80" r="11" fill="#00D4FF" opacity="0.2" />
        </g>
        <g>
          <animateTransform
            attributeName="transform"
            type="rotate"
            from="120 260 260"
            to="480 260 260"
            dur="28s"
            repeatCount="indefinite"
          />
          <circle cx="260" cy="80" r="4" fill="#4DA8FF" />
          <circle cx="260" cy="80" r="9" fill="#4DA8FF" opacity="0.2" />
        </g>
        <g>
          <animateTransform
            attributeName="transform"
            type="rotate"
            from="240 260 260"
            to="-120 260 260"
            dur="36s"
            repeatCount="indefinite"
          />
          <circle cx="260" cy="80" r="3.5" fill="#fff" opacity="0.9" />
        </g>
      </g>

      {/* Small data labels (static) */}
      <g fontFamily="'IBM Plex Mono', monospace" fontSize="8" fill="rgba(255,255,255,0.55)">
        <text x="50" y="120">5G NR</text>
        <text x="50" y="135" fill="rgba(0, 212, 255, 0.8)">▲ 1.2 Gbps</text>

        <text x="400" y="160">NEUTRAL HOST</text>
        <text x="400" y="175" fill="rgba(0, 212, 255, 0.8)">4 OPERATORS</text>

        <text x="70" y="420">IoT MESH</text>
        <text x="70" y="435" fill="rgba(0, 212, 255, 0.8)">● 1,284 nodes</text>

        <text x="380" y="400">SITES</text>
        <text x="380" y="415" fill="rgba(0, 212, 255, 0.8)">3,000+ DEPLOYED</text>
      </g>
    </svg>
  );
};

// Mulberry32 PRNG for deterministic node placement
function mulberry32(seed) {
  let a = seed;
  return function() {
    a |= 0; a = a + 0x6D2B79F5 | 0;
    let t = Math.imul(a ^ a >>> 15, 1 | a);
    t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
    return ((t ^ t >>> 14) >>> 0) / 4294967296;
  };
}

Object.assign(window, { NetworkBg, HeroViz });
