import { useEffect, useState } from 'react';
import type { PageData } from '../types';
import {
  extractPageMediaAssets,
  preloadPagesMedia,
} from '../utils/pageMediaUrls';

type PageBackground = Pick<
  PageData,
  'backgroundType' | 'backgroundImageUrl' | 'backgroundVideoUrl'
>;

function mergePageBackground(
  page: PageData,
  background?: Partial<PageBackground>,
): PageData {
  if (!background) return page;
  return {
    ...page,
    backgroundType: background.backgroundType ?? page.backgroundType,
    backgroundImageUrl:
      background.backgroundImageUrl ?? page.backgroundImageUrl,
    backgroundVideoUrl:
      background.backgroundVideoUrl ?? page.backgroundVideoUrl,
  };
}

export function usePageMediaReady(
  page: PageData,
  background?: Partial<PageBackground>,
  enabled = true,
) {
  const [isReady, setIsReady] = useState(false);

  const mediaKey = enabled
    ? extractPageMediaAssets([mergePageBackground(page, background)])
        .map((asset) => `${asset.kind}:${asset.url}`)
        .sort()
        .join('|')
    : '';

  useEffect(() => {
    if (!enabled) {
      setIsReady(true);
      return;
    }

    const mergedPage = mergePageBackground(page, background);
    const assets = extractPageMediaAssets([mergedPage]);

    if (assets.length === 0) {
      setIsReady(true);
      return;
    }

    let cancelled = false;
    setIsReady(false);

    void preloadPagesMedia([mergedPage]).then(() => {
      if (!cancelled) setIsReady(true);
    });

    return () => {
      cancelled = true;
    };
  }, [enabled, page.id, mediaKey, background?.backgroundType, background?.backgroundImageUrl, background?.backgroundVideoUrl]);

  return isReady;
}
