/* Maple GDPR Cookies - Frontend JavaScript */
(function() {
    'use strict';
    
    // Check if consent already given
    if (getCookie('mgc_consent')) {
        return;
    }
    
    // Create and show cookie notice
    document.addEventListener('DOMContentLoaded', function() {
        createNotice();
    });
    
    function createNotice() {
        const settings = window.mgcSettings || {};
        
        // Create notice container
        const notice = document.createElement('div');
        notice.className = 'mgc-notice mgc-position-' + (settings.position || 'bottom') + 
                          ' mgc-theme-' + (settings.theme || 'light') +
                          ' mgc-animation-' + (settings.animation || 'slide');
        
        // Create content
        const content = document.createElement('div');
        content.className = 'mgc-notice-content';
        // Decode HTML entities and strip slashes
        const noticeText = (settings.noticeText || 'We use cookies to enhance your browsing experience.')
            .replace(/\\"/g, '"')
            .replace(/\\\\/g, '\\')
            .replace(/&quot;/g, '"')
            .replace(/"Accept All"/g, '<strong>Accept All</strong>')
            .replace(/"Reject All"/g, '<strong>Reject All</strong>');
        content.innerHTML = noticeText;
        
        // Add privacy policy link if provided
        if (settings.privacyPolicyUrl) {
            content.innerHTML += ' <a href="' + settings.privacyPolicyUrl + '" class="mgc-privacy-link" target="_blank">' + 
                               (settings.privacyPolicyText || 'Privacy Policy') + '</a>';
        }
        
        // Create buttons container
        const buttons = document.createElement('div');
        buttons.className = 'mgc-notice-buttons';
        
        // Accept button
        const acceptBtn = document.createElement('button');
        acceptBtn.className = 'mgc-button mgc-button-accept mgc-button-color-' + (settings.buttonColor || 'blue');
        acceptBtn.textContent = settings.acceptButtonText || 'Accept All';
        acceptBtn.onclick = function() {
            handleConsent('accept', ['analytics', 'marketing', 'functional']);
        };
        buttons.appendChild(acceptBtn);
        
        // Reject button (optional)
        if (settings.showRejectButton) {
            const rejectBtn = document.createElement('button');
            rejectBtn.className = 'mgc-button mgc-button-reject mgc-button-color-' + (settings.buttonColor || 'blue');
            rejectBtn.textContent = settings.rejectButtonText || 'Reject All';
            rejectBtn.onclick = function() {
                handleConsent('reject', []);
            };
            buttons.appendChild(rejectBtn);
        }
        
        // Settings button (optional)
        if (settings.showSettingsButton) {
            const settingsBtn = document.createElement('button');
            settingsBtn.className = 'mgc-button mgc-button-settings mgc-button-color-' + (settings.buttonColor || 'blue');
            settingsBtn.textContent = settings.settingsButtonText || 'Cookie Settings';
            settingsBtn.onclick = function() {
                showSettingsModal();
            };
            buttons.appendChild(settingsBtn);
        }
        
        // Append elements
        notice.appendChild(content);
        notice.appendChild(buttons);
        document.body.appendChild(notice);
    }
    
    function showSettingsModal() {
        // Remove initial notice
        const initialNotice = document.querySelector('.mgc-notice');
        if (initialNotice) {
            initialNotice.classList.add('mgc-hidden');
        }
        
        // Create settings modal
        const modal = document.createElement('div');
        modal.className = 'mgc-settings-modal';
        
        const modalContent = document.createElement('div');
        modalContent.className = 'mgc-settings-content';
        
        // Modal title
        const title = document.createElement('h3');
        title.textContent = 'Cookie Settings';
        title.style.marginTop = '0';
        modalContent.appendChild(title);
        
        // Description
        const desc = document.createElement('p');
        desc.textContent = 'Choose which types of cookies you want to allow:';
        modalContent.appendChild(desc);
        
        // Cookie categories
        const categories = [
            {
                id: 'functional',
                label: 'Functional Cookies',
                description: 'These cookies are essential for the website to function properly.',
                required: true
            },
            {
                id: 'analytics',
                label: 'Analytics Cookies',
                description: 'Help us understand how visitors interact with our website.',
                required: false
            },
            {
                id: 'marketing',
                label: 'Marketing Cookies',
                description: 'Used to track visitors across websites for marketing purposes.',
                required: false
            }
        ];
        
        const checkboxes = [];
        categories.forEach(function(cat) {
            const categoryDiv = document.createElement('div');
            categoryDiv.className = 'mgc-category';
            categoryDiv.style.marginBottom = '15px';
            categoryDiv.style.padding = '10px';
            categoryDiv.style.border = '1px solid #ddd';
            categoryDiv.style.borderRadius = '4px';
            
            const label = document.createElement('label');
            label.style.display = 'flex';
            label.style.alignItems = 'flex-start';
            label.style.cursor = cat.required ? 'not-allowed' : 'pointer';
            
            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.id = 'mgc-cat-' + cat.id;
            checkbox.value = cat.id;
            checkbox.checked = true;
            checkbox.disabled = cat.required;
            checkbox.style.marginRight = '10px';
            checkbox.style.marginTop = '3px';
            
            if (!cat.required) {
                checkboxes.push(checkbox);
            }
            
            const textDiv = document.createElement('div');
            
            const labelText = document.createElement('strong');
            labelText.textContent = cat.label;
            if (cat.required) {
                labelText.textContent += ' (Required)';
            }
            
            const descText = document.createElement('div');
            descText.textContent = cat.description;
            descText.style.fontSize = '13px';
            descText.style.color = '#666';
            descText.style.marginTop = '3px';
            
            textDiv.appendChild(labelText);
            textDiv.appendChild(descText);
            
            label.appendChild(checkbox);
            label.appendChild(textDiv);
            categoryDiv.appendChild(label);
            modalContent.appendChild(categoryDiv);
        });
        
        // Buttons
        const buttonRow = document.createElement('div');
        buttonRow.className = 'mgc-notice-buttons';
        buttonRow.style.marginTop = '20px';
        
        // Accept Selected button
        const acceptSelected = document.createElement('button');
        acceptSelected.className = 'mgc-button mgc-button-accept mgc-button-color-' + (window.mgcSettings?.buttonColor || 'blue');
        acceptSelected.textContent = 'Save Preferences';
        acceptSelected.onclick = function() {
            const selectedCategories = ['functional']; // Always include functional
            checkboxes.forEach(function(cb) {
                if (cb.checked) {
                    selectedCategories.push(cb.value);
                }
            });
            handleConsent('accept', selectedCategories);
            modal.remove();
        };
        buttonRow.appendChild(acceptSelected);
        
        // Accept All button
        const acceptAll = document.createElement('button');
        acceptAll.className = 'mgc-button mgc-button-accept mgc-button-color-' + (window.mgcSettings?.buttonColor || 'blue');
        acceptAll.textContent = 'Accept All';
        acceptAll.onclick = function() {
            handleConsent('accept', ['functional', 'analytics', 'marketing']);
            modal.remove();
        };
        buttonRow.appendChild(acceptAll);
        
        // Reject All button
        const rejectAll = document.createElement('button');
        rejectAll.className = 'mgc-button mgc-button-settings mgc-button-color-' + (window.mgcSettings?.buttonColor || 'blue');
        rejectAll.textContent = 'Reject Optional';
        rejectAll.onclick = function() {
            handleConsent('accept', ['functional']);
            modal.remove();
        };
        buttonRow.appendChild(rejectAll);
        
        modalContent.appendChild(buttonRow);
        modal.appendChild(modalContent);
        document.body.appendChild(modal);
    }
    
    function handleConsent(type, categories) {
        // Set cookie
        const expiry = window.mgcSettings?.cookieExpiry || 365;
        setCookie('mgc_consent', type, expiry);
        setCookie('mgc_consent_categories', JSON.stringify(categories), expiry);
        
        // Send to server (fire and forget)
        if (window.mgcSettings?.ajaxUrl) {
            const formData = new FormData();
            formData.append('action', 'mgc_save_consent');
            formData.append('nonce', window.mgcSettings.nonce);
            formData.append('consent_type', type);
            
            categories.forEach(function(cat) {
                formData.append('categories[]', cat);
            });
            
            fetch(window.mgcSettings.ajaxUrl, {
                method: 'POST',
                body: formData
            }).catch(function() {
                // Silently fail - consent is saved in cookie anyway
            });
        }
        
        // Remove notice
        const notice = document.querySelector('.mgc-notice');
        if (notice) {
            notice.classList.add('mgc-hidden');
            setTimeout(function() {
                notice.remove();
            }, 300);
        }
        
        // Trigger custom event
        const event = new CustomEvent('mgc_consent_saved', {
            detail: {
                type: type,
                categories: categories
            }
        });
        document.dispatchEvent(event);
    }
    
    function setCookie(name, value, days) {
        const d = new Date();
        d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
        const expires = 'expires=' + d.toUTCString();
        document.cookie = name + '=' + value + ';' + expires + ';path=/;SameSite=Lax';
    }
    
    function 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 c.substring(nameEQ.length, c.length);
        }
        return null;
    }
    
})();
