/**
 * useProjectAssets Hook
 *
 * Preloads and resolves project assets (favicon, og_image, logo) to presigned URLs.
 * Handles both storage_key (relative paths) and legacy cdn_url (full S3 URLs) formats.
 */

import { useState, useEffect, useRef, useCallback } from 'react';
import {
  extractStoragePath,
  queuePresignedUrls,
  resolveAssetPlaybackUrl,
} from '../lib/assetUrl';

interface ProjectAssets {
  faviconUrl: string | null;
  ogImageUrl: string | null;
  logoUrl: string | null;
  isLoading: boolean;
}

interface ProjectAssetInput {
  favicon_url?: string;
  og_image_url?: string;
  logo_url?: string;
}

/**
 * Hook to preload and resolve project assets (favicon, og_image, logo).
 * Extracts storage paths from URLs (handles both formats) and resolves them
 * to presigned URLs for access.
 */
export function useProjectAssets(project: ProjectAssetInput | null): ProjectAssets {
  const [assets, setAssets] = useState<ProjectAssets>({
    faviconUrl: null,
    ogImageUrl: null,
    logoUrl: null,
    isLoading: true,
  });

  // Track the last project URLs to avoid redundant processing
  const lastUrlsRef = useRef<string>('');

  const resolveAssets = useCallback(async () => {
    if (!project) {
      setAssets({
        faviconUrl: null,
        ogImageUrl: null,
        logoUrl: null,
        isLoading: false,
      });
      return;
    }

    // Extract storage paths from URLs (handles both formats)
    const faviconPath = extractStoragePath(project.favicon_url || '');
    const ogImagePath = extractStoragePath(project.og_image_url || '');
    const logoPath = extractStoragePath(project.logo_url || '');

    // Collect paths that need presigning (relative paths only)
    const pathsToPresign = [faviconPath, ogImagePath, logoPath].filter(
      (path) => path && !path.startsWith('http'),
    );

    // Queue presigned URL requests
    if (pathsToPresign.length > 0) {
      await queuePresignedUrls(pathsToPresign);
    }

    // Resolve to playback URLs (presigned if available, otherwise proxy)
    setAssets({
      faviconUrl: faviconPath ? resolveAssetPlaybackUrl(faviconPath) : null,
      ogImageUrl: ogImagePath ? resolveAssetPlaybackUrl(ogImagePath) : null,
      logoUrl: logoPath ? resolveAssetPlaybackUrl(logoPath) : null,
      isLoading: false,
    });
  }, [project]);

  useEffect(() => {
    // Create a key from the URLs to detect changes
    const urlsKey = `${project?.favicon_url || ''}|${project?.og_image_url || ''}|${project?.logo_url || ''}`;

    // Skip if URLs haven't changed
    if (urlsKey === lastUrlsRef.current) {
      return;
    }
    lastUrlsRef.current = urlsKey;

    // Reset loading state and resolve
    setAssets((prev) => ({ ...prev, isLoading: true }));
    resolveAssets();
  }, [project?.favicon_url, project?.og_image_url, project?.logo_url, resolveAssets]);

  return assets;
}
