import { useCallback, useEffect } from 'react';
import { useLocation, useNavigate, NavigateOptions } from 'react-router-dom';
import { supportsViewTransitions, withViewTransition } from '../utils/viewTransitions';

/**
 * Hook to enable View Transitions for React Router navigation
 * This intercepts navigation and wraps it in view transitions
 */
export const useViewTransitions = () => {
  const location = useLocation();

  useEffect(() => {
    if (!supportsViewTransitions()) {
      return;
    }

    // Mark that we support view transitions
    document.documentElement.classList.add('view-transitions-enabled');

    return () => {
      document.documentElement.classList.remove('view-transitions-enabled');
    };
  }, []);

  useEffect(() => {
    // Route changed - view transitions will be handled by CSS
  }, [location]);

  return {
    supportsViewTransitions: supportsViewTransitions(),
  };
};

/**
 * Custom navigate hook that wraps navigation in view transitions
 * 
 * **USAGE:**
 * Replace `useNavigate()` with `useNavigateWithTransition()` for smooth transitions
 * 
 * ```tsx
 * // Before:
 * import { useNavigate } from 'react-router-dom';
 * const navigate = useNavigate();
 * 
 * // After:
 * import { useNavigateWithTransition } from '../hooks/useViewTransitions';
 * const navigate = useNavigateWithTransition();
 * 
 * // Usage remains the same:
 * navigate('/some/path');
 * navigate(-1); // Go back
 * ```
 * 
 * This enables smooth animated transitions when navigating between:
 * - Different spaces
 * - Different rooms
 * - Different sections (Home, Inbox, Settings, etc.)
 * 
 * Falls back to instant navigation on browsers that don't support View Transitions API.
 */
export const useNavigateWithTransition = () => {
  const navigate = useNavigate();

  return useCallback(
    (to: string | number, options?: NavigateOptions) => {
      if (!supportsViewTransitions()) {
        if (typeof to === 'number') {
          navigate(to);
        } else {
          navigate(to, options);
        }
        return;
      }

      withViewTransition(() => {
        if (typeof to === 'number') {
          navigate(to);
        } else {
          navigate(to, options);
        }
      });
    },
    [navigate]
  );
};
