'use client';

import { useEffect } 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();

  useEffect(() => {
    if (searchParams.get('create') !== '1') return;
    onOpen();
    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);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchParams]);
}
