import { useLayoutEffect, useEffect, useRef } from 'react';
import { registerLabel, unregisterLabel } from './viewportLabelStore';

/**
 * STABLE VIEWPORT CORE — label registration hook.
 * Registers an array of plain-data labels into the shared store each render
 * and unregisters them on unmount. The DOM overlay (ViewportLabelLayer) reads
 * the store and projects positions to screen — no Drei Html, no portals.
 *
 * label = { id, position:[x,y,z], title, subtitle?, tone?, badge? }
 */
export function useLabels(labels) {
  const prev = useRef([]);
  useLayoutEffect(() => {
    for (const id of prev.current) unregisterLabel(id);
    const ids = [];
    for (const l of labels) {
      if (!l || !l.id) continue;
      registerLabel(l.id, l);
      ids.push(l.id);
    }
    prev.current = ids;
  });
  useEffect(() => () => {
    for (const id of prev.current) unregisterLabel(id);
    prev.current = [];
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
}