(function() {
  var STORAGE_KEY = 'aegisone_service_theme';
  var themes = ['system', 'dark', 'light'];

  function getSystemTheme() {
    return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
  }

  function applyTheme(theme) {
    var resolved = theme === 'system' ? getSystemTheme() : theme;
    document.documentElement.setAttribute('data-theme', resolved);
    var names = { system: 'Авто', dark: 'Тёмная', light: 'Светлая' };
    var icons = { system: '🖥', dark: '🌙', light: '☀️' };
    var btn = document.getElementById('theme-btn');
    if (btn) {
      btn.textContent = icons[theme] || '🖥';
      btn.title = names[theme] || 'Авто';
    }
  }

  function getNextTheme(current) {
    var idx = themes.indexOf(current);
    return themes[(idx + 1) % themes.length];
  }

  function toggleTheme() {
    var current = localStorage.getItem(STORAGE_KEY) || 'system';
    var next = getNextTheme(current);
    localStorage.setItem(STORAGE_KEY, next);
    applyTheme(next);
  }

  var saved = localStorage.getItem(STORAGE_KEY) || 'system';
  applyTheme(saved);

  window.matchMedia('(prefers-color-scheme: light)').addEventListener('change', function() {
    var current = localStorage.getItem(STORAGE_KEY) || 'system';
    if (current === 'system') {
      applyTheme('system');
    }
  });

  window.toggleTheme = toggleTheme;
})();
