'use client';

import { useState, useEffect } from 'react';

type UseImageDownloadTimeReturn = {
  downloadTime: number | null;
  isLoading: boolean;
};

export const useImageDownloadTime = (imageUrl: string | null): UseImageDownloadTimeReturn => {
  const [downloadTime, setDownloadTime] = useState<number | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (!imageUrl) {
      setDownloadTime(null);
      setIsLoading(false);
      return;
    }

    const measureDownloadTime = async () => {
      setIsLoading(true);

      try {
        const startTime = performance.now();
        const cacheBustUrl = `${imageUrl}?_t=${Date.now()}`;

        await new Promise<void>((resolve, reject) => {
          const img = new Image();

          img.onload = () => {
            const endTime = performance.now();
            const duration = Math.round(endTime - startTime);
            setDownloadTime(duration);
            setIsLoading(false);
            resolve();
          };

          img.onerror = () => {
            setDownloadTime(null);
            setIsLoading(false);
            reject(new Error('Failed to load image'));
          };

          img.src = cacheBustUrl;
        });
      } catch (error) {
        setDownloadTime(null);
        setIsLoading(false);
      }
    };

    measureDownloadTime();
  }, [imageUrl]);

  return { downloadTime, isLoading };
};
