/*
 * Echo6 Theme Toggle for Open WebUI
 * Adds a small button (bottom-right) that toggles the .echo6 class
 * on <html>, activating/deactivating the companion CSS theme.
 * Persists preference in localStorage.
 */
(function () {
  'use strict';

  var STORAGE_KEY = 'echo6-theme-active';
  var html = document.documentElement;

  // Restore saved state immediately (before paint if possible)
  var saved = localStorage.getItem(STORAGE_KEY);
  if (saved === 'true') {
    html.classList.add('echo6');
  }

  function createToggle() {
    // Don't double-inject
    if (document.getElementById('echo6-toggle')) return;

    var btn = document.createElement('button');
    btn.id = 'echo6-toggle';
    btn.textContent = 'E6';
    btn.title = 'Toggle Echo6 theme';
    btn.setAttribute('aria-label', 'Toggle Echo6 theme');

    // Sync active state with current class
    if (html.classList.contains('echo6')) {
      btn.classList.add('active');
    }

    btn.addEventListener('click', function () {
      var isActive = html.classList.toggle('echo6');
      btn.classList.toggle('active', isActive);
      localStorage.setItem(STORAGE_KEY, isActive ? 'true' : 'false');
    });

    document.body.appendChild(btn);
  }

  // Inject once DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', createToggle);
  } else {
    createToggle();
  }
})();
