import { useEffect, useRef, useState } from 'react';
import { Vector3, Matrix } from '@babylonjs/core';

export default function DomLabelLayerV2({ getContext, labels }) {
  const nodeRefs = useRef({});

  useEffect(() => {
    let raf = 0;
    const tick = () => {
      raf = requestAnimationFrame(tick);
      const ctx = getContext && getContext();
      if (!ctx || !ctx.engine || !ctx.scene || !ctx.camera || !ctx.canvas) return;
      const { engine, scene, camera, canvas } = ctx;
      let rw, rh, vp, transform, scaleX, scaleY;
      try {
        rw = engine.getRenderWidth();
        rh = engine.getRenderHeight();
        if (!rw || !rh) return;
        vp = camera.viewport.toGlobal(rw, rh);
        transform = scene.getTransformMatrix();
        scaleX = canvas.clientWidth / rw;
        scaleY = canvas.clientHeight / rh;
      } catch (_) { return; }

      for (const label of labels) {
        const node = nodeRefs.current[label.id];
        if (!node) continue;
        try {
          const p = Vector3.Project(new Vector3(label.position[0], label.position[1], label.position[2]), Matrix.Identity(), transform, vp);
          if (!isFinite(p.x) || !isFinite(p.y) || !isFinite(p.z) || p.z < 0 || p.z > 1) { node.style.display = 'none'; continue; }
          node.style.display = '';
          node.style.transform = `translate(-50%, -50%) translate(${p.x * scaleX}px, ${p.y * scaleY}px)`;
        } catch (_) { node.style.display = 'none'; }
      }
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [getContext, labels]);

  return (
    <div className="pointer-events-none absolute inset-0 z-10 overflow-hidden">
      {labels.map((l) => (
        <div
          key={l.id}
          ref={(el) => { if (el) nodeRefs.current[l.id] = el; }}
          className={l.badge
            ? `absolute left-0 top-0 flex h-5 w-5 items-center justify-center rounded-full border text-[9px] font-bold backdrop-blur ${toneClass(l.tone)}`
            : `absolute left-0 top-0 whitespace-nowrap rounded-md border px-2 py-1 text-[10px] font-semibold backdrop-blur ${toneClass(l.tone)}`}
          style={{ display: 'none' }}
        >
          {l.badge || l.text}
        </div>
      ))}
    </div>
  );
}

function toneClass(tone) {
  switch (tone) {
    case 'purple': return 'border-violet-500/50 bg-[#0b0d14]/90 text-violet-300';
    case 'green': return 'border-emerald-400/50 bg-[#0b0d14]/90 text-emerald-300';
    case 'red': return 'border-red-400/50 bg-[#0b0d14]/90 text-red-300';
    case 'amber': return 'border-amber-400/40 bg-[#0b0f13]/90 text-amber-300';
    default: return 'border-white/15 bg-[#0b0f13]/90 text-slate-300';
  }
}