import videojs from "video.js";
import videojsEn from "video.js/dist/lang/en.json";
import videojsJa from "video.js/dist/lang/ja.json";
import customEn from "./en.json";
import customJa from "./ja.json";

export const DEFAULT_LANGUAGE = "ja";
export const SUPPORTED_LANGUAGES = ["en", "ja"];

const LANGUAGE_PACKS = {
  en: [videojsEn, customEn],
  ja: [videojsJa, customJa],
};

const registeredLanguages = new Set();

function mergeDictionaries(...dictionaries) {
  return Object.assign({}, ...dictionaries);
}

/**
 * Register a language with Video.js (Video.js base strings + src/lang overrides).
 * Safe to call multiple times; only the first registration loads the full pack.
 */
export function registerLanguage(language) {
  const code = resolveLanguage(language);
  if (registeredLanguages.has(code)) {
    return code;
  }

  const packs = LANGUAGE_PACKS[code];
  if (!packs) {
    return code;
  }

  videojs.addLanguage(code, mergeDictionaries(...packs));
  registeredLanguages.add(code);
  return code;
}

export function registerAllLanguages() {
  SUPPORTED_LANGUAGES.forEach((code) => registerLanguage(code));
}

export function resolveLanguage(language) {
  if (!language) {
    return DEFAULT_LANGUAGE;
  }

  const normalized = String(language).toLowerCase().split("-")[0];
  return SUPPORTED_LANGUAGES.includes(normalized) ? normalized : DEFAULT_LANGUAGE;
}

/**
 * Apply language to a player instance (registers pack if needed).
 *
 * @param {import("video.js").Player} player
 * @param {string} language
 */
export function applyPlayerLanguage(player, language) {
  if (!player) {
    return DEFAULT_LANGUAGE;
  }

  const code = registerLanguage(language);
  player.language(code);
  return code;
}
