/**
 * @file useReauthModalSuspension.ts - Determines a modal's visual state based on whether the global reauthentication modal is currently displayed.
 * When reauthentication is required, the consuming modal enters a "suspended" state where it stays mounted in the DOM (preserving user input) but is visually hidden so the reauth modal can appear on top without stacking issues.
 */

import { useReauth } from '../../contexts/ReauthContext.tsx';
import { useMemo } from 'react';

/**
 * Tri-state representing a modal's effective visibility when the reauth modal may overlay it.
 *
 * - `'visible'`   -- modal is shown normally
 * - `'hidden'`    -- modal is not shown (its own `show` condition is false)
 * - `'suspended'` -- modal should be shown but is temporarily hidden because the reauth modal is active
 */
export type ModalReauthSuspensionState = 'visible' | 'hidden' | 'suspended';

/**
 * Determines a modal component's suspension state based on whether the global reauthentication modal is shown.
 * Can be used to help prevent modals on top of modals and interference with other hooks.
 *
 * @param show The modal's existing show condition
 * @returns The effective show state
 */
export function useReauthModalSuspension(show: boolean) {
  const { reauthModalShown } = useReauth();

  // Keep the modal mounted, but hide it visually if reauthentication modal is shown
  const effectiveShow: ModalReauthSuspensionState = useMemo(() => {
    if (reauthModalShown && show) {
      return 'suspended';
    }
    return show
      ? ('visible' as ModalReauthSuspensionState)
      : ('hidden' as ModalReauthSuspensionState);
  }, [reauthModalShown, show]);

  return effectiveShow;
}
