/** Join studio path prefix with an in-site href (supports query strings). */
export function joinStudioPath(basePath: string, href: string): string {
  if (
    !href ||
    href.startsWith("http://") ||
    href.startsWith("https://") ||
    href.startsWith("mailto:") ||
    href.startsWith("tel:") ||
    href.startsWith("#")
  ) {
    return href;
  }

  const hashIndex = href.indexOf("#");
  const hash = hashIndex >= 0 ? href.slice(hashIndex) : "";
  const withoutHash = hashIndex >= 0 ? href.slice(0, hashIndex) : href;
  const qIndex = withoutHash.indexOf("?");
  const search = qIndex >= 0 ? withoutHash.slice(qIndex) : "";
  const pathname = qIndex >= 0 ? withoutHash.slice(0, qIndex) : withoutHash;

  const path =
    !pathname || pathname === "/"
      ? "/"
      : pathname.startsWith("/")
        ? pathname
        : `/${pathname}`;

  const prefix = basePath.replace(/\/$/, "");
  const full = path === "/" ? prefix || "/" : `${prefix}${path}`;
  return `${full}${search}${hash}`;
}
