/**
 * Widget flotante de accesibilidad
 * Similar a WP Accessibility
 */

(function() {
    'use strict';

    // Configuración
    const config = {
        storageKey: 'accessibility_preferences',
        defaults: {
            grayscale: false,
            highContrast: false,
            negativeContrast: false,
            lightBackground: false,
            underlineLinks: false,
            readableFont: false,
            fontSize: 0  // 0 = normal, 1-5 = aumentado
        }
    };

    // Cargar preferencias guardadas
    function loadPreferences() {
        const saved = localStorage.getItem(config.storageKey);
        return saved ? JSON.parse(saved) : config.defaults;
    }

    // Guardar preferencias
    function savePreferences(prefs) {
        localStorage.setItem(config.storageKey, JSON.stringify(prefs));
    }

    // Estado actual
    let preferences = loadPreferences();

    // Crear el HTML del widget
    function createWidget() {
        // Leer configuración del admin
        const widgetConfig = window.accessibilityConfig || {
            showFontSize: true,
            showGrayscale: true,
            showHighContrast: true,
            showNegativeContrast: true,
            showLightBackground: true,
            showUnderlineLinks: true,
            showReadableFont: true
        };
        
        const widget = document.createElement('div');
        widget.id = 'accessibility-widget';
        widget.innerHTML = `
            <button id="accessibility-toggle" aria-label="Abrir herramientas de accesibilidad" aria-expanded="false">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M12 2C13.1 2 14 2.9 14 4C14 5.1 13.1 6 12 6C10.9 6 10 5.1 10 4C10 2.9 10.9 2 12 2M21 9H15V22H13V16H11V22H9V9H3V7H21V9Z"/>
                </svg>
            </button>
            <div id="accessibility-panel" class="accessibility-panel" role="dialog" aria-labelledby="accessibility-title" hidden>
                <div class="accessibility-panel-header">
                    <h2 id="accessibility-title">Herramientas de accesibilidad</h2>
                    <button id="accessibility-close" aria-label="Cerrar panel">×</button>
                </div>
                <div class="accessibility-panel-content">
                    ${widgetConfig.showFontSize ? `
                    <!-- Control de tamaño de fuente -->
                    <div class="font-size-controls">
                        <div class="font-size-label">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                                <path d="M9.6,14L12,7.7L14.4,14M11,5L5.5,19H7.7L8.8,16H15.2L16.3,19H18.5L13,5H11Z"/>
                            </svg>
                            <span>Tamaño de letra</span>
                        </div>
                        <div class="font-size-buttons">
                            <button id="decrease-font" class="font-size-btn" aria-label="Disminuir tamaño de letra" ${preferences.fontSize === 0 ? 'disabled' : ''}>A-</button>
                            <button id="increase-font" class="font-size-btn" aria-label="Aumentar tamaño de letra" ${preferences.fontSize >= 5 ? 'disabled' : ''}>A+</button>
                        </div>
                    </div>
                    ` : ''}
                    
                    ${widgetConfig.showGrayscale ? `
                    <button class="accessibility-option" data-option="grayscale" aria-pressed="${preferences.grayscale}">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,4A8,8 0 0,1 20,12A8,8 0 0,1 12,20V4Z"/>
                        </svg>
                        <span>Escala de grises</span>
                    </button>
                    ` : ''}
                    
                    ${widgetConfig.showHighContrast ? `
                    <button class="accessibility-option" data-option="highContrast" aria-pressed="${preferences.highContrast}">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,4A8,8 0 0,1 20,12A8,8 0 0,1 12,20A8,8 0 0,1 4,12A8,8 0 0,1 12,4Z"/>
                        </svg>
                        <span>Alto contraste</span>
                    </button>
                    ` : ''}
                    
                    ${widgetConfig.showNegativeContrast ? `
                    <button class="accessibility-option" data-option="negativeContrast" aria-pressed="${preferences.negativeContrast}">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22A10,10 0 0,1 2,12A10,10 0 0,1 12,2M12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20A8,8 0 0,0 20,12A8,8 0 0,0 12,4Z"/>
                        </svg>
                        <span>Contraste negativo</span>
                    </button>
                    ` : ''}
                    
                    ${widgetConfig.showLightBackground ? `
                    <button class="accessibility-option" data-option="lightBackground" aria-pressed="${preferences.lightBackground}">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M12,18C11.11,18 10.26,17.8 9.5,17.45C11.56,16.5 13,14.42 13,12C13,9.58 11.56,7.5 9.5,6.55C10.26,6.2 11.11,6 12,6A6,6 0 0,1 18,12A6,6 0 0,1 12,18M20,8.69V4H15.31L12,0.69L8.69,4H4V8.69L0.69,12L4,15.31V20H8.69L12,23.31L15.31,20H20V15.31L23.31,12L20,8.69Z"/>
                        </svg>
                        <span>Fondo claro</span>
                    </button>
                    ` : ''}
                    
                    ${widgetConfig.showUnderlineLinks ? `
                    <button class="accessibility-option" data-option="underlineLinks" aria-pressed="${preferences.underlineLinks}">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M5,17H19V19H5V17M12,15A5,5 0 0,1 7,10V4H9V10A3,3 0 0,0 12,13A3,3 0 0,0 15,10V4H17V10A5,5 0 0,1 12,15Z"/>
                        </svg>
                        <span>Subrayar enlaces</span>
                    </button>
                    ` : ''}
                    
                    ${widgetConfig.showReadableFont ? `
                    <button class="accessibility-option" data-option="readableFont" aria-pressed="${preferences.readableFont}">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M9.6,14L12,7.7L14.4,14M11,5L5.5,19H7.7L8.8,16H15.2L16.3,19H18.5L13,5H11Z"/>
                        </svg>
                        <span>Fuente legible</span>
                    </button>
                    ` : ''}
                    
                    <button id="accessibility-reset" class="accessibility-reset">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M12,4C14.1,4 16.1,4.8 17.6,6.3C20.7,9.4 20.7,14.5 17.6,17.6C15.8,19.5 13.3,20.2 10.9,19.9L11.4,17.9C13.1,18.1 14.9,17.5 16.2,16.2C18.5,13.9 18.5,10.1 16.2,7.7C15.1,6.6 13.5,6 12,6V10.6L7,5.6L12,0.6V4M6.3,17.6C3.7,15 3.3,11 5.1,7.9L6.6,9.4C5.5,11.6 5.9,14.4 7.8,16.2C8.3,16.7 8.9,17.1 9.6,17.4L9,19.4C8,19 7.1,18.4 6.3,17.6Z"/>
                        </svg>
                        <span>Reiniciar</span>
                    </button>
                </div>
            </div>
        `;
        
        document.body.appendChild(widget);
    }

    // Aplicar opción
    function applyOption(option, enabled) {
        const body = document.body;
        
        switch(option) {
            case 'grayscale':
                body.classList.toggle('a11y-grayscale', enabled);
                break;
            case 'highContrast':
                body.classList.toggle('a11y-high-contrast', enabled);
                break;
            case 'negativeContrast':
                body.classList.toggle('a11y-negative-contrast', enabled);
                break;
            case 'lightBackground':
                body.classList.toggle('a11y-light-background', enabled);
                break;
            case 'underlineLinks':
                body.classList.toggle('a11y-underline-links', enabled);
                break;
            case 'readableFont':
                body.classList.toggle('a11y-readable-font', enabled);
                break;
        }
    }
    
    // Aplicar tamaño de fuente
    function applyFontSize(size) {
        const body = document.body;
        // Remover todas las clases de tamaño
        for (let i = 1; i <= 5; i++) {
            body.classList.remove(`a11y-font-size-${i}`);
        }
        // Aplicar nuevo tamaño si es mayor que 0
        if (size > 0) {
            body.classList.add(`a11y-font-size-${size}`);
        }
        
        // Actualizar botones
        const decreaseBtn = document.getElementById('decrease-font');
        const increaseBtn = document.getElementById('increase-font');
        
        if (decreaseBtn && increaseBtn) {
            decreaseBtn.disabled = size === 0;
            increaseBtn.disabled = size >= 5;
        }
    }

    // Aplicar todas las preferencias guardadas
    function applyAllPreferences() {
        Object.keys(preferences).forEach(option => {
            if (option === 'fontSize') {
                applyFontSize(preferences.fontSize);
            } else {
                applyOption(option, preferences[option]);
            }
        });
    }

    // Inicializar eventos
    function initEvents() {
        const toggle = document.getElementById('accessibility-toggle');
        const panel = document.getElementById('accessibility-panel');
        const close = document.getElementById('accessibility-close');
        const reset = document.getElementById('accessibility-reset');
        const options = document.querySelectorAll('.accessibility-option');

        // Abrir/cerrar panel
        toggle.addEventListener('click', function() {
            const isHidden = panel.hasAttribute('hidden');
            
            if (isHidden) {
                panel.removeAttribute('hidden');
                toggle.setAttribute('aria-expanded', 'true');
                panel.querySelector('button').focus();
            } else {
                panel.setAttribute('hidden', '');
                toggle.setAttribute('aria-expanded', 'false');
            }
        });

        // Cerrar panel
        close.addEventListener('click', function() {
            panel.setAttribute('hidden', '');
            toggle.setAttribute('aria-expanded', 'false');
            toggle.focus();
        });

        // Cerrar con ESC
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && !panel.hasAttribute('hidden')) {
                panel.setAttribute('hidden', '');
                toggle.setAttribute('aria-expanded', 'false');
                toggle.focus();
            }
        });

        // Opciones
        options.forEach(option => {
            option.addEventListener('click', function() {
                const optionName = this.getAttribute('data-option');
                const currentState = preferences[optionName];
                const newState = !currentState;
                
                // Actualizar estado
                preferences[optionName] = newState;
                
                // Aplicar
                applyOption(optionName, newState);
                
                // Actualizar UI
                this.setAttribute('aria-pressed', newState);
                
                // Guardar
                savePreferences(preferences);
            });
        });

        // Reset
        reset.addEventListener('click', function() {
            // Resetear preferencias
            preferences = {...config.defaults};
            
            // Remover todas las clases
            Object.keys(preferences).forEach(option => {
                if (option === 'fontSize') {
                    applyFontSize(0);
                } else {
                    applyOption(option, false);
                }
            });
            
            // Actualizar UI
            options.forEach(option => {
                option.setAttribute('aria-pressed', 'false');
            });
            
            // Guardar
            savePreferences(preferences);
            
            // Notificar
            const notification = document.createElement('div');
            notification.className = 'a11y-notification';
            notification.textContent = 'Preferencias de accesibilidad restablecidas';
            notification.setAttribute('role', 'status');
            notification.setAttribute('aria-live', 'polite');
            document.body.appendChild(notification);
            
            setTimeout(() => notification.remove(), 3000);
        });
        
        // Aumentar tamaño de fuente
        const increaseBtn = document.getElementById('increase-font');
        if (increaseBtn) {
            increaseBtn.addEventListener('click', function() {
                if (preferences.fontSize < 5) {
                    preferences.fontSize++;
                    applyFontSize(preferences.fontSize);
                    savePreferences(preferences);
                }
            });
        }
        
        // Disminuir tamaño de fuente
        const decreaseBtn = document.getElementById('decrease-font');
        if (decreaseBtn) {
            decreaseBtn.addEventListener('click', function() {
                if (preferences.fontSize > 0) {
                    preferences.fontSize--;
                    applyFontSize(preferences.fontSize);
                    savePreferences(preferences);
                }
            });
        }
    }

    // Inicializar
    function init() {
        createWidget();
        applyAllPreferences();
        initEvents();
    }

    // Ejecutar cuando el DOM esté listo
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();