/**
 * Utility for enabling View Transitions API in the app
 */

/**
 * Check if View Transitions API is supported
 */
export const supportsViewTransitions = (): boolean => 'startViewTransition' in document;

/**
 * Execute a function with view transition if supported
 * Falls back to immediate execution if not supported
 */
export const withViewTransition = async (callback: () => void | Promise<void>): Promise<void> => {
  if (!supportsViewTransitions()) {
    await callback();
    return;
  }

  const doc = document as Document & {
    startViewTransition: (callback: () => void | Promise<void>) => {
      finished: Promise<void>;
      updateCallbackDone: Promise<void>;
      ready: Promise<void>;
    };
  };

  try {
    const transition = doc.startViewTransition(async () => {
      await callback();
    });

    await transition.finished;
  } catch (error) {
    // Fallback if transition fails
    await callback();
  }
};

/**
 * Enable light view transitions for browser back/forward only.
 *
 * Do NOT intercept in-app <a>/NavLink clicks: wrapping room switches in
 * document.startViewTransition keeps the previous room painted until the new
 * Room tree finishes mounting (often ~1s), which feels like a dead click.
 */
export const enableViewTransitionsForNavigation = (): void => {
  if (!supportsViewTransitions()) {
    return;
  }

  window.addEventListener('popstate', () => {
    withViewTransition(() => {
      // URL already changed; transition just softens the re-render.
    });
  });
};
