import { useCallback } from 'react';

/**
 * Hook for prefetching resources on hover or focus
 * Improves perceived performance by loading data before user clicks
 */
export function usePrefetch() {
  const prefetchedUrls = new Set<string>();

  const prefetch = useCallback((url: string, type: 'image' | 'page' | 'data' = 'page') => {
    // Don't prefetch the same URL twice
    if (prefetchedUrls.has(url)) return;
    prefetchedUrls.add(url);

    if (type === 'image') {
      // Prefetch image
      const img = new Image();
      img.src = url;
    } else if (type === 'page') {
      // Prefetch page using link rel="prefetch"
      const link = document.createElement('link');
      link.rel = 'prefetch';
      link.href = url;
      link.as = 'document';
      document.head.appendChild(link);
    } else if (type === 'data') {
      // Prefetch data
      fetch(url, { method: 'GET', credentials: 'same-origin' }).catch(() => {
        // Silently fail - it's just a prefetch
      });
    }
  }, []);

  const createPrefetchHandlers = useCallback((url: string, type: 'image' | 'page' | 'data' = 'page') => ({
    onMouseEnter: () => prefetch(url, type),
    onFocus: () => prefetch(url, type),
  }), [prefetch]);

  return { prefetch, createPrefetchHandlers };
}
