/* ==========================================================================
   Niwa Chatbot -- Theme Switcher
   ---------------------------------------------------------------------------
   Resolves neutral, light, dark, or automatic system theme on .niwa-widget.

   PERSISTENCE:  localStorage key "niwa-theme"
   PRIORITY:     localized config > rendered widget attribute > OS preference.
                  Stored theme is only used when a real frontend toggle exists.

   NAMESPACE: window.Niwa.ThemeSwitcher
   ========================================================================== */

window.Niwa = window.Niwa || {};

window.Niwa.ThemeSwitcher = (function () {
  'use strict';

  var STORAGE_KEY = 'niwa-theme';
  var widgets = [];
  var toggleBtn = null;
  var currentTheme = 'neutral';
  var currentMode = 'neutral';
  var mediaQuery = null;

  function isTheme(value) {
    return value === 'neutral' || value === 'light' || value === 'dark';
  }

  function isMode(value) {
    return value === 'neutral' || value === 'light' || value === 'dark' || value === 'auto';
  }

  function getStoredTheme() {
    try {
      var stored = localStorage.getItem(STORAGE_KEY);
      return isTheme(stored) ? stored : '';
    } catch (e) {
      return '';
    }
  }

  function getSystemTheme() {
    return mediaQuery && mediaQuery.matches ? 'dark' : 'light';
  }

  function getRenderedMode() {
    for (var i = 0; i < widgets.length; i++) {
      var mode = widgets[i].getAttribute('data-niwa-theme');
      if (isMode(mode)) {
        return mode;
      }
    }

    return '';
  }

  function resolveMode() {
    var adminMode = window.NiwaAI && window.NiwaAI.chat_theme_mode;
    if (isMode(adminMode)) {
      return adminMode;
    }

    var renderedMode = getRenderedMode();
    if (isMode(renderedMode)) {
      return renderedMode;
    }

    return 'neutral';
  }

  function resolveTheme(mode) {
    if (isTheme(mode)) {
      return mode;
    }

    // Auto should follow the OS by default.
    // Only honor localStorage when an actual frontend toggle exists.
    if (mode === 'auto') {
      var stored = toggleBtn ? getStoredTheme() : '';
      return stored || getSystemTheme();
    }

    var renderedMode = getRenderedMode();
    if (isTheme(renderedMode)) {
      return renderedMode;
    }

    return getStoredTheme() || getSystemTheme();
  }

  function bindSystemThemeListener() {
    if (!mediaQuery) return;

    var handleChange = function (e) {
      if (currentMode !== 'auto') {
        return;
      }

      if (toggleBtn && getStoredTheme()) {
        return;
      }

      apply(e.matches ? 'dark' : 'light');
    };

    if (typeof mediaQuery.addEventListener === 'function') {
      mediaQuery.addEventListener('change', handleChange);
    } else if (typeof mediaQuery.addListener === 'function') {
      mediaQuery.addListener(handleChange);
    }
  }

  function init() {
    widgets = Array.prototype.slice.call(document.querySelectorAll('.niwa-widget'));
    toggleBtn = document.getElementById('niwaThemeToggle');
    mediaQuery = window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null;

    if (!widgets.length) return;

    currentMode = resolveMode();
    currentTheme = resolveTheme(currentMode);

    apply(currentTheme);

    // Toggle button
    if (toggleBtn) {
      toggleBtn.addEventListener('click', toggle);
    }

    bindSystemThemeListener();
  }

  function toggle() {
    var newTheme = currentTheme === 'light' ? 'dark' : 'light';
    apply(newTheme);
    try {
      localStorage.setItem(STORAGE_KEY, newTheme);
    } catch (e) { /* ignore */ }
  }

  function apply(theme) {
    currentTheme = theme;
    for (var i = 0; i < widgets.length; i++) {
      widgets[i].setAttribute('data-niwa-theme', theme);
    }

    // Update toggle switch visual
    if (toggleBtn) {
      if (theme === 'dark') {
        toggleBtn.classList.add('niwa-switch--active');
      } else {
        toggleBtn.classList.remove('niwa-switch--active');
      }
    }
  }

  return {
    init: init,
    toggle: toggle,
    apply: apply,
    get currentTheme() { return currentTheme; }
  };
})();
