/**
 * Utility to append localization and context parameters to a URL string.
 */

/** A link to another website: an absolute http(s) URL. */
export function isExternalUrl(url: string): boolean {
  return /^https?:\/\//i.test(url.trim());
}

/** mailto:, tel:, sms: and friends - not pages, and not ours to rewrite. */
export function hasNonWebScheme(url: string): boolean {
  const trimmed = url.trim();
  // Matches "scheme:" but not a protocol-relative "//host" or a bare path.
  return /^[a-z][a-z0-9+.-]*:/i.test(trimmed) && !isExternalUrl(trimmed);
}
/**
 * "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;

  // Anything that is not a web page on this site is returned untouched.
  //
  // `mailto:` and `tel:` were being treated as relative paths and rewritten to
  // "/mailto:support@..." — broken links, but only once a language was active,
  // which is why they looked fine in English.
  //
  // Absolute http(s) URLs point at another site, and our language and franchise
  // id mean nothing there: appending them produced
  // "https://maps.google.com/?q=x&lang=de&franchiseeId=..." and handed a third
  // party the franchise id for no reason.
  if (isExternalUrl(url) || hasNonWebScheme(url)) 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;
  }
}
