/**
 * ASB Cookie Consent - Frontend JavaScript
 * Save as: frontend.js in plugin directory
 */

(function() {
    'use strict';
    
    const CC = {
        cookieName: 'asb_cookie_consent',
        
        init() {
            if (!this.hasConsent()) {
                this.showBanner();
                this.hideAgainButton(); // Hide show-again button when banner is showing
            } else {
                this.showAgainButton();
                this.loadScripts();
            }
            
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape') {
                    this.closeBanner();
                    this.closeSettings();
                }
            });
        },
        
        hasConsent() {
            return this.getCookie(this.cookieName) !== null;
        },
        
        showBanner() {
            const banner = document.getElementById('cc-banner');
            const backdrop = document.getElementById('cc-backdrop');
            const showAgainBtn = document.getElementById('cc-show-again');
            
            if (banner) {
                banner.style.display = 'block';
                // Only show backdrop if prior_consent mode is enabled
                if (backdrop && asbCC.settings.prior_consent) {
                    backdrop.style.display = 'block';
                }
            }
            
            // Hide show-again button when banner is visible
            if (showAgainBtn) {
                showAgainBtn.classList.remove('visible');
                console.log('❌ Banner shown, button hidden');
            }
        },
        
        hideBanner() {
            const banner = document.getElementById('cc-banner');
            const backdrop = document.getElementById('cc-backdrop');
            if (banner) banner.style.display = 'none';
            if (backdrop) backdrop.style.display = 'none'; // Hide backdrop when closing banner
        },
        
        showAgainButton() {
            const btn = document.getElementById('cc-show-again');
            if (btn) {
                btn.classList.add('visible');
                console.log('✅ Show-again button: VISIBLE'); // Debug
            }
        },
        
        hideAgainButton() {
            const btn = document.getElementById('cc-show-again');
            if (btn) {
                btn.classList.remove('visible');
                console.log('❌ Show-again button: HIDDEN'); // Debug
            }
        },
        
        closeBanner() {
            this.hideBanner();
        },
        
        acceptAll() {
            const consent = {
                necessary: true,
                functional: true,
                analytics: true,
                performance: true,
                advertisement: true,
                booking_consent: true, // Always true - required for service
                all: true
            };
            this.saveConsent(consent);
        },
        
        rejectAll() {
            const consent = {
                necessary: true,
                functional: false,
                analytics: false,
                performance: false,
                advertisement: false,
                booking_consent: true, // Always true even when rejecting - required for service
                all: false
            };
            this.saveConsent(consent);
        },
        
        showSettings() {
            const modal = document.getElementById('cc-modal');
            if (modal) {
                modal.style.display = 'flex';
                this.loadCurrentPreferences();
                
                // Focus first toggle
                setTimeout(() => {
                    const firstToggle = modal.querySelector('input[type="checkbox"]:not([disabled])');
                    if (firstToggle) firstToggle.focus();
                }, 100);
            }
        },
        
        closeSettings() {
            const modal = document.getElementById('cc-modal');
            if (modal) modal.style.display = 'none';
            // Don't hide backdrop here - it should stay if banner is still showing
        },
        
        loadCurrentPreferences() {
            const consent = this.getConsent();
            if (consent) {
                const ids = ['functional', 'analytics', 'performance', 'advertisement'];
                ids.forEach(id => {
                    const el = document.getElementById('cc-' + id);
                    if (el) el.checked = consent[id] || false;
                });
                // Booking consent always checked and disabled
                const bookingEl = document.getElementById('cc-booking');
                if (bookingEl) {
                    bookingEl.checked = true;
                    bookingEl.disabled = true;
                }
            }
        },
        
        savePreferences() {
            const consent = {
                necessary: true,
                functional: document.getElementById('cc-functional')?.checked || false,
                analytics: document.getElementById('cc-analytics')?.checked || false,
                performance: document.getElementById('cc-performance')?.checked || false,
                advertisement: document.getElementById('cc-advertisement')?.checked || false,
                booking_consent: true, // Always true - cannot be disabled
                all: false
            };
            this.saveConsent(consent); // This will hide banner AND backdrop
            this.closeSettings(); // Close modal
        },
        
        saveConsent(consent) {
            const expiry = asbCC.settings.cookie_expiry || 365;
            this.setCookie(this.cookieName, JSON.stringify(consent), expiry);
            
            // Send to backend
            if (typeof jQuery !== 'undefined') {
                jQuery.post(asbCC.ajaxurl, {
                    action: 'asb_save_consent',
                    nonce: asbCC.nonce,
                    consent: JSON.stringify(consent)
                });
            }
            
            this.hideBanner(); // This will hide both banner AND backdrop
            this.showAgainButton();
            this.loadScripts(consent);
            
            if (asbCC.settings.reload_on_accept) {
                setTimeout(() => location.reload(), 500);
            }
        },
        
        getConsent() {
            const cookie = this.getCookie(this.cookieName);
            return cookie ? JSON.parse(cookie) : null;
        },
        
        loadScripts(consent) {
            consent = consent || this.getConsent();
            if (!consent) return;
            
            if (consent.analytics && asbCC.settings.google_analytics_id) {
                this.loadGA(asbCC.settings.google_analytics_id);
            }
            
            if (consent.advertisement && asbCC.settings.facebook_pixel_id) {
                this.loadFBPixel(asbCC.settings.facebook_pixel_id);
            }
            
            if (consent.advertisement && asbCC.settings.gtm_id) {
                this.loadGTM(asbCC.settings.gtm_id);
            }
        },
        
        loadGA(id) {
            if (window.gtag) return;
            
            const script = document.createElement('script');
            script.async = true;
            script.src = 'https://www.googletagmanager.com/gtag/js?id=' + id;
            document.head.appendChild(script);
            
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            window.gtag = gtag;
            gtag('js', new Date());
            gtag('config', id);
        },
        
        loadFBPixel(id) {
            if (window.fbq) return;
            
            !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
            n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
            n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
            t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
            document,'script','https://connect.facebook.net/en_US/fbevents.js');
            
            fbq('init', id);
            fbq('track', 'PageView');
        },
        
        loadGTM(id) {
            if (window.dataLayer) return;
            
            (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
            new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
            j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
            'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
            })(window,document,'script','dataLayer',id);
        },
        
        setCookie(name, value, days) {
            const d = new Date();
            d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
            document.cookie = name + "=" + value + ";expires=" + d.toUTCString() + ";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);
                if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length);
            }
            return null;
        }
    };
    
    // Global functions
    window.ccAcceptAll = () => CC.acceptAll();
    window.ccRejectAll = () => CC.rejectAll();
    window.ccShowSettings = () => CC.showSettings();
    window.ccCloseSettings = () => CC.closeSettings();
    window.ccSavePreferences = () => CC.savePreferences();
    window.ccShowBanner = () => { 
        CC.hideAgainButton(); 
        CC.showBanner(); 
    };
    
    // Initialize
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => CC.init());
    } else {
        CC.init();
    }
})();