/* ============================================================================
   NAVIGATION TYPE — should the current navigation restore the saved scroll?
   ----------------------------------------------------------------------------
   Restore only on browser back/forward (popstate) or when the document load
   itself was a reload / back-forward — NEVER on a fresh forward navigation,
   which should start at the top. A forward navigation goes through pushState, so
   we clear the flag there to avoid a back/forward that landed on an unrelated
   page leaking "restore" intent into the next forward navigation.
   ========================================================================== */

let poppedNavigation = false;
let initialLoadHandled = false;

if (typeof window !== 'undefined') {
  window.addEventListener('popstate', () => {
    poppedNavigation = true;
  });

  const originalPushState = window.history.pushState.bind(window.history);
  window.history.pushState = function (
    ...args: Parameters<typeof window.history.pushState>
  ): void {
    poppedNavigation = false;
    originalPushState(...args);
  };
}

/** True when this navigation should restore a previously saved scroll position. */
export function shouldRestoreScroll(): boolean {
  if (typeof window !== 'undefined' && !initialLoadHandled) {
    // Navigation Timing describes the document load, so it is only meaningful on
    // the very first check after a page load (reload / back-forward into the app).
    initialLoadHandled = true;
    const [entry] = performance.getEntriesByType('navigation') as PerformanceNavigationTiming[];
    if (entry && (entry.type === 'reload' || entry.type === 'back_forward')) {
      return true;
    }
  }
  return poppedNavigation;
}

/** Consume the back/forward flag so the next forward navigation starts at top. */
export function clearPopNavigation(): void {
  poppedNavigation = false;
}
