import { useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';

import { type MenuItems } from 'src/pages/dashboard/performance/types';

import { parseMenuItemUrlValue } from '../utils';

/**
 * Reads `?menu=<lowercase>` from the URL as a one-shot signal:
 *
 * - Returns the parsed `MenuItems` value (or `null`) computed synchronously
 *   from the URL at the moment this hook runs. Intended to seed a `useState`
 *   lazy initializer so the first render is already on the right tab.
 * - After mount, strips the `menu` param from the URL with `replace: true`
 *   so it doesn't leak into subsequent internal navigation.
 *
 * Used by `PerformanceReviewProvider` to preselect a menu when arriving from
 * a child route (e.g. CalibrationDetail back button → `?menu=calibration`).
 */
export const useMenuQueryParam = (): MenuItems | null => {
  const [searchParams, setSearchParams] = useSearchParams();
  const initialMenu = parseMenuItemUrlValue(searchParams.get('menu'));

  // biome-ignore lint/correctness/useExhaustiveDependencies: one-shot on mount
  useEffect(() => {
    if (!searchParams.get('menu')) return;
    const next = new URLSearchParams(searchParams);
    next.delete('menu');
    setSearchParams(next, { replace: true });
  }, []);

  return initialMenu;
};
