'use client';

import { useEffect, useRef } from 'react';
import { usePathname } from 'next/navigation';

import { useBreadcrumbStore } from '@/stores/breadcrumb-store';

/**
 * Tracks in-app navigation so `useSmartBack` can return the user to the
 * page they were actually on rather than just the logical URL parent.
 *
 * Push/pop semantics: when the user navigates forward (new pathname,
 * not equal to the current top of stack), the PREVIOUS pathname is
 * pushed. When the user navigates to whatever's currently on top (i.e.
 * pressed the back button or used browser back), the top is popped.
 * This prevents the infamous back-button-loop ("press back, end up on
 * the page you came from, press back again, return to the page you
 * just left").
 *
 * Mounts once at the app shell so it sees every route change without
 * unmounting. The store is in-memory only - a hard refresh clears the
 * history and the back button falls through to its other resolution
 * tiers (registered hint, then URL-derived parent).
 */
export function NavigationHistoryTracker() {
  const pathname = usePathname();
  // First render's "previous" is null so we don't push a synthetic
  // entry. After the first navigation, this ref holds whatever pathname
  // was active just before the latest route change.
  const previousRef = useRef<string | null>(null);

  useEffect(() => {
    const previous = previousRef.current;
    previousRef.current = pathname;

    // No-op on initial mount and on idempotent renders.
    if (previous === null || previous === pathname) return;

    // Read the live store outside of React's subscription model so this
    // effect doesn't re-fire on every store update (only on route changes).
    const state = useBreadcrumbStore.getState();
    const top = state.historyStack[state.historyStack.length - 1];

    if (top === pathname) {
      // The user navigated back to whatever was on top of the stack - pop
      // it so the next "back" press uses the next-older entry (or falls
      // through to logical parent when the stack is empty).
      state.popHistory();
    } else {
      // Forward navigation: push the previous pathname so the back button
      // on the page we just landed on can return to it.
      state.pushHistory(previous);
    }
  }, [pathname]);

  return null;
}
