document.addEventListener("DOMContentLoaded", function () {
  // Initialize theme from server-provided mode (authoritative) so auto mode resolves correctly
  const currentTheme = (window.fanspaysiteThemeSwitch && fanspaysiteThemeSwitch.current_mode)
    ? fanspaysiteThemeSwitch.current_mode
    : (localStorage.getItem('theme') || 'light');
  setTheme(currentTheme); // Set the initial theme

  const themeButtons = document.querySelectorAll('.ui.button.fpsMode');
  themeButtons.forEach(button => {
    button.addEventListener('click', function () {
      const theme = this.id.replace('-mode', '');
      setTheme(theme);
      setActiveButton(this);
      updateThemeSetting(theme);
    });
  });

  function setTheme(theme) {
    const isDarkMode = theme === 'dark' || (theme === 'auto' && window.matchMedia("(prefers-color-scheme: dark)").matches);
    // Resolve to actual "dark" or "light" for data-theme so CSS selectors match
    var resolved = isDarkMode ? 'dark' : 'light';
    document.body.dataset.theme = resolved;
    document.documentElement.setAttribute('data-theme', resolved);
    localStorage.setItem('theme', theme); // Store the user's choice (including "auto")
    jQuery("body").toggleClass("inverted", isDarkMode);
    jQuery(".ui").toggleClass("inverted", isDarkMode);
  }

  // Listen for system color scheme changes to update auto mode in real time
  if (window.matchMedia) {
    window.matchMedia("(prefers-color-scheme: dark)").addEventListener('change', function () {
      const storedTheme = localStorage.getItem('theme');
      if (storedTheme === 'auto') {
        setTheme('auto');
      }
    });
  }

  function setActiveButton(activeButton) {
    themeButtons.forEach(button => {
      button.classList.remove('active');
    });
    activeButton.classList.add('active');
  }

  function updateThemeSetting(theme) {
    jQuery.ajax({
      url: fanspaysiteThemeSwitch.ajax_url,
      type: "POST",
      data: {
        action: "fanspaysite_update_theme_mode",
        mode: theme,
        nonce: fanspaysiteThemeSwitch.nonce,
      },
      success: function (response) {
        if (response.warning) {
          console.warn(response.message);
        } else {
          console.log("Theme mode updated using AJAX.");
        }
      },
      error: function (xhr, status, error) {
        console.error("AJAX Error:", status, error);
      }
    });
  }
});
