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

  let savedTheme = null;
  let savedLanguage = null;
  try {
    savedTheme = localStorage.getItem(themeKey);
    savedLanguage = localStorage.getItem(languageKey);
  } catch (_) {}

  const systemDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
  const theme = savedTheme === 'light' || savedTheme === 'dark'
    ? savedTheme
    : (systemDark ? 'dark' : 'light');
  const browserLanguage = (navigator.language || 'en').toLowerCase().split('-')[0];
  const language = supportedLanguages.has(savedLanguage)
    ? savedLanguage
    : (supportedLanguages.has(browserLanguage) ? browserLanguage : 'en');

  root.dataset.apuTheme = theme;
  root.dataset.apuLanguage = language;
  root.lang = language;
  root.style.colorScheme = theme;
})();
