/**
 * 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.1.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)
 * - Supports custom localStorage key via window.RSL_THEME_KEY for template isolation
 *
 * 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;
 * }
 *
 * // For templates, set custom key BEFORE this script loads:
 * // window.RSL_THEME_KEY = 'my-template-theme';
 *
 * Public API:
 * - Theme persists in localStorage (key: window.RSL_THEME_KEY or 'rsl-theme')
 * - Toggle button has class 'rsl-theme-toggle'
 * - Theme attribute: document.documentElement.getAttribute('data-theme')
 */

(function() {
    'use strict';

    // Use custom key if set by template, otherwise default to 'rsl-theme'
    var THEME_KEY = window.RSL_THEME_KEY || 'rsl-theme';

    /**
     * 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.
     *
     * If theme was already set by inline script (for templates), this respects
     * that setting and doesn't override it.
     *
     * @returns {void}
     *
     * @example
     * // Called automatically on page load
     * // Theme applied to <html data-theme="dark"> or "light"
     */
    function initTheme() {
        // Check if theme was already set by inline script
        var currentTheme = document.documentElement.getAttribute('data-theme');
        if (currentTheme) {
            // Theme already set, just ensure localStorage matches
            if (!localStorage.getItem(THEME_KEY)) {
                localStorage.setItem(THEME_KEY, currentTheme);
            }
            return;
        }

        var storedTheme = localStorage.getItem(THEME_KEY);

        if (storedTheme) {
            // User has previously set a preference
            document.documentElement.setAttribute('data-theme', storedTheme);
        } else {
            // Check system preference
            var prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            var theme = prefersDark ? 'dark' : 'light';
            document.documentElement.setAttribute('data-theme', theme);
            localStorage.setItem(THEME_KEY, 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() {
        var currentTheme = document.documentElement.getAttribute('data-theme');
        var newTheme = currentTheme === 'dark' ? 'light' : 'dark';

        document.documentElement.setAttribute('data-theme', newTheme);
        localStorage.setItem(THEME_KEY, 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)
        var existingButton = document.querySelector('.rsl-theme-toggle');
        if (existingButton) {
            // Attach click handler to existing button
            existingButton.addEventListener('click', toggleTheme);
            return;
        }

        var 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(THEME_KEY)) {
            var theme = e.matches ? 'dark' : 'light';
            document.documentElement.setAttribute('data-theme', theme);
        }
    });

})();
