export class CookieBanner extends HTMLElement {
    connectedCallback() {
        const currentStatus = sessionStorage.getItem('ldk_cookie');

        if (currentStatus === 'accepted' || currentStatus === 'refused') {
            this.triggerEvent(currentStatus);
            this.renderTrigger(currentStatus); // On passe le statut au trigger
            return;
        }

        if (!currentStatus) {
            sessionStorage.setItem('ldk_cookie', 'non');
        }

        this.renderBanner();
    }

    triggerEvent(status) {
        const eventName = status === 'accepted' ? 'cookieAccepted' : 'cookieRefused';
        window.dispatchEvent(new CustomEvent(eventName, {
            detail: { status, timestamp: new Date().toISOString() }
        }));
    }

    // Le badge affiche maintenant une couleur selon le statut
    renderTrigger(status) {
        const colorClass = status === 'accepted' ? 'border-green-500' : 'border-red-500';
        const shadowClass = status === 'accepted' ? 'shadow-green-100' : 'shadow-red-100';

        this.innerHTML = `
            <button id="cookie-reopen" title="Modifier vos préférences cookies"
                class="fixed bottom-4 right-4 bg-white border-2 ${colorClass} ${shadowClass} p-3 rounded-full shadow-lg hover:scale-110 transition-all z-40 text-2xl duration-300 flex items-center justify-center">
                <span class="relative flex h-3 w-3 mr-1">
                    <span class="animate-ping absolute inline-flex h-full w-full rounded-full ${status === 'accepted' ? 'bg-green-400' : 'bg-red-400'} opacity-75"></span>
                    <span class="relative inline-flex rounded-full h-3 w-3 ${status === 'accepted' ? 'bg-green-500' : 'bg-red-500'}"></span>
                </span>
                🍪
            </button>
        `;
        this.querySelector('#cookie-reopen').addEventListener('click', () => this.renderBanner());
    }

    renderBanner() {
        this.innerHTML = `
            <div id="cookie-banner" class="fixed bottom-4 left-4 right-4 md:left-auto md:max-w-md z-50">
                <div class="bg-white border border-gray-200 rounded-xl shadow-2xl p-6 transition-all duration-300 transform scale-100 opacity-100">
                    <div class="flex flex-col gap-4">
                        <div class="flex-1">
                            <h3 class="text-lg font-semibold text-gray-900 flex items-center gap-2">
                                🍪 Gestion des cookies
                            </h3>

                            <p class="mt-2 text-sm text-gray-600 leading-relaxed">
                                En acceptant les cookies, vous permettez au site d'activer des outils qui mesurent la <strong>vitesse du site</strong> et la <strong>liste des pages vues</strong>. Ces analyses nous permettent d'améliorer le site en continu. Ces données sont <strong>non revendues</strong> !
                            </p>

                            <div class="mt-4 p-3 bg-gray-50 rounded-lg border border-gray-100">
                                <div class="flex items-center gap-2 mb-1">
                                    <span class="flex h-2 w-2 rounded-full bg-blue-500"></span>
                                    <span class="text-[10px] font-bold uppercase tracking-wider text-gray-700">Cookies techniques essentiels</span>
                                </div>
                                <p class="text-[12px] text-gray-500 leading-snug">
                                    Ces cookies sont <strong>obligatoires</strong> pour permettre la navigation, la sécurisation de vos accès et le processus de réservation. Ils ne peuvent pas être désactivés.
                                </p>
                            </div>
                        </div>
                    </div>

                    <div class="mt-6 flex flex-col sm:flex-row gap-3">
                        <button id="btn-accept" class="flex-1 bg-slate-900 hover:bg-slate-800 text-white text-sm font-semibold py-2.5 px-4 rounded-lg transition-all active:scale-95">
                            Accepter tout
                        </button>
                        <button id="btn-refuse" class="flex-1 bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-medium py-2.5 px-4 rounded-lg transition-all">
                            Refuser
                        </button>
                    </div>

                    <div class="mt-4 flex justify-center gap-4 text-[11px] text-gray-400">
                        <a href="/reservation/cookies" class="underline hover:text-gray-600">Politique de cookies</a>
                        <a href="/reservation/rgpd" class="underline hover:text-gray-600">Charte RGPD</a>
                    </div>
                </div>
            </div>
        `;

        this.querySelector('#btn-accept').addEventListener('click', () => this.updateStatus('accepted'));
        this.querySelector('#btn-refuse').addEventListener('click', () => this.updateStatus('refused'));
    }

    updateStatus(status) {
        sessionStorage.setItem('ldk_cookie', status);

        // Synchronisation avec le script Umami
        if (status === 'accepted') {
            localStorage.removeItem('umami.disabled');
            console.log("✅ Umami activé dans le localStorage");
        } else {
            localStorage.setItem('umami.disabled', '1');
            console.log("🛑 Umami désactivé dans le localStorage");
        }

        // Déclenchement de tes Custom Events
        this.triggerEvent(status);

        // Animation de sortie
        const banner = this.querySelector('#cookie-banner > div');
        if (banner) {
            banner.classList.add('opacity-0', 'translate-y-8', 'scale-95');
            setTimeout(() => {
                this.renderTrigger(status);
            }, 300);
        }
    }
}

if (!customElements.get('cookie-banner')) {
    customElements.define('cookie-banner', CookieBanner);
}
