"use client";

import {
  useRouter,
  usePathname,
  useSearchParams,
} from "next/navigation";
import { useCallback, useMemo } from "react";

export type NavigateFunction = (
  to: string | number,
  options?: { replace?: boolean; state?: unknown },
) => void;

export function useLocation(): {
  pathname: string;
  search: string;
  hash: string;
  state: unknown;
  key: string;
} {
  const pathname = usePathname() ?? "/";
  const searchParams = useSearchParams();
  const search = useMemo(() => {
    const q = searchParams.toString();
    return q ? `?${q}` : "";
  }, [searchParams]);

  return {
    pathname,
    search,
    hash: "",
    state: null,
    key: pathname + search,
  };
}

export function useNavigate(): NavigateFunction {
  const router = useRouter();

  return useCallback(
    (to: string | number, options?: { replace?: boolean }) => {
      if (typeof to === "number") {
        if (to < 0) router.back();
        else if (to > 0) router.forward();
        return;
      }
      if (options?.replace) router.replace(to);
      else router.push(to);
    },
    [router],
  );
}