import { useEffect, useMemo } from "react";
import { useAnnotations } from "@/context/AnnotationsContext";
import { isPdfAnchor, parsePdfAnchor } from "@/utils/pdfAnchor";
import { normalizeHighlightColor } from "@/constants/bookmarkHighlightColors";

export interface PdfPageHighlight {
  rects: [number, number, number, number][];
  color: string;
}

export function usePdfHighlights(ebookId: number, currentPage: number): PdfPageHighlight[] {
  const { markers, loadBookmarks } = useAnnotations();

  const bookMarkers = useMemo(
    () => markers.filter((m) => m.ebook_id === ebookId),
    [markers, ebookId],
  );

  useEffect(() => {
    if (!ebookId || Number.isNaN(ebookId)) return;
    void loadBookmarks(ebookId);
  }, [ebookId, loadBookmarks]);

  return useMemo(() => {
    const highlights: PdfPageHighlight[] = [];
    for (const marker of bookMarkers) {
      if (!isPdfAnchor(marker.epub_cfi)) continue;
      const parsed = parsePdfAnchor(marker.epub_cfi);
      if (!parsed || parsed.page !== currentPage || !parsed.rects.length) continue;
      highlights.push({
        rects: parsed.rects,
        color: normalizeHighlightColor(marker.highlight_color),
      });
    }
    return highlights;
  }, [bookMarkers, currentPage]);
}
