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.showCookieSettingsButton();
                }
            })
            .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.showCookieSettingsButton();
                }
            });
    }

    async loadLegalData() {
        try {
            const response = await fetch('/api/legal/cookie-consent');
            if (!response.ok) {
                throw new Error(`Error en la API: ${response.status}`);
            }
            const data = await response.json();
            if (data.success) {
                this.legalData = data.data;
            } else {
                throw new Error('Respuesta de API incorrecta');
            }
        } catch (error) {
            console.error('Error al cargar datos legales:', error);
            this.legalData = this.getDefaultLegalData();
            throw error;
        }
    }

    getDefaultLegalData() {
        // Devuelve los textos por defecto en caso de error
        return {
            banner_title: "Gestionar el consentimiento de las cookies",
            banner_text: "Utilizamos cookies propias y de terceros para obtener datos estadísticos de la navegación de nuestros usuarios, ofrecer marketing personalizado y mejorar nuestros servicios.",
            documents: {
                cookies: {
                    title: "Política de Cookies",
                    url: "/cookies",
                    version: "1.0"
                },
                privacy: {
                    title: "Política de Privacidad",
                    url: "/privacidad",
                    version: "1.0"
                },
                terms: {
                    title: "Aviso Legal",
                    url: "/aviso-legal",
                    version: "1.0"
                }
            }
        };
    }

    createDOMElements() {
        this.container = document.createElement('div');
        this.container.className = 'cookie-consent-container';
        document.body.appendChild(this.container);

        this.miniBannerWrapper = document.createElement('div');
        this.miniBannerWrapper.className = 'cookie-mini-banner-wrapper';
        this.miniBannerWrapper.style.display = 'none';
        this.miniBannerWrapper.innerHTML = `
            <div class="cookie-mini-banner">
                <div class="cookie-mini-banner-header">
                    <div class="cookie-mini-banner-title">${this.legalData.banner_title}</div>
                    <button type="button" class="cookie-mini-banner-close">&times;</button>
                </div>
                <div class="cookie-mini-banner-text">
                    ${this.legalData.banner_text}
                </div>
                <div class="cookie-mini-banner-actions">
                    <button type="button" class="cookie-button cookie-button-accept">Aceptar</button>
                    <button type="button" class="cookie-button cookie-button-reject">Denegar</button>
                    <button type="button" class="cookie-button cookie-button-preferences">Ver preferencias</button>
                </div>
                <div class="cookie-mini-banner-links">
                    <a href="${this.legalData.documents.cookies.url}">${this.legalData.documents.cookies.title.toUpperCase()}</a>
                    <a href="${this.legalData.documents.privacy.url}">${this.legalData.documents.privacy.title.toUpperCase()}</a>
                    <a href="${this.legalData.documents.terms.url}">${this.legalData.documents.terms.title.toUpperCase()}</a>
                </div>
            </div>`;

        this.fullBanner = document.createElement('div');
        this.fullBanner.className = 'cookie-consent-banner';
        this.fullBanner.style.display = 'none';
        this.fullBanner.innerHTML = `
            <div class="cookie-consent-modal">
                <div class="cookie-consent-header">
                    <h3 class="cookie-consent-title">Preferencias de Cookies</h3>
                    <button type="button" class="cookie-consent-close">&times;</button>
                </div>
                <div class="cookie-consent-body">
                    <p>Utilizamos cookies propias y de terceros para obtener datos estadísticos de la navegación de nuestros usuarios, ofrecer marketing personalizado y mejorar nuestros servicios. Tienes más información en nuestra Política de Cookies (enlace a página de cookies).</p>
                    <div class="cookie-option">
                        <div class="cookie-option-header">
                            <h4>Funcional</h4>
                            <span class="cookie-option-status">Siempre activo</span>
                        </div>
                    </div>
                    <div class="cookie-option">
                        <div class="cookie-option-header">
                            <h4><span>Estadísticas</span> <i class="cookie-toggle-info fa fa-info-circle" data-target="cookie-analytics-info"></i></h4>
                            <label class="cookie-switch"><input type="checkbox" id="cookie-analytics-checkbox"><span class="cookie-slider"></span></label>
                        </div>
                        <div id="cookie-analytics-info" class="cookie-option-details" style="display:none;">
                            <p>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.</p>
                        </div>
                    </div>
                    <div class="cookie-option">
                        <div class="cookie-option-header">
                            <h4><span>Marketing</span> <i class="cookie-toggle-info fa fa-info-circle" data-target="cookie-marketing-info"></i></h4>
                            <label class="cookie-switch"><input type="checkbox" id="cookie-marketing-checkbox"><span class="cookie-slider"></span></label>
                        </div>
                        <div id="cookie-marketing-info" class="cookie-option-details" style="display:none;">
                            <p>El almacenamiento o acceso técnico es necesario para crear perfiles de usuario para enviar publicidad, o para rastrear al usuario en una web o en varias web con fines de marketing similares.</p>
                        </div>
                    </div>
                </div>
                <div class="cookie-consent-footer">
                    <div class="footer-buttons-left">
                        <button type="button" class="cookie-button cookie-button-save">Guardar preferencias</button>
                        <button type="button" class="cookie-button cookie-button-accept">Aceptar todas</button>
                        <button type="button" class="cookie-button cookie-button-reject">Denegar todas</button>
                    </div>
                </div>
            </div>`;

        this.cookieSettingsButton = document.createElement('div');
        this.cookieSettingsButton.className = 'cookie-settings-button';
        this.cookieSettingsButton.style.display = 'none';
        this.cookieSettingsButton.innerHTML = '🍪';

        this.container.appendChild(this.miniBannerWrapper);
        this.container.appendChild(this.fullBanner);
        this.container.appendChild(this.cookieSettingsButton);
    }

    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();
    }

    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();
    }

    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();
    }

    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;
        if (consent.analytics) {
            console.log('Analytics cookies enabled');
        } else {
            console.log('Analytics cookies disabled');
        }
        if (consent.marketing) {
            console.log('Marketing cookies enabled');
        } else {
            console.log('Marketing cookies disabled');
        }
    }

    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();
    }

    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();
    }

    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) {
        const expirationDate = new Date();
        expirationDate.setFullYear(expirationDate.getFullYear() + 1);
        
        // Guardar cookie
        document.cookie = `${this.cookieName}=${encodeURIComponent(JSON.stringify(consent))};expires=${expirationDate.toUTCString()};path=/;SameSite=Lax`;
        
        // Emitir evento para que otros scripts puedan reaccionar al cambio
        const event = new CustomEvent('cookieConsentChanged', {
            detail: consent
        });
        document.dispatchEvent(event);
        
        console.log('Consentimiento guardado y evento emitido:', consent);
        this.applyConsent(consent);
    }

    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) {
                const encodedValue = c.substring(nameEQ.length, c.length);
                return decodeURIComponent(encodedValue);
            }
        }
        return null;
    }
    
    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;
        }
    }

}

document.addEventListener('DOMContentLoaded', () => {
    window.cookieConsent = new CookieConsent();
    window.cookieConsent.init();
});
