// SVG cable layer with animated electric flow

const CableLayer = ({ sources, consumers, connections, allocations, pendingCable, mousePos, onCableClick, period, isMobile }) => {
  // Returns port world coords. Source out: right edge. Consumer in: left edge.
  // Card widths/heights differ between desktop and mobile.
  const srcW = isMobile ? 180 : 240;
  const srcH = isMobile ? 160 : 182; // approximate full card height
  const conW = isMobile ? 160 : 200;
  const conH = isMobile ? 130 : 158;
  const srcCenterY = srcH / 2;
  const conCenterY = conH / 2;
  const sourcePort = (s) => ({ x: s.x + srcW, y: s.y + srcCenterY });
  const consumerPort = (c) => ({ x: c.x, y: c.y + conCenterY });

  // Build a smooth bezier path between two points
  const bezier = (a, b) => {
    const dx = Math.abs(b.x - a.x);
    const sag = Math.min(60, dx * 0.15) + 30; // gravity-like sag
    const c1x = a.x + dx * 0.5;
    const c1y = a.y + sag;
    const c2x = b.x - dx * 0.5;
    const c2y = b.y + sag;
    return `M ${a.x} ${a.y} C ${c1x} ${c1y}, ${c2x} ${c2y}, ${b.x} ${b.y}`;
  };

  return (
    <svg
      style={{
        position: 'absolute',
        inset: 0,
        width: '100%',
        height: '100%',
        pointerEvents: 'none',
        zIndex: 2
      }}
    >
      <defs>
        {/* glow filter */}
        <filter id="cable-glow" x="-50%" y="-50%" width="200%" height="200%">
          <feGaussianBlur stdDeviation="3" result="blur" />
          <feMerge>
            <feMergeNode in="blur" />
            <feMergeNode in="SourceGraphic" />
          </feMerge>
        </filter>
        <filter id="cable-glow-strong" x="-50%" y="-50%" width="200%" height="200%">
          <feGaussianBlur stdDeviation="6" result="blur" />
          <feMerge>
            <feMergeNode in="blur" />
            <feMergeNode in="SourceGraphic" />
          </feMerge>
        </filter>

        {/* gradients */}
        <linearGradient id="cable-cyan" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" stopColor="#4cf3ff" stopOpacity="0.9" />
          <stop offset="100%" stopColor="#6ef195" stopOpacity="0.9" />
        </linearGradient>
        <linearGradient id="cable-amber" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" stopColor="#ffc36b" stopOpacity="0.9" />
          <stop offset="100%" stopColor="#ffc36b" stopOpacity="0.6" />
        </linearGradient>
        <linearGradient id="cable-red" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" stopColor="#ff5577" stopOpacity="0.9" />
          <stop offset="100%" stopColor="#ff5577" stopOpacity="0.7" />
        </linearGradient>
      </defs>

      {/* existing connections */}
      {connections.map((conn) => {
        const src = sources.find(s => s.id === conn.sourceId);
        const cons = consumers.find(c => c.id === conn.consumerId);
        if (!src || !cons) return null;

        const a = sourcePort(src);
        const b = consumerPort(cons);
        const path = bezier(a, b);

        // Determine cable state
        const alloc = allocations[conn.id] || 0;
        const sourceOverloaded = (allocations.__sourceDraw?.[src.id] || 0) > src.amount && src.amount > 0;
        const consumerFunded = (allocations.__consumerSupply?.[cons.id] || 0) >= cons.amount && cons.amount > 0;
        const inactive = alloc === 0;

        const stroke = sourceOverloaded ? 'url(#cable-red)'
                       : consumerFunded ? 'url(#cable-cyan)'
                       : inactive ? '#2a3340'
                       : 'url(#cable-amber)';
        const flowColor = sourceOverloaded ? '#ff5577'
                         : consumerFunded ? '#4cf3ff'
                         : inactive ? '#475061'
                         : '#ffc36b';

        return (
          <g key={conn.id} style={{ pointerEvents: 'auto', cursor: 'pointer' }}>
            {/* hit area */}
            <path
              d={path}
              fill="none"
              stroke="transparent"
              strokeWidth="20"
              onClick={(e) => { e.stopPropagation(); onCableClick(conn.id); }}
            />
            {/* outer glow */}
            <path
              d={path}
              fill="none"
              stroke={flowColor}
              strokeWidth="6"
              opacity={inactive ? 0 : 0.15}
              filter="url(#cable-glow-strong)"
              style={{ pointerEvents: 'none' }}
            />
            {/* base cable */}
            <path
              d={path}
              fill="none"
              stroke={stroke}
              strokeWidth="3"
              strokeLinecap="round"
              filter={inactive ? 'none' : 'url(#cable-glow)'}
              style={{ pointerEvents: 'none' }}
            />
            {/* flow animation */}
            {!inactive && (
              <path
                d={path}
                fill="none"
                stroke={flowColor}
                strokeWidth="2"
                strokeLinecap="round"
                strokeDasharray="4 16"
                style={{
                  pointerEvents: 'none',
                  animation: `flow ${sourceOverloaded ? '0.6s' : '1.5s'} linear infinite`
                }}
              />
            )}
            {/* end caps */}
            <circle cx={a.x} cy={a.y} r="4" fill={flowColor} opacity={inactive ? 0.3 : 1} filter="url(#cable-glow)" style={{ pointerEvents: 'none' }} />
            <circle cx={b.x} cy={b.y} r="4" fill={flowColor} opacity={inactive ? 0.3 : 1} filter="url(#cable-glow)" style={{ pointerEvents: 'none' }} />
          </g>
        );
      })}

      {/* pending (drag) cable */}
      {pendingCable && mousePos && (() => {
        const src = sources.find(s => s.id === pendingCable.sourceId);
        if (!src) return null;
        const a = sourcePort(src);
        const b = mousePos;
        const path = bezier(a, b);
        return (
          <g style={{ pointerEvents: 'none' }}>
            <path d={path} fill="none" stroke="#4cf3ff" strokeWidth="3" strokeLinecap="round" opacity="0.4" filter="url(#cable-glow-strong)" />
            <path d={path} fill="none" stroke="#4cf3ff" strokeWidth="2" strokeLinecap="round" strokeDasharray="6 6" style={{ animation: 'flow 0.6s linear infinite' }} />
            <circle cx={b.x} cy={b.y} r="6" fill="#4cf3ff" opacity="0.3" />
            <circle cx={b.x} cy={b.y} r="3" fill="#4cf3ff" />
          </g>
        );
      })()}
    </svg>
  );
};

window.CableLayer = CableLayer;
