/**
 * Script de Debug para Responsive Design
 * Muestra información en tiempo real de la resolución y breakpoints activos
 */

class ResponsiveDebugger {
    constructor() {
        this.init();
        this.createIndicator();
        this.bindEvents();
    }

    init() {
        // Crear el indicador solo si estamos en modo debug
        const isDebug = window.location.search.includes('debug=responsive') || 
                       localStorage.getItem('responsive-debug') === 'true';
        
        if (!isDebug) return;
        
        this.createIndicator();
    }

    createIndicator() {
        // Crear indicador de resolución
        const indicator = document.createElement('div');
        indicator.id = 'resolution-indicator';
        indicator.style.cssText = `
            position: fixed;
            top: 10px;
            right: 10px;
            background: rgba(0, 0, 0, 0.9);
            color: white;
            padding: 12px 16px;
            border-radius: 8px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            z-index: 9999;
            pointer-events: none;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
            border: 2px solid #fff;
            min-width: 200px;
        `;
        
        document.body.appendChild(indicator);
        this.indicator = indicator;
        
        // Crear botón para activar/desactivar
        this.createToggleButton();
        
        this.updateIndicator();
    }

    createToggleButton() {
        const button = document.createElement('button');
        button.innerHTML = '📱';
        button.title = 'Toggle Responsive Debug';
        button.style.cssText = `
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            border: none;
            background: #007bff;
            color: white;
            font-size: 20px;
            cursor: pointer;
            z-index: 9998;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        `;
        
        button.addEventListener('click', () => {
            const isActive = localStorage.getItem('responsive-debug') === 'true';
            localStorage.setItem('responsive-debug', !isActive);
            location.reload();
        });
        
        document.body.appendChild(button);
    }

    bindEvents() {
        if (!this.indicator) return;
        
        // Actualizar al redimensionar
        window.addEventListener('resize', () => {
            this.updateIndicator();
        });
        
        // Actualizar al rotar dispositivo
        window.addEventListener('orientationchange', () => {
            setTimeout(() => this.updateIndicator(), 100);
        });
    }

    updateIndicator() {
        if (!this.indicator) return;
        
        const width = window.innerWidth;
        const height = window.innerHeight;
        const dpr = window.devicePixelRatio || 1;
        
        let breakpoint = this.getBreakpoint(width);
        let color = this.getBreakpointColor(breakpoint);
        
        this.indicator.style.background = color;
        this.indicator.innerHTML = `
            <div style="font-weight: bold; margin-bottom: 4px;">${breakpoint}</div>
            <div>Resolución: ${width} × ${height}</div>
            <div>DPR: ${dpr.toFixed(1)}</div>
            <div style="margin-top: 8px; font-size: 11px; opacity: 0.8;">
                ${this.getOptimizationStatus(width)}
            </div>
        `;
    }

    getBreakpoint(width) {
        if (width < 576) return 'XS (Extra Small)';
        if (width < 768) return 'SM (Small)';
        if (width < 992) return 'MD (Medium)';
        if (width < 1200) return 'LG (Large)';
        if (width < 1400) return 'XL (Extra Large)';
        if (width >= 1920) return 'Desktop HD';
        return 'XXL (2X Large)';
    }

    getBreakpointColor(breakpoint) {
        const colors = {
            'XS (Extra Small)': 'rgba(220, 53, 69, 0.9)',   // Red
            'SM (Small)': 'rgba(253, 126, 20, 0.9)',        // Orange
            'MD (Medium)': 'rgba(255, 193, 7, 0.9)',        // Yellow
            'LG (Large)': 'rgba(25, 135, 84, 0.9)',         // Green
            'XL (Extra Large)': 'rgba(13, 110, 253, 0.9)',  // Blue
            'XXL (2X Large)': 'rgba(102, 16, 242, 0.9)',    // Purple
            'Desktop HD': 'rgba(111, 66, 193, 0.9)'         // Indigo
        };
        return colors[breakpoint] || 'rgba(0, 0, 0, 0.9)';
    }

    getOptimizationStatus(width) {
        if (width === 1366) {
            return '✅ Optimización 1366x768 ACTIVA';
        } else if (width >= 1200 && width <= 1400) {
            return '✅ Optimización Laptop ACTIVA';
        } else if (width >= 768 && width < 1200) {
            return '✅ Optimización Tablet ACTIVA';
        } else if (width < 768) {
            return '✅ Optimización Móvil ACTIVA';
        } else if (width >= 1920) {
            return '✅ Optimización Desktop HD ACTIVA';
        }
        return '⚠️ Sin optimización específica';
    }

    // Método público para activar/desactivar
    static toggle() {
        const isActive = localStorage.getItem('responsive-debug') === 'true';
        localStorage.setItem('responsive-debug', (!isActive).toString());
        location.reload();
    }

    // Método para mostrar información de CSS activo
    static showActiveCSS() {
        const styles = [];
        const sheets = document.styleSheets;
        
        for (let sheet of sheets) {
            try {
                const rules = sheet.cssRules || sheet.rules;
                for (let rule of rules) {
                    if (rule.type === CSSRule.MEDIA_RULE) {
                        if (window.matchMedia(rule.conditionText).matches) {
                            styles.push(rule.conditionText);
                        }
                    }
                }
            } catch (e) {
                // Ignorar errores CORS
            }
        }
        
        console.log('📱 Media queries activos:', styles);
        return styles;
    }
}

// Auto-inicializar si está en modo debug
document.addEventListener('DOMContentLoaded', () => {
    new ResponsiveDebugger();
});

// Exponer funciones globales para debug manual
window.ResponsiveDebugger = ResponsiveDebugger;

// Debug rápido en consola
console.log(`
🎯 GGEE Responsive Debug Cargado
================================
• Para activar indicador: localStorage.setItem('responsive-debug', 'true') y recargar
• Para ver CSS activo: ResponsiveDebugger.showActiveCSS()
• URL debug: agregue ?debug=responsive
• Resolución actual: ${window.innerWidth}×${window.innerHeight}
`);

// Detectar 1366x768 específicamente y mostrar mensaje
if (window.innerWidth === 1366 && window.innerHeight === 768) {
    console.log('🎯 RESOLUCIÓN 1366x768 DETECTADA - Optimizaciones activas!');
}
