import type { Locale } from "@/types";
import { fr } from "./fr";
import { en } from "./en";
import type { Translations } from "./fr";

export const DEFAULT_LOCALE: Locale = "fr";
export const LOCALES: readonly Locale[] = ["fr", "en"] as const;

export const DEMO_URL = "https://demo.missioflow.fr/login.php";

const translations: Record<Locale, Translations> = { fr, en };

/**
 * Table de correspondance des routes entre FR et EN.
 * Clé = chemin FR (sans prefix), Valeur = slug EN (sans /en/).
 */
const routeMap: Record<string, string> = {
  "/": "/",
  "/fonctionnalites": "/features",
  "/tarifs": "/pricing",
  "/a-propos": "/about",
  "/contact": "/contact",
  "/mentions-legales": "/legal",
  "/cgv": "/terms",
  "/confidentialite": "/privacy",
};

const reverseRouteMap: Record<string, string> = Object.fromEntries(
  Object.entries(routeMap).map(([fr, en]) => [en, fr])
);

export function t(locale: Locale): Translations {
  return translations[locale] ?? translations[DEFAULT_LOCALE];
}

export function getLocaleFromUrl(url: URL): Locale {
  const [, segment] = url.pathname.split("/");
  if (LOCALES.includes(segment as Locale) && segment !== DEFAULT_LOCALE) {
    return segment as Locale;
  }
  return DEFAULT_LOCALE;
}

export function localePath(path: string, locale: Locale): string {
  const cleanPath = path.startsWith("/") ? path : `/${path}`;
  if (locale === DEFAULT_LOCALE) return cleanPath;
  return `/${locale}${cleanPath}`;
}

/**
 * Retourne le chemin équivalent dans l'autre langue.
 * Ex: "/en/features" → "/fonctionnalites", "/tarifs" → "/en/pricing"
 */
export function getAlternatePath(currentPath: string, currentLocale: Locale, targetLocale: Locale): string {
  // Normaliser : retirer le trailing slash (sauf pour "/")
  let normalized = currentPath;
  while (normalized.length > 1 && normalized.endsWith("/")) {
    normalized = normalized.slice(0, -1);
  }
  normalized = normalized || "/";

  // Extraire le chemin "nu" (sans prefix de locale)
  let barePath = normalized;
  if (currentLocale !== DEFAULT_LOCALE && barePath.startsWith(`/${currentLocale}/`)) {
    barePath = barePath.slice(currentLocale.length + 1);
  } else if (currentLocale !== DEFAULT_LOCALE && barePath === `/${currentLocale}`) {
    barePath = "/";
  }

  if (targetLocale === "fr") {
    // EN → FR : chercher dans reverseRouteMap
    return reverseRouteMap[barePath] ?? barePath;
  }
  // FR → EN : chercher dans routeMap
  const enSlug = routeMap[barePath] ?? barePath;
  return `/en${enSlug}`;
}

export function getAlternateLocales(currentPath: string, currentLocale: Locale): { locale: Locale; href: string }[] {
  return LOCALES.map((locale) => ({
    locale,
    href: locale === currentLocale
      ? currentPath
      : getAlternatePath(currentPath, currentLocale, locale),
  }));
}

export function getLocaleLabel(locale: Locale): string {
  const labels: Record<Locale, string> = {
    fr: "Français",
    en: "English",
  };
  return labels[locale];
}
