class CookieConsent {
    constructor() {
        this.cookieName = 'ole_cookie_consent';
        this.container = null;
        this.miniBannerWrapper = null;
        this.fullBanner = null;
        this.cookieSettingsButton = null;
        this.legalData = null; // Almacenará los datos legales dinámicos de la API
    }

    init() {
        // Primero, cargar los datos legales desde la API
        this.loadLegalData()
            .then(() => {
                // Comprobar si ya existe el consentimiento
                const consent = this.getConsent();
                
                // Crear elementos DOM con los datos legales
                this.createDOMElements();
                
                // Añadir listeners de eventos
                this.addEventListeners();
                
                // Mostrar banner o botón según corresponda
                if (consent) {
                    this.showCookieSettingsButton();
                    this.applyConsent(consent);
                } else {
                    this.showMiniBanner();
                }
            })
            .catch(error => {
                console.error('Error al cargar datos legales:', error);
                // En caso de error, usar los textos por defecto
                this.legalData = this.getDefaultLegalData();
                
                // Continuar con la inicialización
                const consent = this.getConsent();
                this.createDOMElements();
                this.addEventListeners();
                
                if (consent) {
                    this.showCookieSettingsButton();
                    this.applyConsent(consent);
                } else {
                    this.showMiniBanner();
                }
            });
    }
    
