export interface RouteMapping {
  en: string;
  fr: string;
  aliases?: string[];
}

export const ROUTE_MAP: RouteMapping[] = [
  { en: "/", fr: "/" },
  { en: "/about-us", fr: "/a-propos", aliases: ["/a-propos-de-nous"] },
  { en: "/blogs", fr: "/blog", aliases: ["/blogs"] },
  { en: "/book-appointment", fr: "/prendre-rendez-vous", aliases: ["/book-an-appointement", "/rendez-vous"] },

  // Clinics and Doctors
  { en: "/clinics-and-doctors", fr: "/cliniques", aliases: ["/cliniques-et-medecins", "/our-clinics-and-doctors"] },
  { en: "/clinics-and-doctors/buelle", fr: "/clinique-moleson-bulle", aliases: ["/cliniques-et-medecins/buelle", "/our-clinics-and-doctors/buelle-clinic", "/clinics-and-doctors/buelle-clinic"] },
  { en: "/clinics-and-doctors/lausanne", fr: "/clinique-ophtalmologique-lausanne", aliases: ["/cliniques-et-medecins/lausanne", "/our-clinics-and-doctors/lausanne-clinic", "/clinics-and-doctors/lausanne-clinic"] },
  { en: "/clinics-and-doctors/renens", fr: "/clinique-ophtalmologique-renens", aliases: ["/cliniques-et-medecins/renens", "/our-clinics-and-doctors/renens-clinic", "/clinics-and-doctors/renens-clinic"] },
  { en: "/clinics-and-doctors/romont", fr: "/clinique-ophtalmologique-romont", aliases: ["/cliniques-et-medecins/romont", "/our-clinics-and-doctors/romont-clinic", "/clinics-and-doctors/romont-clinic"] },

  // Ophthalmology
  { en: "/ophthalmology/laser-vision-correction", fr: "/laser-yeux", aliases: ["/ophtalmologie/correction-vision-laser", "/laser-eye-surgery", "/chirurgie-laser-des-yeux"] },
  { en: "/ophthalmology/cataract", fr: "/ophtalmologie/cataracte", aliases: ["/cataract", "/cataracte"] },
  { en: "/ophthalmology/glaucoma", fr: "/ophtalmologie/glaucome", aliases: ["/glaucoma", "/glaucome"] },
  { en: "/ophthalmology/macula", fr: "/ophtalmologie/dmla", aliases: ["/ophtalmologie/macula", "/macula"] },
  { en: "/ophthalmology/pediatrics", fr: "/ophtalmologie-pediatrique", aliases: ["/ophtalmologie/pediatrie", "/pediatrics", "/ophtalmopediatrie"] },

  // Aesthetic Main & About
  { en: "/aesthetic", fr: "/esthetique" },
  { en: "/aesthetic/about-aesthetic", fr: "/esthetique", aliases: ["/esthetique/a-propos"] },

  // Aesthetic Medicine
  { en: "/aesthetic/aesthetic-medicine", fr: "/medecine-esthetique", aliases: ["/esthetique/medecine-esthetique"] },
  { en: "/aesthetic/aesthetic-medicine/hyluronic-acid", fr: "/medecine-esthetique/acide-hyaluronique", aliases: ["/esthetique/medecine-esthetique/acide-hyaluronique"] },
  { en: "/aesthetic/aesthetic-medicine/botulinum", fr: "/medecine-esthetique/injections-anti-rides", aliases: ["/esthetique/medecine-esthetique/toxine-botulique", "/botulinum"] },

  // Aesthetic Surgery
  { en: "/aesthetic/aesthetic-surgery", fr: "/chirurgie-esthetique", aliases: ["/esthetique/chirurgie-esthetique"] },
  { en: "/aesthetic/aesthetic-surgery/breast-augmentation", fr: "/chirurgie-esthetique/augmentation-mammaire", aliases: ["/esthetique/chirurgie-esthetique/augmentation-mammaire"] },
  { en: "/aesthetic/aesthetic-surgery/breast-reduction", fr: "/chirurgie-esthetique/reduction-mammaire", aliases: ["/esthetique/chirurgie-esthetique/reduction-mammaire"] },
  { en: "/aesthetic/aesthetic-surgery/breast-lift", fr: "/chirurgie-esthetique/lifting-mammaire", aliases: ["/esthetique/chirurgie-esthetique/lifting-mammaire", "/cosmetic-landing-fr/cosmetic-surgery-fr/lifting-de-la-poitrine"] },
  { en: "/aesthetic/aesthetic-surgery/blepharoplasty", fr: "/chirurgie-esthetique/blepharoplastie", aliases: ["/esthetique/chirurgie-esthetique/blepharoplastie"] },

  // Aesthetic Care
  { en: "/aesthetic/aesthetic-care", fr: "/soins-esthetiques", aliases: ["/esthetique/soins-esthetiques"] },
  { en: "/aesthetic/aesthetic-care/peeling", fr: "/soins-esthetiques/peeling", aliases: ["/esthetique/soins-esthetiques/peeling"] },
  { en: "/aesthetic/aesthetic-care/permanent-hair-removal", fr: "/epilation-laser", aliases: ["/esthetique/soins-esthetiques/epilation-definitive"] },
  { en: "/aesthetic/aesthetic-care/pico-laser-tattoo-removal", fr: "/detatouage-laser", aliases: ["/esthetique/soins-esthetiques/detatouage-laser-pico"] },

  // General Services
  { en: "/general/about-general-services", fr: "/specialites-medicales", aliases: ["/general/a-propos-des-soins-generaux", "/general-landing"] },
  { en: "/general/general-medicine", fr: "/medecine-generale", aliases: ["/general/medecine-generale", "/general-landing/general-internal-medicine", "/medecine-de-famille"] },
  { en: "/general/orthopaedics", fr: "/orthopedie", aliases: ["/general/orthopedie", "/general-landing/orthopaedic-surgery"] },

  // Utilities
  { en: "/precaution-and-faq", fr: "/faq", aliases: ["/precautions-et-faq", "/precaution-and-faq"] },
  { en: "/cookies", fr: "/cookies" },
  { en: "/styleguide", fr: "/styleguide" },
];

