(() => {
  'use strict';
  const root = document.documentElement;
  const THEME_KEY = 'apu-ui-theme';
  const LANGUAGE_KEY = 'apu-ui-language';
  const LEGACY_THEME_KEYS = ['apu-ui-theme-v5.5'];
  const LEGACY_LANGUAGE_KEYS = ['apu-ui-language-v5.5'];
  const supportedLanguages = new Set(['id', 'en', 'ms', 'de', 'vi', 'zh', 'ja']);

  const readStored = (primary, legacyKeys) => {
    try {
      const direct = localStorage.getItem(primary);
      if (direct) return direct;
      for (const key of legacyKeys) {
        const value = localStorage.getItem(key);
        if (value) {
          localStorage.setItem(primary, value);
          return value;
        }
      }
    } catch (_) {}
    return null;
  };

  const savedTheme = readStored(THEME_KEY, LEGACY_THEME_KEYS);
  const savedLanguage = readStored(LANGUAGE_KEY, LEGACY_LANGUAGE_KEYS);
  const systemDark = Boolean(window.matchMedia?.('(prefers-color-scheme: dark)').matches);
  const browserLanguage = (navigator.language || 'en').toLowerCase().split('-')[0];

  const theme = savedTheme === 'light' || savedTheme === 'dark'
    ? savedTheme
    : (systemDark ? 'dark' : 'light');
  const language = supportedLanguages.has(savedLanguage)
    ? savedLanguage
    : (supportedLanguages.has(browserLanguage) ? browserLanguage : 'en');

  root.dataset.apuTheme = theme;
  root.dataset.apuLanguage = language;
  root.lang = language;
  root.dir = 'ltr';
  root.style.colorScheme = theme;
  root.classList.add('apu-theme-bootstrapped');
})();
