import { useRef, useEffect } from "react";
import { useLazyEyes } from "@/hooks/useLazyEyes";

interface EyeSpec {
  top: number;
  left: number;
  size?: number;
  irisSize?: number;
}

interface LazyEyesProps {
  eyes: EyeSpec[];
  /** Viewport-relative anchor the eyes "live" at. If omitted, uses the component's own position. */
  anchor?: { x: number; y: number };
  maxShift?: number;
  ease?: number;
  className?: string;
}

export default function LazyEyes({ eyes, anchor, maxShift, ease, className }: LazyEyesProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const anchorRef = useRef<{ x: number; y: number } | null>(anchor ?? null);

  // Keep anchorRef in sync with prop or auto-compute from DOM
  useEffect(() => {
    if (anchor) {
      anchorRef.current = anchor;
      return;
    }
    const update = () => {
      if (containerRef.current) {
        const rect = containerRef.current.getBoundingClientRect();
        anchorRef.current = { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
      }
    };
    update();
    window.addEventListener("scroll", update, true);
    window.addEventListener("resize", update);
    return () => {
      window.removeEventListener("scroll", update, true);
      window.removeEventListener("resize", update);
    };
  }, [anchor]);

  const offset = useLazyEyes({ anchorRef, maxShift, ease });

  return (
    <div ref={containerRef} className={className} style={{ position: "absolute", pointerEvents: "none" }}>
      {eyes.map((eye, i) => {
        const size = eye.size ?? 5;
        const irisSize = eye.irisSize ?? 2;
        // Clamp iris within eye circle
        const maxR = (size - irisSize) / 2;
        const dist = Math.sqrt(offset.x * offset.x + offset.y * offset.y) || 0;
        const scale = dist > maxR && dist > 0 ? maxR / dist : 1;
        const cx = offset.x * scale;
        const cy = offset.y * scale;
        return (
          <div
            key={i}
            className="editor-pointer-eye"
            style={{ top: eye.top, left: eye.left, width: size, height: size }}
          >
            <div
              className="editor-pointer-iris"
              style={{
                width: irisSize,
                height: irisSize,
                marginTop: -(irisSize / 2) - 0.5,
                marginLeft: -(irisSize / 2) - 0.5,
                transform: `translate(${cx}px, ${cy}px)`,
              }}
            />
          </div>
        );
      })}
    </div>
  );
}
