// SVG overlay that draws one short straight line per engagement inside a
// StationArea. Reads chip/card positions from refs the parent collects.
//
// Props:
//   engagements — Array<{ taskId, chipRef, cardRef, hex }>
//                 chipRef and cardRef are React refs to the chip and the
//                 task card DOM nodes; hex is the stroke color.
//   areaRef     — React ref to the StationArea container (the SVG sits
//                 absolutely inside this container, so all coordinates are
//                 relative to it).
//
// Re-measures on window resize. Mutates SVG path elements directly to avoid
// re-rendering the whole SVG tree on each measure.

const TetherLayer = ({ engagements, areaRef }) => {
  const svgRef = React.useRef(null);
  const lineRefs = React.useRef({});

  const measure = React.useCallback(() => {
    const area = areaRef?.current;
    const svg = svgRef.current;
    if (!area || !svg) return;
    const areaRect = area.getBoundingClientRect();
    for (const eng of engagements) {
      const lineEl = lineRefs.current[eng.taskId];
      const chip = eng.chipRef?.current;
      const card = eng.cardRef?.current;
      if (!lineEl || !chip || !card) continue;
      const chipRect = chip.getBoundingClientRect();
      const cardRect = card.getBoundingClientRect();
      const x1 = chipRect.left + chipRect.width / 2 - areaRect.left;
      const y1 = chipRect.bottom - areaRect.top;
      const x2 = cardRect.left + cardRect.width / 2 - areaRect.left;
      const y2 = cardRect.top - areaRect.top;
      lineEl.setAttribute('x1', x1);
      lineEl.setAttribute('y1', y1);
      lineEl.setAttribute('x2', x2);
      lineEl.setAttribute('y2', y2);
      lineEl.setAttribute('stroke', eng.hex);
    }
  }, [engagements, areaRef]);

  React.useLayoutEffect(() => { measure(); }, [measure]);
  React.useEffect(() => {
    const onResize = () => measure();
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, [measure]);

  return (
    <svg
      ref={svgRef}
      className="absolute inset-0 pointer-events-none"
      style={{ width: '100%', height: '100%' }}
    >
      {engagements.map((eng) => (
        <line
          key={eng.taskId}
          ref={(el) => { if (el) lineRefs.current[eng.taskId] = el; }}
          x1="0" y1="0" x2="0" y2="0"
          stroke={eng.hex}
          strokeWidth="2"
          strokeLinecap="round"
        />
      ))}
    </svg>
  );
};

if (typeof window !== 'undefined') {
  window.TetherLayer = TetherLayer;
}
