export type LanguageDirection = "rtl" | "ltr";

export type LanguageDefinition = {
  /** ISO 639-1 code — also used as folder name under src/locales/ */
  code: string;
  nativeLabel: string;
  englishLabel: string;
  direction: LanguageDirection;
  htmlLang: string;
  ogLocale: string;
  dateLocale: string;
  /** Show in language picker */
  enabled: boolean;
};

/**
 * Central language registry.
 * To add a new language later:
 * 1. Add entry here with enabled: true
 * 2. Create src/locales/{code}/common.json + seo.json
 * 3. Register bundle in src/lib/i18n/resources.ts
 */
export const LANGUAGE_REGISTRY: Record<string, LanguageDefinition> = {
  fa: {
    code: "fa",
    nativeLabel: "فارسی",
    englishLabel: "Persian",
    direction: "rtl",
    htmlLang: "fa",
    ogLocale: "fa_IR",
    dateLocale: "fa-IR",
    enabled: true,
  },
  en: {
    code: "en",
    nativeLabel: "English",
    englishLabel: "English",
    direction: "ltr",
    htmlLang: "en",
    ogLocale: "en_US",
    dateLocale: "en-US",
    enabled: true,
  },
  // Example for future — set enabled: true after adding locale files:
  // ar: {
  //   code: "ar",
  //   nativeLabel: "العربية",
  //   englishLabel: "Arabic",
  //   direction: "rtl",
  //   htmlLang: "ar",
  //   ogLocale: "ar_SA",
  //   dateLocale: "ar-SA",
  //   enabled: false,
  // },
};

export type AppLanguage = keyof typeof LANGUAGE_REGISTRY;

export const DEFAULT_LANGUAGE: AppLanguage = "fa";

export const LANGUAGE_COOKIE = "modstagram_lang";

export const SUPPORTED_LANGUAGES = Object.keys(LANGUAGE_REGISTRY) as AppLanguage[];

export const ENABLED_LANGUAGES = SUPPORTED_LANGUAGES.filter(
  (code) => LANGUAGE_REGISTRY[code]?.enabled
);

export function getLanguageDefinition(
  code: string | null | undefined
): LanguageDefinition {
  if (code && LANGUAGE_REGISTRY[code]) {
    return LANGUAGE_REGISTRY[code];
  }
  return LANGUAGE_REGISTRY[DEFAULT_LANGUAGE];
}

export function isAppLanguage(
  value: string | null | undefined
): value is AppLanguage {
  return Boolean(value && LANGUAGE_REGISTRY[value]?.enabled);
}

export function getDirection(code: AppLanguage): LanguageDirection {
  return getLanguageDefinition(code).direction;
}

export function normalizeAppLanguage(
  value: string | null | undefined
): AppLanguage {
  return isAppLanguage(value) ? value : DEFAULT_LANGUAGE;
}

/** Legacy map for components that need native/english labels */
export const LANGUAGE_LABELS = Object.fromEntries(
  ENABLED_LANGUAGES.map((code) => {
    const def = LANGUAGE_REGISTRY[code];
    return [code, { native: def.nativeLabel, english: def.englishLabel }];
  })
) as Record<AppLanguage, { native: string; english: string }>;
