/**
 * Utility to append localization and context parameters to a URL string.
 */
/**
 * "default" means English and "translated" is a transient UI state the language
 * toggle sets before the real code lands in the URL — neither is a language the
 * API understands, so neither may be written into a link.
 */
function isRealLanguage(lang: string | null | undefined): lang is string {
  return !!lang && lang !== "default" && lang !== "translated";
}

export function getLocalizedUrl(url: string, lang: string | null, franchiseeId?: string | null): string {
  // In-page anchor (e.g. "#footerForm") — must stay on the current page, never rewrite
  // it into a path. The current URL already carries lang/franchiseeId params.
  if (url.startsWith("#")) return url;

  // If no params to add, return original
  if (!isRealLanguage(lang) && !franchiseeId) return url;

  try {
    // Handle both relative and absolute URLs
    // Clean the base URL string to remove potential trailing '?' or other malformed parts
    const cleanUrlString = url.replace(/\?+$/, "");
    const isAbsolute = cleanUrlString.startsWith("http://") || cleanUrlString.startsWith("https://");
    const baseUrl = isAbsolute ? cleanUrlString : `https://dummy.com${cleanUrlString.startsWith("/") ? "" : "/"}${cleanUrlString}`;
    const parsedUrl = new URL(baseUrl);

    // 1. Handle lang parameter
    if (isRealLanguage(lang)) {
      parsedUrl.searchParams.set("lang", lang);
      // Clean up old variant
      parsedUrl.searchParams.delete("language");
    }

    // 2. Handle franchiseeId persistence
    if (franchiseeId) {
      // Clean the ID aggressively (strip any trailing junk)
      const cleanId = franchiseeId.split(/[?&/=\s]/)[0];
      parsedUrl.searchParams.set("franchiseeId", cleanId);
    }

    if (isAbsolute) {
      return parsedUrl.toString();
    }

    // Return relative path + search + hash
    return parsedUrl.pathname + parsedUrl.search + parsedUrl.hash;
  } catch (error) {
    return url;
  }
}
