import { useEffect, useRef, useState } from 'react';
import { getLabels, projectToScreen } from './viewportLabelStore';

/**
 * STABLE VIEWPORT CORE — DOM label overlay.
 * Renders measurement labels, warnings and callouts as ordinary React DOM
 * elements OUTSIDE the Canvas. Positions are computed each frame by projecting
 * the label's world-space anchor through the live camera. If projection fails
 * (no camera / point behind camera) the label is hidden but the viewport stays.
 * No Drei Html, no portals.
 */

const TONE = {
  cyan: 'border-cyan-400/55 bg-[#0b0f13]/95 text-cyan-200',
  amber: 'border-amber-400/55 bg-[#0b0f13]/95 text-amber-300',
  purple: 'border-purple-400/55 bg-[#0b0f13]/95 text-purple-200',
  red: 'border-red-400/55 bg-[#0b0f13]/95 text-red-300',
  slate: 'border-white/15 bg-[#0b0f13]/95 text-slate-200',
};

export default function ViewportLabelLayer() {
  const [, tick] = useState(0);
  const raf = useRef(0);

  useEffect(() => {
    const loop = () => {
      tick((n) => (n + 1) & 0xffff);
      raf.current = requestAnimationFrame(loop);
    };
    raf.current = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf.current);
  }, []);

  const labels = getLabels();

  return (
    <div className="pointer-events-none absolute inset-0 overflow-hidden">
      {labels.map((l) => {
        const p = projectToScreen(l.position);
        if (!p) return null;
        const tone = TONE[l.tone] || TONE.slate;
        return (
          <div
            key={l.id}
            className="absolute -translate-x-1/2 -translate-y-1/2 whitespace-nowrap rounded-lg border px-2.5 py-1 text-xs shadow-lg"
            style={{ left: p.x, top: p.y, ...(l.offset ? { marginLeft: l.offset.x, marginTop: l.offset.y } : {}) }}
          >
            <div className={tone}>
              {l.badge && (
                <span className="mr-1.5 inline-flex h-4 w-4 items-center justify-center rounded-full bg-cyan-400/20 text-[9px] font-bold text-cyan-300">
                  {l.badge}
                </span>
              )}
              <span className="font-semibold text-slate-100">{l.title}</span>
              {l.subtitle && <div className="mt-0.5 text-[10px] font-normal opacity-90">{l.subtitle}</div>}
            </div>
          </div>
        );
      })}
    </div>
  );
}