const SUPPORTED_UI_LANGUAGES = [
  'cs',
  'da',
  'de',
  'en',
  'es',
  'fi',
  'fr',
  'it',
  'ja',
  'ko',
  'nb',
  'nl',
  'pl',
  'pt_BR',
  'ru',
  'sv',
  'tr',
  'zh_CN',
  'zh_TW',
  // Kept for system / previously saved preference (Hong Kong)
  'zh_HK'
];
const UI_LANGUAGE_STORAGE_KEY = 'uiLanguage';

let customMessages = null;
let currentUILanguage = 'system';
let localizationReady = null;

const originalGetMessage = chrome.i18n.getMessage.bind(chrome.i18n);

function applySubstitutions(message, substitutions) {
  if (!substitutions) {
    return message;
  }

  const values = Array.isArray(substitutions) ? substitutions : [substitutions];
  return values.reduce((text, value, index) => {
    return text.replace(new RegExp(`\\$${index + 1}`, 'g'), String(value));
  }, message);
}

function resolveMessage(messageName, substitutions) {
  if (customMessages && customMessages[messageName] && customMessages[messageName].message) {
    return applySubstitutions(customMessages[messageName].message, substitutions);
  }
  return originalGetMessage(messageName, substitutions) || '';
}

// 覆盖 chrome.i18n.getMessage，使手动选择的语言对全局生效
chrome.i18n.getMessage = function(messageName, substitutions) {
  return resolveMessage(messageName, substitutions);
};

async function loadLocaleMessages(locale) {
  if (!SUPPORTED_UI_LANGUAGES.includes(locale)) {
    return null;
  }

  const url = chrome.runtime.getURL(`_locales/${locale}/messages.json`);
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`Failed to load locale: ${locale}`);
  }
  return response.json();
}

async function applyUILanguage(language) {
  const nextLanguage = language || 'system';

  if (nextLanguage === 'system' || !SUPPORTED_UI_LANGUAGES.includes(nextLanguage)) {
    customMessages = null;
    currentUILanguage = 'system';
  } else {
    customMessages = await loadLocaleMessages(nextLanguage);
    currentUILanguage = nextLanguage;
  }

  document.documentElement.lang = currentUILanguage === 'system'
    ? (chrome.i18n.getUILanguage() || 'en')
    : currentUILanguage.replace('_', '-');

  if (document.readyState !== 'loading') {
    window.updateUILanguage();
    document.dispatchEvent(new CustomEvent('uilanguagechange'));
    if (window.WelcomeManager && typeof window.WelcomeManager.updateWelcomeMessage === 'function') {
      window.WelcomeManager.updateWelcomeMessage();
    }
  }
}

window.getSupportedUILanguages = function() {
  return SUPPORTED_UI_LANGUAGES.slice();
};

window.getCurrentUILanguage = function() {
  return currentUILanguage;
};

window.setUILanguage = async function(language) {
  const nextLanguage = language || 'system';
  localStorage.setItem(UI_LANGUAGE_STORAGE_KEY, nextLanguage);
  chrome.storage.sync.set({ [UI_LANGUAGE_STORAGE_KEY]: nextLanguage });
  await applyUILanguage(nextLanguage);
};

window.getLocalizedMessage = function(messageName, substitutions) {
  return resolveMessage(messageName, substitutions);
};

window.updateUILanguage = function() {
  document.querySelectorAll('[data-i18n]').forEach((element) => {
    // 欢迎语由 WelcomeManager 单独组装（问候语 + 用户名），跳过 data-i18n 覆盖
    if (element.id === 'welcome-message') {
      return;
    }
    // Toast 文案由调用方动态设置，不能被全局 i18n 重置
    if (element.closest('#more-button-toast')) {
      return;
    }
    const messageName = element.getAttribute('data-i18n');
    const localizedMessage = window.getLocalizedMessage(messageName);
    if (localizedMessage) {
      element.textContent = localizedMessage;
    }
  });

  document.querySelectorAll('[data-i18n-placeholder]').forEach((element) => {
    const messageName = element.getAttribute('data-i18n-placeholder');
    const localizedMessage = window.getLocalizedMessage(messageName);
    if (localizedMessage) {
      element.placeholder = localizedMessage;
    }
  });

  document.querySelectorAll('[data-i18n-title]').forEach((element) => {
    const messageName = element.getAttribute('data-i18n-title');
    const localizedMessage = window.getLocalizedMessage(messageName);
    if (localizedMessage) {
      element.title = localizedMessage;
    }
  });

  document.querySelectorAll('[data-i18n-aria-label]').forEach((element) => {
    const messageName = element.getAttribute('data-i18n-aria-label');
    const localizedMessage = window.getLocalizedMessage(messageName);
    if (localizedMessage) {
      element.setAttribute('aria-label', localizedMessage);
    }
  });

  // Keep Chrome's tab strip title aligned with the localized extension name.
  const extName = window.getLocalizedMessage('extName');
  if (extName && document.title !== extName) {
    document.title = extName;
  }

  if (window.WelcomeManager && typeof window.WelcomeManager.updateWelcomeMessage === 'function') {
    window.WelcomeManager.updateWelcomeMessage();
  }
};

window.initLocalization = function() {
  if (localizationReady) {
    return localizationReady;
  }

  localizationReady = new Promise((resolve) => {
    const cachedLanguage = localStorage.getItem(UI_LANGUAGE_STORAGE_KEY) || 'system';

    chrome.storage.sync.get({ [UI_LANGUAGE_STORAGE_KEY]: cachedLanguage }, async (result) => {
      const preferredLanguage = result[UI_LANGUAGE_STORAGE_KEY] || 'system';
      if (preferredLanguage !== cachedLanguage) {
        localStorage.setItem(UI_LANGUAGE_STORAGE_KEY, preferredLanguage);
      }

      try {
        await applyUILanguage(preferredLanguage);
      } catch (error) {
        console.error('Failed to apply UI language:', error);
        customMessages = null;
        currentUILanguage = 'system';
      }
      resolve(currentUILanguage);
    });
  });

  return localizationReady;
};

document.addEventListener('DOMContentLoaded', () => {
  window.initLocalization().then(() => {
    window.updateUILanguage();
    document.dispatchEvent(new CustomEvent('uilanguagechange'));
  });
});
