import { useEffect, useMemo, useRef } from "react";
import { useAnnotations } from "@/context/AnnotationsContext";
import type { EpubRendition } from "@/utils/epubRendition";
import {
  syncBookmarkHighlights,
  type EpubRenditionWithHighlights,
} from "@/utils/epubHighlights";

export function useEpubHighlights(
  ebookId: number,
  renditionRef: React.RefObject<EpubRendition | null>,
  renditionVersion: number,
): void {
  const { markers, loadBookmarks } = useAnnotations();
  const appliedRef = useRef<Map<string, string>>(new Map());

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

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

  useEffect(() => {
    appliedRef.current.clear();
  }, [ebookId, renditionVersion]);

  useEffect(() => {
    const rendition = renditionRef.current as EpubRenditionWithHighlights | null;
    if (!rendition) return;

    const sync = () => {
      syncBookmarkHighlights(rendition, bookMarkers, appliedRef.current);
    };

    sync();

    const onRelocated = () => sync();
    rendition.on?.("relocated", onRelocated);
    rendition.on?.("rendered", onRelocated);

    return () => {
      rendition.off?.("relocated", onRelocated);
      rendition.off?.("rendered", onRelocated);
    };
  }, [bookMarkers, renditionRef, renditionVersion]);
}
