/**
 * Theme controller — persists the user's light/dark preference.
 *
 * Bootstrap 5.3 reads the `data-bs-theme` attribute on <html>. We restore the
 * saved choice on load and toggle it via the navbar button.
 */
(function () {
    'use strict';

    const STORAGE_KEY = 'botguard-theme';
    const root = document.documentElement;

    function apply(theme) {
        root.setAttribute('data-bs-theme', theme);
        const icon = document.querySelector('#themeToggle i');
        if (icon) {
            icon.className = theme === 'dark' ? 'bi bi-moon-stars' : 'bi bi-sun';
        }
    }

    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved) {
        apply(saved);
    } else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) {
        apply('light');
    }

    document.addEventListener('click', function (e) {
        const btn = e.target.closest('#themeToggle');
        if (!btn) return;
        const next = root.getAttribute('data-bs-theme') === 'dark' ? 'light' : 'dark';
        localStorage.setItem(STORAGE_KEY, next);
        apply(next);
    });
})();
