import { useRef, useEffect, useCallback } 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);

  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 { registerIris, unregisterIris } = useLazyEyes({ anchorRef, maxShift, ease });

  const irisRef = useCallback((el: HTMLElement | null) => {
    if (el) registerIris(el);
    return () => { if (el) unregisterIris(el); };
  }, [registerIris, unregisterIris]);

  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;
        return (
          <div
            key={i}
            className="editor-pointer-eye"
            style={{ top: eye.top, left: eye.left, width: size, height: size }}
          >
            <div
              ref={irisRef}
              className="editor-pointer-iris"
              style={{
                width: irisSize,
                height: irisSize,
                marginTop: -(irisSize / 2) - 0.5,
                marginLeft: -(irisSize / 2) - 0.5,
              }}
            />
          </div>
        );
      })}
    </div>
  );
}
