export const locales = ["fr", "en", "ar"] as const;
export type Locale = (typeof locales)[number];
export const defaultLocale: Locale = "fr";
export const localeCookieName = "NEXT_LOCALE";

export const localeMeta: Record<Locale, { label: string; short: string; dir: "ltr" | "rtl"; htmlLang: string; intl: string }> = {
  fr: { label: "Français", short: "FR", dir: "ltr", htmlLang: "fr", intl: "fr-MA" },
  en: { label: "English", short: "EN", dir: "ltr", htmlLang: "en", intl: "en-MA" },
  ar: { label: "العربية", short: "AR", dir: "rtl", htmlLang: "ar", intl: "ar-MA" },
};

export function isLocale(value: string | undefined | null): value is Locale {
  return !!value && (locales as readonly string[]).includes(value);
}

export function localePath(locale: Locale, path = "") {
  const clean = path.replace(/^\/(fr|en|ar)(?=\/|$)/, "");
  return `/${locale}${clean.startsWith("/") ? clean : clean ? `/${clean}` : ""}`;
}

export function stripLocale(pathname: string) {
  const segments = pathname.split("/");
  if (isLocale(segments[1])) return "/" + segments.slice(2).join("/");
  return pathname;
}

export function otherLocalePath(pathname: string, next: Locale) {
  const rest = stripLocale(pathname);
  return `/${next}${rest === "/" ? "" : rest}`;
}
