"use client"
import { usePathname, useSearchParams } from "next/navigation";

type OptionalParams = Record<string, string>;
/**
 * This hook is simplifying working with the **Parallel modal** routes.
 * It takes actual `modal` path, current `origin` and **optional** `additional` params.
 * In case when we don't put the `origin` argument, it will be replaced with current pathname and search params.
 * @param modal
 * @param origin
 * @param params
 * @return string
 */

export default function useParallelModalRoute(modal: string, origin?: string, params?: OptionalParams): string {
  const sp = useSearchParams();
  const pathname = usePathname();

  const originSearchParams = new URLSearchParams(sp);
  const modalSearchParams = new URLSearchParams();
  modalSearchParams.append("origin", origin || (pathname + "?" + originSearchParams));
  modalSearchParams.append("modal", modal);

  if (params) {
    for (let key in params) {
      const isExists = sp.get(key) !== undefined;
      if (isExists) {
        modalSearchParams.set(key, params[key]);
      } else {
        modalSearchParams.append(key, params[key]);
      }
    }
  }

  return modal + "?" + modalSearchParams.toString();
}
