export function useNavigation() {
  function normalizePath(url: string): string {
    try {
      return new URL(url, window.location.origin).pathname;
    } catch {
      return url;
    }
  }

  function isNavActive(
    route: string | null | undefined,
    currentUrl: string,
  ): boolean {
    if (!route) return false;
    const routePath = normalizePath(route);
    const current = normalizePath(currentUrl);
    if (current === routePath) return true;
    if (current.startsWith(routePath + "/")) {
      // Only treat sub-paths as active when the next segment is a numeric
      // resource ID or the 'create' action — not named sub-routes like
      // '/menus/locations' which have their own nav item.
      const remainder = current.slice(routePath.length + 1);
      const firstSegment = remainder.split("/")[0];
      return firstSegment === "create" || /^\d+$/.test(firstSegment);
    }
    return false;
  }

  function isGroupActive(
    children: { route?: string | null }[],
    currentUrl: string,
  ): boolean {
    return children.some((child) => isNavActive(child.route, currentUrl));
  }

  return { normalizePath, isNavActive, isGroupActive };
}
