(function () {
    'use strict';

    const STORAGE_KEY = 'ppphp-color-theme';
    const CHOICES = ['system', 'light', 'midnight', 'dracula', 'gruvbox', 'rosepine'];
    const CHOICE_META = {
        system: { label: 'System', icon: 'bi-display' },
        light: { label: 'Light', icon: 'bi-sun-fill' },
        midnight: { label: 'Midnight', icon: 'bi-moon-stars-fill' },
        dracula: { label: 'Dracula', icon: 'bi-magic' },
        gruvbox: { label: 'Gruvbox', icon: 'bi-fire' },
        rosepine: { label: 'Rosé Pine', icon: 'bi-flower1' },
    };
    const root = document.documentElement;
    const systemPreference = window.matchMedia('(prefers-color-scheme: dark)');

    function normalizeChoice(choice) {
        if (choice === 'dark') return 'midnight';
        if (choice === 'graphite') return 'dracula';
        if (choice === 'aurora') return 'gruvbox';
        return CHOICES.includes(choice) ? choice : 'system';
    }

    function currentChoice() {
        return normalizeChoice(root.getAttribute('data-pp-theme-choice'));
    }

    function effectiveTheme(choice = currentChoice()) {
        if (choice === 'system') return systemPreference.matches ? 'dark' : 'light';
        return choice === 'light' ? 'light' : 'dark';
    }

    function currentTheme() {
        return effectiveTheme();
    }

    function saveChoice(choice) {
        try { window.localStorage.setItem(STORAGE_KEY, choice); } catch (error) {}
    }

    function closePicker(picker) {
        const toggle = picker?.querySelector('[data-pp-theme-toggle]');
        const menu = picker?.querySelector('[data-pp-theme-menu]');
        if (!toggle || !menu) return;
        toggle.setAttribute('aria-expanded', 'false');
        menu.hidden = true;
    }

    function syncControls(choice, theme) {
        const meta = CHOICE_META[choice];
        document.querySelectorAll('[data-pp-theme-picker]').forEach((picker) => {
            const button = picker.querySelector('[data-pp-theme-toggle]');
            const icon = button?.querySelector('.pp-theme-toggle-icon i');
            const detail = choice === 'system' ? ` (${theme === 'dark' ? 'Dark' : 'Light'})` : '';
            button?.setAttribute('aria-label', `Application theme: ${meta.label}${detail}. Choose theme`);
            button?.setAttribute('title', `Application theme: ${meta.label}${detail}`);
            button?.setAttribute('aria-pressed', theme === 'dark' ? 'true' : 'false');
            button?.querySelector('.pp-theme-toggle-label')?.replaceChildren(document.createTextNode(meta.label));
            if (icon) icon.className = `bi ${meta.icon}`;
            picker.querySelectorAll('[data-pp-theme-option]').forEach((option) => {
                option.setAttribute('aria-checked', option.dataset.ppThemeOption === choice ? 'true' : 'false');
            });
        });
        document.querySelector('meta[name="theme-color"]')?.setAttribute('content', theme === 'dark' ? '#0b1120' : '#1f2328');
    }

    function announceChoice(choice, theme) {
        const live = document.getElementById('ppThemeAnnouncement') || (() => {
            const node = document.createElement('span');
            node.id = 'ppThemeAnnouncement';
            node.className = 'visually-hidden';
            node.setAttribute('role', 'status');
            node.setAttribute('aria-live', 'polite');
            document.body.appendChild(node);
            return node;
        })();
        const suffix = choice === 'system' ? `, currently ${theme}` : '';
        live.textContent = `${CHOICE_META[choice].label} theme enabled${suffix}`;
    }

    function applyChoice(choice, persist, announce) {
        const safeChoice = normalizeChoice(choice);
        const theme = effectiveTheme(safeChoice);
        root.setAttribute('data-pp-theme-choice', safeChoice);
        root.setAttribute('data-pp-theme', theme);
        root.setAttribute('data-bs-theme', theme);
        root.style.colorScheme = theme;
        if (persist) saveChoice(safeChoice);
        syncControls(safeChoice, theme);
        window.dispatchEvent(new CustomEvent('ppphp:themechange', { detail: { theme, choice: safeChoice } }));
        if (announce) announceChoice(safeChoice, theme);
    }

    function initialize() {
        applyChoice(currentChoice(), false, false);

        document.addEventListener('click', (event) => {
            const option = event.target.closest('[data-pp-theme-option]');
            if (option) {
                applyChoice(option.dataset.ppThemeOption, true, true);
                closePicker(option.closest('[data-pp-theme-picker]'));
                return;
            }

            const toggle = event.target.closest('[data-pp-theme-toggle]');
            if (toggle) {
                const picker = toggle.closest('[data-pp-theme-picker]');
                const menu = picker?.querySelector('[data-pp-theme-menu]');
                if (!menu) return;
                const opening = menu.hidden;
                document.querySelectorAll('[data-pp-theme-picker]').forEach(closePicker);
                menu.hidden = !opening;
                toggle.setAttribute('aria-expanded', opening ? 'true' : 'false');
                if (opening) menu.querySelector('[aria-checked="true"]')?.focus();
                return;
            }

            document.querySelectorAll('[data-pp-theme-picker]').forEach(closePicker);
        });

        document.addEventListener('keydown', (event) => {
            if (event.key !== 'Escape') return;
            document.querySelectorAll('[data-pp-theme-picker]').forEach((picker) => {
                const wasOpen = picker.querySelector('[data-pp-theme-toggle]')?.getAttribute('aria-expanded') === 'true';
                closePicker(picker);
                if (wasOpen) picker.querySelector('[data-pp-theme-toggle]')?.focus();
            });
        });

        const followSystem = () => {
            if (currentChoice() === 'system') applyChoice('system', false, false);
        };
        if (systemPreference.addEventListener) systemPreference.addEventListener('change', followSystem);
        else systemPreference.addListener(followSystem);
    }

    window.PpPhpTheme = {
        get: currentTheme,
        getChoice: currentChoice,
        choices: CHOICES.slice(),
        set(choice) { applyChoice(choice, true, false); },
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initialize, { once: true });
    } else {
        initialize();
    }
}());
