// A tiny shared guard so a screen with unsaved changes can veto in-app navigation. A screen
// registers a predicate (returns true when it is safe to leave, e.g. after a confirm()); App.tsx's
// nav handler consults `canLeaveCurrentScreen()` before pushing a new route. Only one guard is
// active at a time (the mounted screen) — registering returns an unregister fn for cleanup.
//
// This does NOT cover full-page unloads (reload / close tab / external link) — a screen additionally
// installs its own `beforeunload` listener while dirty for that path.

type NavigationGuard = () => boolean;

let activeGuard: NavigationGuard | null = null;

export function registerNavigationGuard(guard: NavigationGuard): () => void {
  activeGuard = guard;
  return () => {
    if (activeGuard === guard) {
      activeGuard = null;
    }
  };
}

// Returns true when navigation may proceed. With no guard registered, always true.
export function canLeaveCurrentScreen(): boolean {
  if (!activeGuard) {
    return true;
  }
  return activeGuard();
}
