import { CONFIG } from '../config.js';

const LANGUAGES = Object.freeze({
  dk: Object.freeze({
    metaDescription: 'Forge Reactor - et kompakt arkadespil fra Brandsborg Interactive.',
    mainMenu: 'Hovedmenu',
    game: 'Spil',
    gameOver: 'Game over',
    tagline: 'Hold kernen stabil. Overlev så længe du kan.',
    startReactor: 'START REAKTOR',
    bestScore: 'BEDSTE SCORE',
    score: 'SCORE',
    temperature: 'TEMPERATUR',
    coreStable: 'REAKTOR STABIL',
    coreTooCold: 'REAKTOR FOR KOLD',
    coreOverheating: 'REAKTOR OVEROPHEDES',
    combo: 'COMBO',
    escapeMenu: 'ESC · MENU',
    backToMenu: 'Tilbage til menu',
    coreFailure: 'REAKTORFEJL',
    reactorFailed: 'FORGE REACTOR FEJLEDE',
    overheated: 'REAKTOREN OVERHEDEDE',
    frozen: 'REAKTOREN FRØS',
    retry: 'PRØV IGEN',
    menu: 'MENU',
    newRecord: 'NY REKORD!',
    previousRecord: 'TIDLIGERE REKORD',
    newRecordLabel: 'NY REKORD',
    byOnePoint: 'MED ÉT POINT!',
    recordMargin: 'DU FORBEDREDE REKORDEN MED {points} POINT',
    openInformation: 'Åbn information',
    closeInformation: 'Luk information',
    informationDialog: 'Information om Forge Reactor',
    informationTabs: 'Informationsfaner',
    information: 'INFORMATION',
    howToPlay: 'SÅDAN SPILLER DU',
    about: 'OM SPILLET',
    howToIntro: 'Klik på cellerne, før de forsvinder. Hold temperaturen mellem 30% og 70%.',
    heatCell: 'VARMECELLE',
    heatCellEffect: 'Opvarmer reaktoren med 10% og giver 18 point.',
    coolantCell: 'KØLEVÆSKE',
    coolantCellEffect: 'Køler reaktoren med 12% og giver 22 point.',
    wasteCell: 'AFFALD',
    wasteCellEffect: 'Opvarmer reaktoren med 17% og koster 35 point.',
    empCell: 'EMP',
    empCellEffect: 'Opvarmer reaktoren med 28% og koster 80 point.',
    tipLabel: 'TIP:',
    gameTip: 'En overset celle øger temperaturen med 3%. Gode træffere i træk opbygger combo.',
    developedBy: 'UDVIKLET AF',
    developmentAssistance: 'UDVIKLINGSASSISTANCE',
    copyrightText: '© 2026 Brandsborg Interactive. Alle rettigheder forbeholdes.',
    legalText: 'Spillet leveres som det er og uden garantier. Brandsborg Interactive kan ikke holdes ansvarlig for direkte eller indirekte tab som følge af brugen. Alle tredjepartsnavne og varemærker tilhører deres respektive ejere.'
  }),
  gb: Object.freeze({
    metaDescription: 'Forge Reactor - a compact arcade game from Brandsborg Interactive.',
    mainMenu: 'Main menu',
    game: 'Game',
    gameOver: 'Game over',
    tagline: 'Keep the core stable. Survive as long as you can.',
    startReactor: 'START REACTOR',
    bestScore: 'HIGH SCORE',
    score: 'SCORE',
    temperature: 'TEMPERATURE',
    coreStable: 'CORE STABLE',
    coreTooCold: 'CORE TOO COLD',
    coreOverheating: 'CORE OVERHEATING',
    combo: 'COMBO',
    escapeMenu: 'ESC · MENU',
    backToMenu: 'Back to menu',
    coreFailure: 'CORE FAILURE',
    reactorFailed: 'FORGE REACTOR FAILED',
    overheated: 'REACTOR OVERHEATED',
    frozen: 'REACTOR FROZE',
    retry: 'PLAY AGAIN',
    menu: 'MENU',
    newRecord: 'NEW RECORD!',
    previousRecord: 'PREVIOUS RECORD',
    newRecordLabel: 'NEW RECORD',
    byOnePoint: 'BY ONE POINT!',
    recordMargin: 'YOU IMPROVED THE RECORD BY {points} POINTS',
    openInformation: 'Open information',
    closeInformation: 'Close information',
    informationDialog: 'Information about Forge Reactor',
    informationTabs: 'Information tabs',
    information: 'INFORMATION',
    howToPlay: 'HOW TO PLAY',
    about: 'ABOUT',
    howToIntro: 'Click the cells before they disappear. Keep the temperature between 30% and 70%.',
    heatCell: 'HEAT CELL',
    heatCellEffect: 'Heats the reactor by 10% and awards 18 points.',
    coolantCell: 'COOLANT',
    coolantCellEffect: 'Cools the reactor by 12% and awards 22 points.',
    wasteCell: 'WASTE',
    wasteCellEffect: 'Heats the reactor by 17% and costs 35 points.',
    empCell: 'EMP',
    empCellEffect: 'Heats the reactor by 28% and costs 80 points.',
    tipLabel: 'TIP:',
    gameTip: 'A missed cell raises the temperature by 3%. Consecutive good hits build your combo.',
    developedBy: 'DEVELOPED BY',
    developmentAssistance: 'DEVELOPMENT ASSISTANCE',
    copyrightText: '© 2026 Brandsborg Interactive. All rights reserved.',
    legalText: 'This game is provided as-is and without warranties. Brandsborg Interactive accepts no liability for direct or indirect loss arising from its use. All third-party names and trademarks belong to their respective owners.'
  })
});

const listeners = new Set();
let currentLanguage = 'dk';

function readLanguage() {
  try {
    const save = JSON.parse(localStorage.getItem(CONFIG.storageKey));
    return save?.language === 'gb' ? 'gb' : 'dk';
  } catch {
    return 'dk';
  }
}

function writeLanguage(language) {
  try {
    const save = JSON.parse(localStorage.getItem(CONFIG.storageKey)) ?? {};
    save.language = language;
    localStorage.setItem(CONFIG.storageKey, JSON.stringify(save));
  } catch {
    localStorage.setItem(CONFIG.storageKey, JSON.stringify({ language }));
  }
}

export function t(key) {
  return LANGUAGES[currentLanguage][key] ?? LANGUAGES.dk[key] ?? key;
}

export function getLanguage() {
  return currentLanguage;
}

export function setLanguage(language, { persist = true } = {}) {
  currentLanguage = language === 'gb' ? 'gb' : 'dk';
  if (persist) writeLanguage(currentLanguage);
  document.documentElement.lang = currentLanguage === 'dk' ? 'da' : 'en';
  document.querySelector('meta[name="description"]')?.setAttribute('content', t('metaDescription'));

  document.querySelectorAll('[data-i18n]').forEach(element => {
    element.textContent = t(element.dataset.i18n);
  });
  document.querySelectorAll('[data-i18n-aria]').forEach(element => {
    element.setAttribute('aria-label', t(element.dataset.i18nAria));
  });
  document.querySelectorAll('[data-language]').forEach(button => {
    const active = button.dataset.language === currentLanguage;
    button.classList.toggle('is-active', active);
    button.setAttribute('aria-pressed', String(active));
  });

  listeners.forEach(listener => listener(currentLanguage));
}

export function initLanguage() {
  setLanguage(readLanguage(), { persist: false });
}

export function onLanguageChange(listener) {
  listeners.add(listener);
  return () => listeners.delete(listener);
}
