/* ============================================================
   Direction C — Flux de données animés
   Graph dynamique : nodes qui pulsent, signaux qui circulent
   sur un réseau en étoile avec halo lumineux et dégradés
   ============================================================ */

const { useEffect: useEffectC, useState: useStateC } = React;

function DirCFlux({ bare = false } = {}) {
  const [t, setT] = useStateC(0);
  const [isMobile, setIsMobile] = useStateC(
    typeof window !== 'undefined' && window.innerWidth <= 720
  );
  useEffectC(() => {
    let raf;
    const start = performance.now();
    const tick = (now) => {
      setT((now - start) / 1000);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);
  useEffectC(() => {
    const onResize = () => setIsMobile(window.innerWidth <= 720);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  // SVG text sizes — scaled up on mobile to compensate viewBox shrink
  const fsCore  = isMobile ? 26 : 11;
  const fsLabel = isMobile ? 36 : 16;
  const fsSub   = isMobile ? 22 : 10;
  const labelOffset = isMobile ? 70 : 52;
  // Vertical gap label↔sub: bigger on mobile so lines breathe
  const subOffset    = isMobile ? 52 : 26;   // sub under label (nodes below hub)
  const subOffsetTop = isMobile ? -42 : -16; // sub above label (nodes above hub)

  // Center hub at (600,400). Nodes around it.
  const cx = 600, cy = 400;
  const nodes = [
    { id: 'interphone', label: 'Interphonie', sub: 'SIP · Vidéo', x: 220, y: 200, color: '#22D3A4' },
    { id: 'energy',     label: 'Énergie',     sub: 'M-Bus · PV',  x: 220, y: 600, color: '#22D3A4' },
    { id: 'domotique',  label: 'Domotique',   sub: 'KNX · Matter',x: 980, y: 200, color: '#22D3A4' },
    { id: 'app',        label: 'App résident',sub: 'iOS · Android',x: 980,y: 600, color: '#22D3A4' },
    { id: 'cloud',      label: 'Cloud',       sub: 'API · Décomptes', x: 600, y: 120, color: '#22D3A4' },
    { id: 'gerance',    label: 'Gérance',     sub: 'Export compta', x: 600, y: 680, color: '#22D3A4' },
  ];

  return (
    <div style={{
      position: 'relative',
      width: '100%',
      height: '100%',
      background: bare
        ? 'transparent'
        : 'radial-gradient(ellipse at 50% 50%, #1B2347 0%, #0B1129 55%, #050817 100%)',
      overflow: 'hidden',
      fontFamily: '"Inter", system-ui, sans-serif',
      color: '#F5F2EB',
    }}>
      {/* Ambient halo */}
      <div style={{
        position: 'absolute', left: '50%', top: '50%',
        width: 900, height: 900, marginLeft: -450, marginTop: -450,
        background: 'radial-gradient(circle, rgba(34,211,164,0.18) 0%, transparent 65%)',
        filter: 'blur(40px)',
      }} />
      {/* Concentric rings */}
      <svg viewBox="0 0 1200 800" preserveAspectRatio="xMidYMid meet"
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
        <defs>
          <radialGradient id="hubGradC" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="#22D3A4" stopOpacity="0.9" />
            <stop offset="60%" stopColor="#22D3A4" stopOpacity="0.3" />
            <stop offset="100%" stopColor="#22D3A4" stopOpacity="0" />
          </radialGradient>
          <linearGradient id="lineGradC" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0%" stopColor="#22D3A4" stopOpacity="0.1" />
            <stop offset="50%" stopColor="#22D3A4" stopOpacity="0.6" />
            <stop offset="100%" stopColor="#22D3A4" stopOpacity="0.1" />
          </linearGradient>
          <filter id="glowC">
            <feGaussianBlur stdDeviation="4" result="coloredBlur" />
            <feMerge>
              <feMergeNode in="coloredBlur" />
              <feMergeNode in="SourceGraphic" />
            </feMerge>
          </filter>
        </defs>

        {/* Concentric rings around hub */}
        {[120, 220, 320, 420].map((r, i) => (
          <circle key={r} cx={cx} cy={cy} r={r}
            fill="none"
            stroke="rgba(34,211,164,0.10)"
            strokeWidth="1"
            strokeDasharray={i % 2 ? '4,6' : 'none'}
            style={{
              transformOrigin: `${cx}px ${cy}px`,
              animation: `spinC ${20 + i * 8}s linear ${i % 2 ? 'reverse' : 'normal'} infinite`,
            }}
          />
        ))}

        {/* Node connections */}
        {nodes.map((n, i) => {
          const dx = n.x - cx, dy = n.y - cy;
          const dist = Math.sqrt(dx * dx + dy * dy);
          // Pulse position along line
          const phase = ((t * 0.4) + i * 0.18) % 1;
          const px = cx + dx * phase;
          const py = cy + dy * phase;
          // direction pulse (incoming from app/sensors -> hub)
          const phase2 = ((t * 0.4) + i * 0.18 + 0.5) % 1;
          const px2 = n.x - dx * phase2;
          const py2 = n.y - dy * phase2;
          return (
            <g key={n.id}>
              <line x1={cx} y1={cy} x2={n.x} y2={n.y}
                stroke="url(#lineGradC)" strokeWidth="1.5" />
              {/* Outgoing pulse */}
              <circle cx={px} cy={py} r="4"
                fill="#22D3A4" filter="url(#glowC)"
                opacity={0.3 + 0.7 * Math.sin(phase * Math.PI)} />
              {/* Incoming pulse */}
              <circle cx={px2} cy={py2} r="3"
                fill="#22D3A4" filter="url(#glowC)"
                opacity={0.2 + 0.5 * Math.sin(phase2 * Math.PI)} />
            </g>
          );
        })}

        {/* Hub */}
        <circle cx={cx} cy={cy} r="70" fill="url(#hubGradC)" />
        <circle cx={cx} cy={cy} r="38"
          fill="#0B1129" stroke="#22D3A4" strokeWidth="1.5"
          filter="url(#glowC)" />
        <circle cx={cx} cy={cy} r="14"
          fill="#22D3A4" filter="url(#glowC)">
          <animate attributeName="r" values="14;18;14" dur="2s" repeatCount="indefinite" />
        </circle>
        <text x={cx} y={cy + (isMobile ? 84 : 60)} textAnchor="middle"
          fill="rgba(34,211,164,0.9)" fontSize={fsCore}
          fontFamily="JetBrains Mono, monospace" letterSpacing="2">
          NEOLIA · CORE
        </text>

        {/* Nodes */}
        {nodes.map((n, i) => {
          const pulse = 0.7 + 0.3 * Math.sin(t * 1.5 + i);
          return (
            <g key={'n-' + n.id}>
              {/* Halo */}
              <circle cx={n.x} cy={n.y} r="42"
                fill="rgba(34,211,164,0.05)"
                style={{ opacity: pulse }} />
              {/* Outer ring */}
              <circle cx={n.x} cy={n.y} r="32"
                fill="none" stroke="rgba(34,211,164,0.4)" strokeWidth="1" />
              {/* Inner */}
              <circle cx={n.x} cy={n.y} r="22"
                fill="#0B1129" stroke="#22D3A4" strokeWidth="1.5"
                filter="url(#glowC)" />
              <circle cx={n.x} cy={n.y} r="6"
                fill="#22D3A4" filter="url(#glowC)" />

              {/* Label */}
              <g transform={`translate(${n.x}, ${n.y + (n.y < cy ? -labelOffset : labelOffset)})`}>
                <text textAnchor="middle"
                  fill="#F5F2EB" fontSize={fsLabel} fontWeight="600"
                  letterSpacing="-0.3"
                  y={n.y < cy ? 0 : 12}>
                  {n.label}
                </text>
                <text textAnchor="middle"
                  fill="rgba(34,211,164,0.7)" fontSize={fsSub}
                  fontFamily="JetBrains Mono, monospace" letterSpacing="2"
                  y={n.y < cy ? subOffsetTop : subOffset}>
                  {n.sub}
                </text>
              </g>
            </g>
          );
        })}
      </svg>

      {/* Header overlay */}
      {!bare && <div style={{
        position: 'absolute', left: 40, top: 40,
        fontFamily: '"JetBrains Mono", monospace', fontSize: 11,
        letterSpacing: '0.18em', textTransform: 'uppercase',
        color: 'rgba(34,211,164,0.9)',
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <span style={{ width: 6, height: 6, background: '#22D3A4', borderRadius: '50%', boxShadow: '0 0 8px #22D3A4' }} />
        Réseau · Flux temps réel
      </div>}

      {!bare && <div style={{
        position: 'absolute', right: 40, bottom: 40,
        fontFamily: '"JetBrains Mono", monospace', fontSize: 10,
        letterSpacing: '0.15em', textTransform: 'uppercase',
        color: 'rgba(245,242,235,0.4)',
      }}>
        6 services · 1 cœur · Latence &lt; 50ms
      </div>}

      <style>{`
        @keyframes spinC {
          from { transform: rotate(0deg); }
          to { transform: rotate(360deg); }
        }
      `}</style>
    </div>
  );
}

window.DirCFlux = DirCFlux;
