"use client";
import { usePathname, useRouter } from "next/navigation";
import { useMemo, useCallback, useEffect, useRef } from "react";
function useApiExplorerNavigation(options) {
  const { basePath, onEndpointChange } = options;
  const pathname = usePathname();
  const router = useRouter();
  const prevPathnameRef = useRef(pathname);
  const selectedEndpoint = useMemo(() => {
    if (!pathname.startsWith(basePath)) return null;
    const relativePath = pathname.slice(basePath.length).replace(/^\//, "");
    if (!relativePath) return null;
    const segments = relativePath.split("/");
    if (segments.length < 2) return null;
    const method = segments[0];
    if (!["GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"].includes(method)) {
      return null;
    }
    const path = "/" + segments.slice(1).join("/");
    return { method, path };
  }, [pathname, basePath]);
  useEffect(() => {
    if (prevPathnameRef.current !== pathname) {
      prevPathnameRef.current = pathname;
      onEndpointChange == null ? void 0 : onEndpointChange((selectedEndpoint == null ? void 0 : selectedEndpoint.method) || null, (selectedEndpoint == null ? void 0 : selectedEndpoint.path) || null);
    }
  }, [pathname, selectedEndpoint, onEndpointChange]);
  const navigateToEndpoint = useCallback(
    (method, path) => {
      const pathSegments = path.replace(/^\//, "");
      const newUrl = `${basePath}/${method}/${pathSegments}`;
      router.push(newUrl);
    },
    [basePath, router]
  );
  const clearSelection = useCallback(() => {
    router.push(basePath);
  }, [basePath, router]);
  return {
    selectedMethod: (selectedEndpoint == null ? void 0 : selectedEndpoint.method) || null,
    selectedPath: (selectedEndpoint == null ? void 0 : selectedEndpoint.path) || null,
    navigateToEndpoint,
    clearSelection
  };
}
export {
  useApiExplorerNavigation
};
