// Cookie Consent Popup - Fixed Version
(function() {
    'use strict';

    // Wait for DOM to be ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initCookieConsent);
    } else {
        initCookieConsent();
    }

    function initCookieConsent() {

        // Check if user already made a choice
        function getCookie(name) {
            var value = "; " + document.cookie;
            var parts = value.split("; " + name + "=");
            if (parts.length === 2) return parts.pop().split(";").shift();
            return null;
        }

        function setCookie(name, value, days) {
            var expires = "";
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toUTCString();
            }
            document.cookie = name + "=" + (value || "") + expires + "; path=/; SameSite=Lax";
        }

        // If already accepted/rejected, hide popup and exit
        if (getCookie('cookie_consent')) {
            var existingPopup = document.getElementById('cookieConsentPopup');
            if (existingPopup) {
                existingPopup.style.display = 'none';
            }
            var existingModal = document.getElementById('cookieModal');
            if (existingModal) {
                existingModal.style.display = 'none';
            }
            return;
        }

        // Check if popup already exists in DOM
        var popup = document.getElementById('cookieConsentPopup');
        if (popup) {
            // Popup already exists, just make sure it's visible
            popup.style.display = 'block';
            attachEventListeners();
            return;
        }

        // Create popup HTML
        var popupHTML = `
        <div id="cookieConsentPopup" style="
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: #0B1F3A;
            color: #fff;
            padding: 30px 20px 20px;
            z-index: 99999;
            box-shadow: 0 -10px 40px rgba(0,0,0,0.3);
            border-top: 3px solid #00C2FF;
            display: block;
        ">
            <div style="max-width: 1200px; margin: 0 auto; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 20px;">
                <div style="flex: 1; min-width: 280px;">
                    <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
                        <span style="font-size: 1.8rem;">🍪</span>
                        <span style="font-family: 'Poppins', sans-serif; font-weight: 700; font-size: 1.2rem; color: #fff;">There for you. Future Business.</span>
                    </div>
                    <p style="font-size: 0.85rem; color: #b9c9e0; margin: 0; line-height: 1.6; max-width: 700px;">
                        This website uses cookies, pixels and similar technologies ("Cookies"), some of which are provided by third parties,
                        for purposes such as to enable certain features and functionality, measure and analyze performance and usage,
                        enhance user experiences, and personalize content and ads. To manage your preferences related to these Cookies,
                        click on "Customize Settings."
                    </p>
                </div>
                <div style="display: flex; flex-wrap: wrap; gap: 10px; align-items: center; flex-shrink: 0;">
                    <button id="cookieCustomize" style="
                        background: transparent;
                        border: 1px solid #00C2FF;
                        color: #00C2FF;
                        padding: 10px 22px;
                        border-radius: 8px;
                        font-weight: 600;
                        font-size: 0.85rem;
                        cursor: pointer;
                        transition: 0.3s;
                        font-family: 'Inter', sans-serif;
                    ">Cookies Settings</button>
                    
                    <button id="cookieReject" style="
                        background: transparent;
                        border: 1px solid #6b7a90;
                        color: #b9c9e0;
                        padding: 10px 22px;
                        border-radius: 8px;
                        font-weight: 600;
                        font-size: 0.85rem;
                        cursor: pointer;
                        transition: 0.3s;
                        font-family: 'Inter', sans-serif;
                    ">Reject All</button>
                    
                    <button id="cookieAccept" style="
                        background: linear-gradient(90deg, #007BFF, #00C2FF);
                        border: none;
                        color: #fff;
                        padding: 10px 28px;
                        border-radius: 8px;
                        font-weight: 700;
                        font-size: 0.85rem;
                        cursor: pointer;
                        transition: 0.3s;
                        font-family: 'Inter', sans-serif;
                        box-shadow: 0 4px 15px rgba(0,194,255,0.3);
                    ">Accept All Cookies</button>
                </div>
            </div>
        </div>

        <!-- Customize Settings Modal -->
        <div id="cookieModal" style="
            display: none;
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.6);
            z-index: 999999;
            align-items: center;
            justify-content: center;
            backdrop-filter: blur(4px);
        ">
            <div style="
                background: #fff;
                border-radius: 16px;
                max-width: 500px;
                width: 90%;
                padding: 35px;
                max-height: 80vh;
                overflow-y: auto;
                color: #1c2b3f;
            ">
                <h4 style="font-family: 'Poppins', sans-serif; font-weight: 700; margin-bottom: 20px; color: #0B1F3A;">Cookie Settings</h4>
                <p style="font-size: 0.9rem; color: #6b7a90; margin-bottom: 20px;">Choose which cookies you want to allow. Essential cookies are required for the website to function properly.</p>
                
                <div style="border: 1px solid #eaeff5; border-radius: 10px; padding: 15px; margin-bottom: 12px;">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <strong style="font-size: 0.95rem;">Essential Cookies</strong>
                            <p style="font-size: 0.8rem; color: #6b7a90; margin: 0;">Required for basic site functionality</p>
                        </div>
                        <span style="background: #e8f5e9; color: #2e7d32; padding: 2px 12px; border-radius: 20px; font-size: 0.75rem; font-weight: 600;">Always On</span>
                    </div>
                </div>

                <div style="border: 1px solid #eaeff5; border-radius: 10px; padding: 15px; margin-bottom: 12px;">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <strong style="font-size: 0.95rem;">Analytics Cookies</strong>
                            <p style="font-size: 0.8rem; color: #6b7a90; margin: 0;">Help us understand how you use our site</p>
                        </div>
                        <label style="position: relative; display: inline-block; width: 48px; height: 26px;">
                            <input type="checkbox" id="analyticsCookies" checked style="opacity:0; width:0; height:0;">
                            <span style="position: absolute; cursor: pointer; top:0; left:0; right:0; bottom:0; background:#ccc; transition:0.3s; border-radius:26px;"></span>
                        </label>
                    </div>
                </div>

                <div style="border: 1px solid #eaeff5; border-radius: 10px; padding: 15px; margin-bottom: 20px;">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <strong style="font-size: 0.95rem;">Marketing Cookies</strong>
                            <p style="font-size: 0.8rem; color: #6b7a90; margin: 0;">Used for personalized ads and content</p>
                        </div>
                        <label style="position: relative; display: inline-block; width: 48px; height: 26px;">
                            <input type="checkbox" id="marketingCookies" checked style="opacity:0; width:0; height:0;">
                            <span style="position: absolute; cursor: pointer; top:0; left:0; right:0; bottom:0; background:#ccc; transition:0.3s; border-radius:26px;"></span>
                        </label>
                    </div>
                </div>

                <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                    <button id="modalSavePreferences" style="
                        flex: 1;
                        background: linear-gradient(90deg, #007BFF, #00C2FF);
                        border: none;
                        color: #fff;
                        padding: 12px;
                        border-radius: 8px;
                        font-weight: 600;
                        cursor: pointer;
                    ">Save Preferences</button>
                    <button id="modalAcceptAll" style="
                        flex: 1;
                        background: #0B1F3A;
                        border: none;
                        color: #fff;
                        padding: 12px;
                        border-radius: 8px;
                        font-weight: 600;
                        cursor: pointer;
                    ">Accept All</button>
                    <button id="modalClose" style="
                        background: transparent;
                        border: 1px solid #ccc;
                        color: #6b7a90;
                        padding: 12px 20px;
                        border-radius: 8px;
                        cursor: pointer;
                    ">Close</button>
                </div>
            </div>
        </div>
        `;

        // Append popup to body
        document.body.insertAdjacentHTML('beforeend', popupHTML);

        // Now attach event listeners
        attachEventListeners();

        // Style toggle switches
        styleToggles();

    } // end initCookieConsent

    function attachEventListeners() {
        var popup = document.getElementById('cookieConsentPopup');
        var modal = document.getElementById('cookieModal');
        var acceptBtn = document.getElementById('cookieAccept');
        var rejectBtn = document.getElementById('cookieReject');
        var customizeBtn = document.getElementById('cookieCustomize');
        var modalClose = document.getElementById('modalClose');
        var modalAcceptAll = document.getElementById('modalAcceptAll');
        var modalSavePrefs = document.getElementById('modalSavePreferences');
        var analyticsCheck = document.getElementById('analyticsCookies');
        var marketingCheck = document.getElementById('marketingCookies');

        function setCookie(name, value, days) {
            var expires = "";
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toUTCString();
            }
            document.cookie = name + "=" + (value || "") + expires + "; path=/; SameSite=Lax";
        }

        function acceptAll() {
            setCookie('cookie_consent', 'accepted', 365);
            setCookie('analytics_consent', 'true', 365);
            setCookie('marketing_consent', 'true', 365);
            if (popup) popup.style.display = 'none';
            if (modal) modal.style.display = 'none';
        }

        function rejectAll() {
            setCookie('cookie_consent', 'rejected', 365);
            setCookie('analytics_consent', 'false', 365);
            setCookie('marketing_consent', 'false', 365);
            if (popup) popup.style.display = 'none';
            if (modal) modal.style.display = 'none';
        }

        function savePreferences() {
            setCookie('cookie_consent', 'customized', 365);
            setCookie('analytics_consent', analyticsCheck && analyticsCheck.checked ? 'true' : 'false', 365);
            setCookie('marketing_consent', marketingCheck && marketingCheck.checked ? 'true' : 'false', 365);
            if (popup) popup.style.display = 'none';
            if (modal) modal.style.display = 'none';
        }

        // Event Listeners - with null checks
        if (acceptBtn) {
            acceptBtn.addEventListener('click', acceptAll);
        }
        
        if (rejectBtn) {
            rejectBtn.addEventListener('click', rejectAll);
        }
        
        if (customizeBtn) {
            customizeBtn.addEventListener('click', function() {
                if (modal) modal.style.display = 'flex';
            });
        }
        
        if (modalClose) {
            modalClose.addEventListener('click', function() {
                if (modal) modal.style.display = 'none';
            });
        }
        
        if (modalAcceptAll) {
            modalAcceptAll.addEventListener('click', function() {
                if (analyticsCheck) analyticsCheck.checked = true;
                if (marketingCheck) marketingCheck.checked = true;
                styleToggles();
                acceptAll();
            });
        }
        
        if (modalSavePrefs) {
            modalSavePrefs.addEventListener('click', savePreferences);
        }

        // Close modal on outside click
        if (modal) {
            modal.addEventListener('click', function(e) {
                if (e.target === modal) {
                    modal.style.display = 'none';
                }
            });
        }
    }

    function styleToggles() {
        document.querySelectorAll('#cookieModal label span').forEach(function(span) {
            var checkbox = span.previousElementSibling;
            if (checkbox && checkbox.checked) {
                span.style.background = '#007BFF';
            } else if (checkbox) {
                span.style.background = '#ccc';
            }
            if (checkbox) {
                checkbox.addEventListener('change', function() {
                    span.style.background = this.checked ? '#007BFF' : '#ccc';
                });
            }
        });
    }

})();