/**
 * RSL Theme Toggle System
 *
 * Manages light/dark theme switching with localStorage persistence and system
 * preference detection. Automatically creates a floating toggle button and handles
 * theme transitions smoothly with CSS custom properties.
 *
 * @fileoverview Theme management system with localStorage and system preference sync
 * @version 1.0.0
 * @license MIT
 *
 * Key Features:
 * - Auto-detects system color scheme preference
 * - Persists user choice to localStorage
 * - Dynamically creates toggle button with FontAwesome icons
 * - Syncs with system theme changes when no user preference is set
 * - Applies theme via data-theme attribute for CSS targeting
 * - Graceful handling of existing buttons (prevents duplicates)
 *
 * Usage:
 * // Automatic initialization (no code required):
 * // Simply include this script, button appears automatically
 *
 * // Theme is applied via data attribute on <html>:
 * // <html data-theme="dark">
 *
 * // CSS can target themes:
 * [data-theme="dark"] {
 *   --background-color: #1a1a1a;
 *   --text-color: #ffffff;
 * }
 *
 * Public API:
 * - Theme persists in localStorage as 'rsl-theme'
 * - Toggle button has class 'rsl-theme-toggle'
 * - Theme attribute: document.documentElement.getAttribute('data-theme')
 */

(function() {
    'use strict';

    /**
     * Initialize theme from localStorage or system preference
     *
     * Checks localStorage first for saved user preference, then falls back
     * to system color scheme preference. Applies theme immediately to prevent
     * flash of unstyled content.
     *
     * @returns {void}
     *
     * @example
     * // Called automatically on page load
     * // Theme applied to <html data-theme="dark"> or "light"
     */
    function initTheme() {
        const storedTheme = localStorage.getItem('rsl-theme');

        if (storedTheme) {
            // User has previously set a preference
            document.documentElement.setAttribute('data-theme', storedTheme);
        } else {
            // Check system preference
            const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            const theme = prefersDark ? 'dark' : 'light';
            document.documentElement.setAttribute('data-theme', theme);
            localStorage.setItem('rsl-theme', theme);
        }
    }

    /**
     * Toggle between light and dark themes
     *
     * Switches current theme and persists the new preference to localStorage.
     * Updates data-theme attribute which CSS can target for styling.
     *
     * @returns {void}
     *
     * @example
     * // Automatically bound to toggle button click
     * // Changes: data-theme="dark" <-> data-theme="light"
     */
    function toggleTheme() {
        const currentTheme = document.documentElement.getAttribute('data-theme');
        const newTheme = currentTheme === 'dark' ? 'light' : 'dark';

        document.documentElement.setAttribute('data-theme', newTheme);
        localStorage.setItem('rsl-theme', newTheme);
    }

    /**
     * Create and insert theme toggle button into the DOM
     *
     * Creates a floating button with sun/moon icons from FontAwesome.
     * Button is positioned via CSS using the .rsl-theme-toggle class.
     * Prevents duplicate buttons if one already exists.
     *
     * @returns {void}
     *
     * @example
     * // Called automatically on initialization
     * // Creates: <button class="rsl-theme-toggle" aria-label="Toggle dark mode">
     * //            <i class="fas fa-sun icon-sun"></i>
     * //            <i class="fas fa-moon icon-moon"></i>
     * //          </button>
     */
    function createToggleButton() {
        // Check if button already exists (prevent duplicates)
        const existingButton = document.querySelector('.rsl-theme-toggle');
        if (existingButton) {
            // Attach click handler to existing button
            existingButton.addEventListener('click', toggleTheme);
            return;
        }

        const button = document.createElement('button');
        button.className = 'rsl-theme-toggle';
        button.setAttribute('aria-label', 'Toggle dark mode');
        button.setAttribute('title', 'Toggle dark mode');

        // Icon uses FontAwesome, CSS controls visibility based on theme
        button.innerHTML = `
            <i class="fas fa-sun icon-sun"></i>
            <i class="fas fa-moon icon-moon"></i>
        `;

        button.addEventListener('click', toggleTheme);

        document.body.appendChild(button);
    }

    /**
     * Initialize theme system on DOM ready
     *
     * Handles both scenarios: script loaded before or after DOM ready.
     * Ensures theme is applied as early as possible to prevent visual flicker.
     */
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            initTheme();
            createToggleButton();
        });
    } else {
        initTheme();
        createToggleButton();
    }

    /**
     * Listen for system theme preference changes
     *
     * Responds to OS-level theme changes (e.g., sunset triggers dark mode).
     * Only applies automatic update if user hasn't explicitly set a preference.
     * This respects user choice while still syncing with system when appropriate.
     */
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function(e) {
        // Only update if user hasn't set a manual preference
        if (!localStorage.getItem('rsl-theme')) {
            const theme = e.matches ? 'dark' : 'light';
            document.documentElement.setAttribute('data-theme', theme);
        }
    });

})();
