export const SUPPORTED_LOCALES = ["pl", "en", "de"] as const;
export type SupportedLocale = (typeof SUPPORTED_LOCALES)[number];
export const DEFAULT_LOCALE: SupportedLocale = "pl";

export const LOCALE_LABELS: Record<SupportedLocale, string> = {
  pl: "Polski",
  en: "English",
  de: "Deutsch",
};

export const LOCALE_SHORT_LABELS: Record<SupportedLocale, string> = {
  pl: "PL",
  en: "EN",
  de: "DE",
};

const STORAGE_KEY = "laskar_locale";

export function isSupportedLocale(value?: string | null): value is SupportedLocale {
  return !!value && (SUPPORTED_LOCALES as readonly string[]).includes(value);
}

export function normalizeLocale(value?: string | null): SupportedLocale {
  if (!value) return DEFAULT_LOCALE;
  const normalized = value.toLowerCase().split("-")[0];
  return isSupportedLocale(normalized) ? normalized : DEFAULT_LOCALE;
}

export function getLocaleFromPathname(pathname?: string | null): SupportedLocale {
  if (!pathname) return DEFAULT_LOCALE;
  const firstSegment = pathname.split("/").filter(Boolean)[0];
  return isSupportedLocale(firstSegment) ? firstSegment : DEFAULT_LOCALE;
}

export function stripLocaleFromPathname(pathname: string): string {
  const parts = pathname.split("/").filter(Boolean);
  if (parts.length && isSupportedLocale(parts[0])) parts.shift();
  return `/${parts.join("/")}`.replace(/\/$/, "") || "/";
}

export function localizedPath(pathname: string, locale: SupportedLocale): string {
  const cleanPath = stripLocaleFromPathname(pathname || "/");
  if (locale === DEFAULT_LOCALE) return cleanPath;
  return cleanPath === "/" ? `/${locale}` : `/${locale}${cleanPath}`;
}

export function getSavedLocale(): SupportedLocale | null {
  if (typeof window === "undefined") return null;
  const saved = window.localStorage.getItem(STORAGE_KEY);
  return isSupportedLocale(saved) ? saved : null;
}

export function saveLocale(locale: SupportedLocale) {
  if (typeof window === "undefined") return;
  window.localStorage.setItem(STORAGE_KEY, locale);
}

export function getBrowserLocale(): SupportedLocale {
  if (typeof window === "undefined") return DEFAULT_LOCALE;
  return normalizeLocale(window.navigator.language || window.navigator.languages?.[0]);
}

export function getCurrentLocale(): SupportedLocale {
  if (typeof window === "undefined") return DEFAULT_LOCALE;

  const urlLocale = getLocaleFromPathname(window.location.pathname);
  if (urlLocale !== DEFAULT_LOCALE || window.location.pathname.startsWith("/pl")) {
    return urlLocale;
  }

  const paramsLocale = new URLSearchParams(window.location.search).get("locale");
  if (isSupportedLocale(paramsLocale)) return paramsLocale;

  return DEFAULT_LOCALE;
}

export function getPreferredLocale(): SupportedLocale {
  if (typeof window === "undefined") return DEFAULT_LOCALE;
  return getSavedLocale() || getBrowserLocale() || DEFAULT_LOCALE;
}

export function withLocale(path: string, locale: SupportedLocale = getCurrentLocale()) {
  return localizedPath(path, locale);
}
