import { useCallback, useEffect, useRef, useState } from "react";
import type { PendingSelection } from "./useEpubSelection";
import { rectsFromSelection, serializePdfAnchor } from "../utils/pdfAnchor";

export function usePdfSelection(
  pageWrapRef: React.RefObject<HTMLDivElement | null>,
  currentPage: number,
  chapterTitle: string,
) {
  const [pendingSelection, setPendingSelection] = useState<PendingSelection | null>(null);
  const chapterTitleRef = useRef(chapterTitle);
  chapterTitleRef.current = chapterTitle;

  const clearSelection = useCallback(() => {
    setPendingSelection(null);
  }, []);

  useEffect(() => {
    const wrap = pageWrapRef.current;
    if (!wrap) return;

    const handler = () => {
      window.setTimeout(() => {
        const sel = window.getSelection();
        const text = sel?.toString()?.trim() ?? "";
        if (!text || !sel || sel.rangeCount === 0) {
          setPendingSelection(null);
          return;
        }

        const range = sel.getRangeAt(0);
        if (!wrap.contains(range.commonAncestorContainer)) {
          setPendingSelection(null);
          return;
        }

        const rects = rectsFromSelection(range, wrap);
        const anchor = serializePdfAnchor(currentPage, rects.length > 0 ? rects : undefined);
        const rect = range.getBoundingClientRect();

        setPendingSelection({
          epubCfi: anchor,
          locationText: text.slice(0, 2000),
          chapterIndex: currentPage - 1,
          chapterTitle: chapterTitleRef.current,
          anchorTop: rect.bottom + 8,
          anchorLeft: Math.min(rect.left, window.innerWidth - 280),
        });
      }, 10);
    };

    wrap.addEventListener("mouseup", handler);
    return () => wrap.removeEventListener("mouseup", handler);
  }, [pageWrapRef, currentPage]);

  return { pendingSelection, clearSelection };
}
