/**
 * Theme Toggle — shared across all pages.
 * Reads/writes 'theme' key in localStorage.
 * Injects an animated moon/sun button into the page.
 */
(() => {
  'use strict';

  const STORAGE_KEY = 'theme';

  /* ---------- SVG icons ---------- */
  const moonSVG = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3a7 7 0 0 0 9.79 9.79z"/></svg>`;
  const sunSVG = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>`;

  /* ---------- Apply saved theme BEFORE paint ---------- */
  const saved = localStorage.getItem(STORAGE_KEY);
  if (saved) {
    document.documentElement.setAttribute('data-theme', saved);
  }

  /* ---------- Create button when DOM ready ---------- */
  function init() {
    const isDark = () => document.documentElement.getAttribute('data-theme') !== 'light';

    const btn = document.createElement('button');
    btn.className = 'btn btn-icon-md btn-secondary theme-toggle';
    btn.setAttribute('aria-label', 'Переключить тему');
    btn.innerHTML = isDark() ? moonSVG : sunSVG;

    btn.addEventListener('click', () => {
      const goLight = isDark();
      document.documentElement.setAttribute('data-theme', goLight ? 'light' : 'dark');
      localStorage.setItem(STORAGE_KEY, goLight ? 'light' : 'dark');

      /* Swap icon immediately and trigger a gentle rotate via CSS */
      btn.innerHTML = goLight ? sunSVG : moonSVG;
      const svg = btn.querySelector('svg');
      svg.classList.remove('theme-toggle-icon-enter');
      void svg.offsetWidth;
      svg.classList.add('theme-toggle-icon-enter');
    });

    /* Where to place the button */
    const topbar = document.querySelector('.topbar');
    if (topbar) {
      /* Admin-style pages: insert into topbar (CSS handles flex layout) */
      topbar.appendChild(btn);
    } else {
      /* Login / placeholder pages: fixed position */
      btn.classList.add('theme-toggle--fixed');
      document.body.appendChild(btn);
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
