import { useEffect, useRef, useState } from "react";
import pointerSvg from "@/assets/pointer.min.svg";

/**
 * Floating pointer that tracks the CodeMirror cursor with smooth lerp animation.
 * Positions itself right next to the left border of the editor container.
 */
export default function EditorPointer() {
  const [y, setY] = useState<number | null>(null);
  const [editorLeft, setEditorLeft] = useState<number | null>(null);
  const targetRef = useRef(0);
  const currentRef = useRef(0);
  const rafRef = useRef(0);
  const activeRef = useRef(false);

  useEffect(() => {
    const ease = 0.09;

    const onCursorMove = (e: Event) => {
      const { top } = (e as CustomEvent).detail;
      targetRef.current = top;

      // Find editor container left edge once (or when it changes)
      const cm = document.querySelector(".cm-editor");
      if (cm) {
        setEditorLeft(cm.getBoundingClientRect().left);
      }

      if (!activeRef.current) {
        currentRef.current = top;
        setY(top);
        activeRef.current = true;
      }
    };

    const tick = () => {
      if (activeRef.current) {
        const diff = targetRef.current - currentRef.current;
        if (Math.abs(diff) < 0.5) {
          currentRef.current = targetRef.current;
        } else {
          currentRef.current += diff * ease;
        }
        setY(currentRef.current);
      }
      rafRef.current = requestAnimationFrame(tick);
    };

    window.addEventListener("cm-cursor-move", onCursorMove);
    rafRef.current = requestAnimationFrame(tick);

    return () => {
      window.removeEventListener("cm-cursor-move", onCursorMove);
      cancelAnimationFrame(rafRef.current);
    };
  }, []);

  if (y === null || editorLeft === null) return null;

  return (
    <div
      className="editor-pointer"
      style={{ top: y, left: editorLeft }}
    >
      <div
        className="editor-pointer-img"
        style={{
          WebkitMaskImage: `url(${pointerSvg})`,
          maskImage: `url(${pointerSvg})`,
        }}
      />
    </div>
  );
}
