import { useEffect, useState } from 'react';
import type { DocumentSettings } from '@/pages/editor/store/editorStore';
import type { PageData } from '../types';
import {
  INITIAL_PAGES_PRELOAD_COUNT,
  preloadPagesMedia,
} from '../utils/pageMediaUrls';

export function useInitialPagesPreload(
  pages: PageData[],
  documentSettings?: Partial<DocumentSettings>,
) {
  const [isReady, setIsReady] = useState(false);
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    if (pages.length === 0) {
      setIsReady(false);
      setProgress(0);
      return;
    }

    let cancelled = false;
    setIsReady(false);
    setProgress(0);

    const pagesToPreload = pages.slice(
      0,
      Math.min(INITIAL_PAGES_PRELOAD_COUNT, pages.length),
    );

    void preloadPagesMedia(pagesToPreload, documentSettings, (loaded, total) => {
      if (cancelled) return;
      setProgress(total === 0 ? 100 : Math.round((loaded / total) * 100));
    }).then(() => {
      if (!cancelled) {
        setProgress(100);
        setIsReady(true);
      }
    });

    return () => {
      cancelled = true;
    };
  }, [pages, documentSettings]);

  return { isReady, progress };
}
