/**
 * useBackgroundTransition Hook
 *
 * Manages background transition effects when switching between pages.
 * Handles the fade-out animation of the transition video overlay and
 * coordinates with the page switch hook to clear previous backgrounds.
 *
 * This hook consolidates the background transition logic used by both
 * RuntimePresentation and constructor.tsx.
 *
 * Two modes:
 * 1. Full mode (RuntimePresentation): Fade-out animation + direct navigation clearing
 * 2. Simple mode (constructor): Direct navigation clearing only
 */

import { useEffect, useState, useCallback } from 'react';

/**
 * Fade-out configuration (optional - for RuntimePresentation)
 */
export interface FadeOutConfig {
  /** Whether a transition video has finished playing and is waiting for bg ready */
  pendingTransitionComplete: boolean;
  /** Whether the new background image is ready to display */
  isBackgroundReady: boolean;
  /** Ref to the transition video element for cleanup */
  transitionVideoRef: React.RefObject<HTMLVideoElement | null>;
  /** Callback to clear transition state after overlay is removed */
  onTransitionCleanup: () => void;
}

export interface UseBackgroundTransitionOptions {
  /** Page switch hook instance for clearing previous background */
  pageSwitch: {
    clearPreviousBackground: () => void;
    isSwitching: boolean;
    isNewBgReady: boolean;
    previousBgImageUrl: string;
  };
  /** Optional fade-out configuration (for RuntimePresentation) */
  fadeOut?: FadeOutConfig;
}

export interface UseBackgroundTransitionResult {
  /** Whether the overlay is currently fading out */
  isOverlayFadingOut: boolean;
  /** Reset the fade-out state (call before starting a new transition) */
  resetFadeOut: () => void;
}

/**
 * Duration of the fade-out animation in milliseconds
 */
const FADE_DURATION_MS = 300;

/**
 * Hook for managing background transition effects.
 *
 * @example
 * // Full mode with fade-out (RuntimePresentation)
 * const { isOverlayFadingOut, resetFadeOut } = useBackgroundTransition({
 *   pageSwitch,
 *   fadeOut: {
 *     pendingTransitionComplete,
 *     isBackgroundReady,
 *     transitionVideoRef,
 *     onTransitionCleanup: () => {
 *       setTransitionPreview(null);
 *       setPendingTransitionComplete(false);
 *     },
 *   },
 * });
 *
 * @example
 * // Simple mode - direct navigation only (constructor)
 * useBackgroundTransition({ pageSwitch });
 */
export function useBackgroundTransition({
  pageSwitch,
  fadeOut,
}: UseBackgroundTransitionOptions): UseBackgroundTransitionResult {
  const [isOverlayFadingOut, setIsOverlayFadingOut] = useState(false);

  /**
   * Reset fade-out state before starting a new transition.
   * This prevents the fade-out effect from re-triggering when state resets.
   */
  const resetFadeOut = useCallback(() => {
    setIsOverlayFadingOut(false);
  }, []);

  /**
   * Effect: Fade out and remove transition overlay when background is ready.
   * Only runs when fadeOut config is provided.
   *
   * Sequence:
   * 1. Transition video finishes playing (pendingTransitionComplete = true)
   * 2. New background image loads (isBackgroundReady = true)
   * 3. Start fade-out animation (isOverlayFadingOut = true)
   * 4. After fade completes, clean up video and clear transition state
   */
  useEffect(() => {
    if (!fadeOut) return;

    const {
      pendingTransitionComplete,
      isBackgroundReady,
      transitionVideoRef,
      onTransitionCleanup,
    } = fadeOut;

    if (pendingTransitionComplete && isBackgroundReady && !isOverlayFadingOut) {
      // Start fade-out animation
      setIsOverlayFadingOut(true);

      // After fade completes, remove the overlay
      const fadeTimer = setTimeout(() => {
        const video = transitionVideoRef.current;
        if (video) {
          video.removeAttribute('src');
          video.load();
        }

        // Clear previous background from shared hook
        pageSwitch.clearPreviousBackground();

        // Notify caller to clear transition state
        onTransitionCleanup();

        // Reset fade-out state
        setIsOverlayFadingOut(false);
      }, FADE_DURATION_MS);

      return () => clearTimeout(fadeTimer);
    }
  }, [fadeOut, isOverlayFadingOut, pageSwitch]);

  /**
   * Effect: Clear previous background overlay when new background is ready (direct navigation).
   *
   * This handles the case when navigating without a transition video.
   * The previous background stays visible until the new one is ready to paint.
   */
  useEffect(() => {
    if (
      pageSwitch.isSwitching &&
      pageSwitch.isNewBgReady &&
      pageSwitch.previousBgImageUrl
    ) {
      // New background is ready - clear the previous background overlay
      pageSwitch.clearPreviousBackground();
    }
  }, [
    pageSwitch.isSwitching,
    pageSwitch.isNewBgReady,
    pageSwitch.previousBgImageUrl,
    pageSwitch.clearPreviousBackground,
  ]);

  return {
    isOverlayFadingOut,
    resetFadeOut,
  };
}