    loadLegalData() {
        return fetch('/api/legal/cookie-consent')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Error al cargar datos legales');
                }
                return response.json();
            })
            .then(data => {
                this.legalData = data;
                return data;
            });
    }
    
    getDefaultLegalData() {
        return {
            banner: {
                title: "Gestionar el consentimiento de las cookies",
                description: "Utilizamos cookies para mejorar la experiencia del usuario.",
                acceptButton: "Aceptar todas",
                rejectButton: "Rechazar no esenciales",
                preferencesButton: "Preferencias"
            },
            preferences: {
                title: "Preferencias de cookies",
                description: "Puede elegir qué cookies permitir y cuáles bloquear.",
                saveButton: "Guardar preferencias",
                categories: {
                    functional: {
                        title: "Funcionales (obligatorias)",
                        description: "Necesarias para el funcionamiento básico del sitio."
                    },
                    analytics: {
                        title: "Estadísticas",
                        description: "Nos ayudan a entender cómo interactúas con el sitio."
                    },
                    marketing: {
                        title: "Marketing",
                        description: "Usadas para publicidad personalizada."
                    }
                }
            },
            documents: {
                cookies: {
                    title: "Política de Cookies",
                    url: "/cookies",
                    version: "1.0"
                },
                privacy: {
                    title: "Política de Privacidad",
                    url: "/politica-de-privacidad",
                    version: "1.0"
                },
                terms: {
                    title: "Aviso Legal",
                    url: "/aviso-legal",
                    version: "1.0"
                }
            }
        };
    }

    createDOMElements() {
        // Crear el contenedor principal si no existe
        this.container = document.querySelector('.cookie-consent-container');
        if (!this.container) {
            this.container = document.createElement('div');
            this.container.className = 'cookie-consent-container';
            document.body.appendChild(this.container);
        } else {
            this.container.innerHTML = ''; // Limpiar contenido existente
        }

        this.createMiniBanner();
        this.createFullBanner();
        this.createCookieSettingsButton();
    }
    
    createMiniBanner() {
        const miniBannerWrapper = document.createElement('div');
        miniBannerWrapper.className = 'cookie-mini-banner-wrapper';
        miniBannerWrapper.style.display = 'none';
        
        const miniBannerHtml = `
            <div class="cookie-mini-banner">
                <div class="cookie-mini-banner-title">
                    ${this.legalData.banner.title}
                </div>
                <div class="cookie-mini-banner-text">
                    ${this.legalData.banner.description} Tienes más información en nuestra <a href="${this.legalData.documents.cookies.url}">Política de Cookies</a>.
                </div>
                <div class="cookie-mini-banner-actions">
                    <button type="button" class="cookie-button-accept">
                        ${this.legalData.banner.acceptButton}
                    </button>
                    <button type="button" class="cookie-button-reject">
                        ${this.legalData.banner.rejectButton}
                    </button>
                    <button type="button" class="cookie-button-preferences">
                        ${this.legalData.banner.preferencesButton}
                    </button>
                </div>
            </div>
        `;
        
        miniBannerWrapper.innerHTML = miniBannerHtml;
        this.container.appendChild(miniBannerWrapper);
        this.miniBannerWrapper = miniBannerWrapper;
    }
    
    createFullBanner() {
        const fullBanner = document.createElement('div');
        fullBanner.className = 'cookie-consent-banner';
        fullBanner.style.display = 'none';
        
        const fullBannerHtml = `
            <div class="cookie-consent-content">
                <div class="cookie-consent-header">
                    <h3>${this.legalData.preferences.title}</h3>
                    <button type="button" class="cookie-consent-close">&times;</button>
                </div>
                <div class="cookie-consent-body">
                    <p>${this.legalData.preferences.description}</p>
                    <div class="cookie-options">
                        <!-- Categoría: Funcional (siempre activo) -->
                        <div class="cookie-option">
                            <div class="cookie-option-header">
                                <div class="cookie-option-title">
                                    ${this.legalData.preferences.categories.functional.title}
                                </div>
                                <span class="cookie-option-status">Siempre activo</span>
                            </div>
                            <p>${this.legalData.preferences.categories.functional.description}</p>
                        </div>
                        
                        <!-- Categoría: Estadísticas -->
                        <div class="cookie-option">
                            <div class="cookie-option-header">
                                <div class="cookie-option-title">
                                    ${this.legalData.preferences.categories.analytics.title}
                                    <span class="cookie-toggle-info" data-target="analytics-details">
                                        <i class="fa fa-info-circle"></i>
                                    </span>
                                </div>
                                <label class="cookie-switch">
                                    <input type="checkbox" id="cookie-analytics-checkbox">
                                    <span class="cookie-slider"></span>
                                </label>
                            </div>
                            <div id="analytics-details" class="cookie-option-details" style="display: none;">
                                The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
                            </div>
                        </div>
                        
                        <!-- Categoría: Marketing -->
                        <div class="cookie-option">
                            <div class="cookie-option-header">
                                <div class="cookie-option-title">
                                    ${this.legalData.preferences.categories.marketing.title}
                                    <span class="cookie-toggle-info" data-target="marketing-details">
                                        <i class="fa fa-info-circle"></i>
                                    </span>
                                </div>
                                <label class="cookie-switch">
                                    <input type="checkbox" id="cookie-marketing-checkbox">
                                    <span class="cookie-slider"></span>
                                </label>
                            </div>
                            <div id="marketing-details" class="cookie-option-details" style="display: none;">
                                El almacenamiento o acceso técnico es necesario para crear perfiles de usuario para enviar publicidad, o para rastrear al usuario en un sitio web o en varios sitios web con fines de marketing similares.
                            </div>
                        </div>
                    </div>
                </div>
                <div class="cookie-consent-footer">
                    <button type="button" class="cookie-button-save">
                        ${this.legalData.preferences.saveButton}
                    </button>
                </div>
            </div>
        `;
        
        fullBanner.innerHTML = fullBannerHtml;
        this.container.appendChild(fullBanner);
        this.fullBanner = fullBanner;
    }
    
    createCookieSettingsButton() {
        const button = document.createElement('div');
        button.className = 'cookie-settings-button';
        button.innerHTML = '<i class="fas fa-cookie"></i>';
        button.style.display = 'none';
        button.setAttribute('title', 'Configurar cookies');
        
        this.container.appendChild(button);
        this.cookieSettingsButton = button;
    }
    
    addEventListeners() {
        this.container.addEventListener('click', (e) => {
            const target = e.target;

            if (target.matches('.cookie-mini-banner .cookie-button-accept') || target.matches('.cookie-consent-banner .cookie-button-accept')) {
                this.handleAcceptAll();
            } else if (target.matches('.cookie-mini-banner .cookie-button-reject') || target.matches('.cookie-consent-banner .cookie-button-reject')) {
                this.handleRejectAll();
            } else if (target.matches('.cookie-mini-banner .cookie-button-preferences')) {
                this.showFullBanner();
            } else if (target.matches('.cookie-consent-banner .cookie-button-save')) {
                this.handleSavePreferences();
            } else if (target.matches('.cookie-consent-close') || target.matches('.cookie-mini-banner-close')) {
                this.showCookieSettingsButton();
            } else if (target.matches('.cookie-settings-button')) {
                this.showMiniBanner();
            } else if (target.matches('.cookie-toggle-info') || target.closest('.cookie-toggle-info')) {
                // Manejar la expansión/colapso de la información de cookies
                const infoIcon = target.matches('.cookie-toggle-info') ? target : target.closest('.cookie-toggle-info');
                const targetId = infoIcon.getAttribute('data-target');
                const detailsElement = document.getElementById(targetId);
                
                if (detailsElement) {
                    // Alternar la visualización
                    if (detailsElement.style.display === 'none') {
                        detailsElement.style.display = 'block';
                        infoIcon.classList.add('active');
                    } else {
                        detailsElement.style.display = 'none';
                        infoIcon.classList.remove('active');
                    }
                }
            }
        });
    }

    handleAcceptAll() {
        const consent = { 
            functional: true, 
            analytics: true, 
            marketing: true,
            // Guardar información sobre las versiones aceptadas
            versions: {
                cookies: this.legalData.documents.cookies.version,
                privacy: this.legalData.documents.privacy.version,
                terms: this.legalData.documents.terms.version
            },
            acceptedAt: new Date().toISOString()
        };
        this.saveConsent(consent);
        this.showCookieSettingsButton();
        
        // Emitir evento personalizado
        this.emitCookieConsentChanged(consent);
    }

    handleRejectAll() {
        const consent = { 
            functional: true, 
            analytics: false, 
            marketing: false,
            // Guardar información sobre las versiones rechazadas
            versions: {
                cookies: this.legalData.documents.cookies.version,
                privacy: this.legalData.documents.privacy.version,
                terms: this.legalData.documents.terms.version
            },
            rejectedAt: new Date().toISOString()
        };
        this.saveConsent(consent);
        this.showCookieSettingsButton();
        
        // Emitir evento personalizado
        this.emitCookieConsentChanged(consent);
    }

    handleSavePreferences() {
        const analytics = this.fullBanner.querySelector('#cookie-analytics-checkbox').checked;
        const marketing = this.fullBanner.querySelector('#cookie-marketing-checkbox').checked;
        const consent = { 
            functional: true, 
            analytics, 
            marketing,
            // Guardar información sobre las versiones
            versions: {
                cookies: this.legalData.documents.cookies.version,
                privacy: this.legalData.documents.privacy.version,
                terms: this.legalData.documents.terms.version
            },
            savedAt: new Date().toISOString()
        };
        this.saveConsent(consent);
        this.showCookieSettingsButton();  // AQUÍ ESTÁ LA CORRECCIÓN
        
        // Emitir evento personalizado
        this.emitCookieConsentChanged(consent);
    }

    showMiniBanner() {
        this.miniBannerWrapper.style.display = 'block';
        this.fullBanner.style.display = 'none';
        this.cookieSettingsButton.style.display = 'none';
    }

    showFullBanner() {
        const consent = this.getConsent() || { analytics: false, marketing: false };
        this.fullBanner.querySelector('#cookie-analytics-checkbox').checked = consent.analytics;
        this.fullBanner.querySelector('#cookie-marketing-checkbox').checked = consent.marketing;

        this.miniBannerWrapper.style.display = 'none';
        this.fullBanner.style.display = 'block';
        this.cookieSettingsButton.style.display = 'none';
    }

    showCookieSettingsButton() {
        this.miniBannerWrapper.style.display = 'none';
        this.fullBanner.style.display = 'none';
        this.cookieSettingsButton.style.display = 'flex';
    }

    saveConsent(consent) {
        this.setCookie(this.cookieName, JSON.stringify(consent), 365);
        this.applyConsent(consent);
    }

    getConsent() {
        const cookie = this.getCookie(this.cookieName);
        try {
            return cookie ? JSON.parse(cookie) : null;
        } catch (e) {
            console.error('Error parsing cookie consent:', e);
            return null;
        }
    }

    applyConsent(consent) {
        if (!consent) return;
        // Implementar lógica para aplicar el consentimiento
    }
    
    // Método para emitir evento personalizado
    emitCookieConsentChanged(consent) {
        const event = new CustomEvent('cookieConsentChanged', { 
            detail: consent,
            bubbles: true 
        });
        document.dispatchEvent(event);
    }

    // Métodos auxiliares para manipular cookies
    setCookie(name, value, days) {
        let expires = '';
        if (days) {
            const date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = '; expires=' + date.toUTCString();
        }
        document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/; SameSite=Lax';
    }

    getCookie(name) {
        const nameEQ = name + '=';
        const ca = document.cookie.split(';');
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
        }
        return null;
    }

    deleteCookie(name) {
        document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    }
}

// Inicializar el sistema de consentimiento de cookies
document.addEventListener('DOMContentLoaded', function() {
    const cookieConsent = new CookieConsent();
    cookieConsent.init();
    
    // Exponer globalmente para depuración
    window.cookieConsent = cookieConsent;
});
