'use client';

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

/**
 * Auto-opens a list page's create sheet when the URL carries `?create=1`,
 * then strips the param so a refresh / back-nav doesn't re-open it. Used
 * by the topbar's "+ New" dropdown - each menu item navigates to the
 * relevant list page with `?create=1` so the user lands on the right
 * scoped view AND gets the create sheet popped in one click.
 */
export function useCreateFromUrl(onOpen: () => void): void {
  const searchParams = useSearchParams();
  const router = useRouter();

  // Keep the latest `onOpen` in a ref so the effect can call it without
  // depending on it. Callers commonly pass an inline arrow (a fresh
  // identity every render); listing it as a dep would re-run the effect
  // and re-pop the sheet on every parent re-render. The ref lets us drop
  // the eslint-disable while still always invoking the current callback.
  // (Assigned in an effect, not during render, to satisfy react-hooks/refs.)
  const onOpenRef = useRef(onOpen);
  useEffect(() => {
    onOpenRef.current = onOpen;
  }, [onOpen]);

  useEffect(() => {
    if (searchParams.get('create') !== '1') return;
    onOpenRef.current();
    const params = new URLSearchParams(searchParams.toString());
    params.delete('create');
    const newUrl = params.toString() ? `?${params.toString()}` : window.location.pathname;
    // typedRoutes can't statically validate a same-route replace; cast is safe.
    router.replace(newUrl as never);
  }, [searchParams, router]);
}
