import Cookies from "js-cookie";
import {
  DEFAULT_LANGUAGE,
  isAppLanguage,
  LANGUAGE_COOKIE,
  type AppLanguage,
} from "./registry";
import {
  resolveLanguageFromLanguageTags,
  resolveLanguageFromSingleTag,
} from "./resolveLanguage";

export function readStoredLanguagePreference(): AppLanguage | null {
  if (typeof window === "undefined") return null;

  const cookieMatch = document.cookie
    .split("; ")
    .find((row) => row.startsWith(`${LANGUAGE_COOKIE}=`))
    ?.split("=")[1];

  if (isAppLanguage(cookieMatch)) return cookieMatch;

  const fromStorage = localStorage.getItem(LANGUAGE_COOKIE);
  if (isAppLanguage(fromStorage)) return fromStorage;

  return null;
}

export function resolveBrowserLanguage(): AppLanguage {
  if (typeof navigator === "undefined") return DEFAULT_LANGUAGE;

  const tags = [
    navigator.language,
    ...(navigator.languages ?? []),
  ].filter(Boolean) as string[];

  return resolveLanguageFromLanguageTags(tags) ?? DEFAULT_LANGUAGE;
}

/** Client locale: saved preference → system language → default (fa) */
export function resolveClientLanguage(): AppLanguage {
  return readStoredLanguagePreference() ?? resolveBrowserLanguage();
}

export function persistLanguagePreference(lang: AppLanguage) {
  Cookies.set(LANGUAGE_COOKIE, lang, { expires: 365, sameSite: "lax" });
  if (typeof window !== "undefined") {
    localStorage.setItem(LANGUAGE_COOKIE, lang);
  }
}

export function resolveLanguageFromNavigatorTag(
  tag: string | null | undefined
): AppLanguage {
  return resolveLanguageFromSingleTag(tag) ?? DEFAULT_LANGUAGE;
}