/**
 * Normalizes a URL path string:
 * Removes trailing slash (unless root "/"), domain prefixes, hash/query params, and leading double slashes.
 */
export function normalizePath(rawPath?: string): string {
  if (!rawPath) return "/";
  let cleaned = rawPath.trim();

  // Strip protocol and domain if full URL is passed
  cleaned = cleaned.replace(/^https?:\/\/[^/]+/, "");

  // Strip query params or hash
  cleaned = cleaned.split("?")[0].split("#")[0];

  // Strip trailing -fr if appended by CMS
  if (cleaned.endsWith("-fr") && cleaned !== "/cosmetic-landing-fr") {
    cleaned = cleaned.replace(/-fr$/, "");
  }

  // Ensure leading slash
  if (!cleaned.startsWith("/")) {
    cleaned = "/" + cleaned;
  }

  // Remove trailing slash if length > 1
  if (cleaned.length > 1 && cleaned.endsWith("/")) {
    cleaned = cleaned.slice(0, -1);
  }

  return cleaned.toLowerCase();
}

/**
 * Resolves a given pathname to route info (English internal path, French URL path, language, and whether it's a French URL).
 */
export function resolveRoute(rawPath: string) {
  const normalized = normalizePath(rawPath);

  // Exact match search in ROUTE_MAP
  for (const item of ROUTE_MAP) {
    if (item.fr === normalized && item.fr !== item.en) {
      return { enPath: item.en, frPath: item.fr, isFrenchUrl: true, lang: "fr" as const };
    }
    if (item.en === normalized) {
      return { enPath: item.en, frPath: item.fr, isFrenchUrl: false, lang: "en" as const };
    }
    if (item.aliases?.includes(normalized)) {
      return { enPath: item.en, frPath: item.fr, isFrenchUrl: false, lang: "en" as const };
    }
  }

  // Check prefix matches for nested routes or dynamic routes
  for (const item of ROUTE_MAP) {
    if (item.fr !== "/" && normalized.startsWith(item.fr + "/")) {
      const rest = normalized.slice(item.fr.length);
      return { enPath: item.en + rest, frPath: normalized, isFrenchUrl: true, lang: "fr" as const };
    }
    if (item.en !== "/" && normalized.startsWith(item.en + "/")) {
      const rest = normalized.slice(item.en.length);
      return { enPath: normalized, frPath: item.fr + rest, isFrenchUrl: false, lang: "en" as const };
    }
  }

  // Fallback for unmapped or dynamic routes (e.g., /blogs/slug or /blog/slug)
  return { enPath: normalized, frPath: normalized, isFrenchUrl: false, lang: "en" as const };
}

/**
 * Returns the French URL path for any given path (English or French).
 */
export function getFrenchUrl(rawPath: string): string {
  if (!rawPath || rawPath === "#") return rawPath;
  const resolved = resolveRoute(rawPath);
  return resolved.frPath;
}

/**
 * Returns the internal English path for any given path (English or French).
 */
export function getEnglishUrl(rawPath: string): string {
  if (!rawPath || rawPath === "#") return rawPath;
  const resolved = resolveRoute(rawPath);
  return resolved.enPath;
}

/**
 * Returns the localized URL path based on target language ('en' | 'fr').
 * If targetLang is omitted, automatically detects active cookie language on client (defaulting to 'fr').
 */
export function getLocalizedUrl(rawPath: string, targetLang?: "en" | "fr"): string {
  if (!rawPath || rawPath === "#" || rawPath.startsWith("tel:") || rawPath.startsWith("mailto:")) {
    return rawPath;
  }

  // Determine language preference: use targetLang if passed, otherwise check client cookie, defaulting to 'fr'
  let lang: "en" | "fr" = targetLang || "fr";
  if (!targetLang && typeof document !== "undefined") {
    const matches = document.cookie.match(/(?:^|; )lang=([^;]*)/);
    const cookieLang = matches ? matches[1]?.toLowerCase() : "fr";
    if (cookieLang === "en" || cookieLang === "fr") {
      lang = cookieLang;
    }
  }

  let pathToResolve = rawPath;

  // If full URL is passed (e.g. from CMS or absolute site links), strip internal/same-origin domain so Next.js Link performs client routing
  if (pathToResolve.startsWith("http://") || pathToResolve.startsWith("https://")) {
    try {
      const urlObj = new URL(pathToResolve);
      const host = urlObj.hostname;
      if (
        host === "localhost" ||
        host === "127.0.0.1" ||
        host.includes("oculus") ||
        host.includes("staging") ||
        host.includes("vercel.app")
      ) {
        pathToResolve = urlObj.pathname + urlObj.search + urlObj.hash;
      } else {
        return rawPath; // External link (e.g. Google Maps, Social Media)
      }
    } catch {
      return rawPath;
    }
  }

  // Preserve query parameters if present in rawPath
  const [basePath, queryString] = pathToResolve.split("?");
  const resolved = resolveRoute(basePath);
  const targetBase = lang === "fr" ? resolved.frPath : resolved.enPath;

  return queryString ? `${targetBase}?${queryString}` : targetBase;
}
