/**
 * EarthPure Theme - Main JavaScript
 * Handles: cart sidebar, login modal, mobile menu, contact form AJAX
 */

(function($) {
    'use strict';

    /* =============================================
       MOBILE HAMBURGER
       ============================================= */
    const hamburger = document.getElementById('hamburger');
    const primaryNav = document.getElementById('primary-nav');

    if (hamburger && primaryNav) {
        hamburger.addEventListener('click', function() {
            primaryNav.classList.toggle('open');
            hamburger.setAttribute('aria-expanded', primaryNav.classList.contains('open'));
        });
        // Close on outside click
        document.addEventListener('click', function(e) {
            if (!hamburger.contains(e.target) && !primaryNav.contains(e.target)) {
                primaryNav.classList.remove('open');
            }
        });
    }

    /* =============================================
       CART SIDEBAR
       ============================================= */
    const cartToggle  = document.getElementById('cart-toggle');
    const cartSidebar = document.getElementById('cart-sidebar');
    const cartOverlay = document.getElementById('cart-overlay');
    const cartClose   = document.getElementById('cart-close');

    function openCart() {
        if (cartSidebar) cartSidebar.classList.add('active');
        if (cartOverlay) cartOverlay.classList.add('active');
        document.body.style.overflow = 'hidden';
    }

    function closeCart() {
        if (cartSidebar) cartSidebar.classList.remove('active');
        if (cartOverlay) cartOverlay.classList.remove('active');
        document.body.style.overflow = '';
    }

    if (cartToggle)  cartToggle.addEventListener('click', openCart);
    if (cartOverlay) cartOverlay.addEventListener('click', closeCart);
    if (cartClose)   cartClose.addEventListener('click', closeCart);

    // Add to cart buttons
    document.querySelectorAll('.add-to-cart-btn').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const productId = this.dataset.productId;
            const originalText = this.textContent;
            this.textContent = '⏳ Toevoegen...';
            this.disabled = true;

            $.post(earthpureData.ajaxUrl, {
                action: 'woocommerce_ajax_add_to_cart',
                product_id: productId,
                quantity: 1,
                nonce: earthpureData.nonce
            }).done(function(response) {
                if (response.error) {
                    btn.textContent = '❌ Fout';
                } else {
                    btn.textContent = '✅ Toegevoegd!';
                    // Update cart count
                    $(document.body).trigger('wc_fragment_refresh');
                    setTimeout(openCart, 400);
                }
            }).fail(function() {
                btn.textContent = '❌ Probeer opnieuw';
            }).always(function() {
                setTimeout(function() {
                    btn.textContent = originalText;
                    btn.disabled = false;
                }, 2000);
            });
        });
    });

    /* =============================================
       LOGIN MODAL
       ============================================= */
    const loginBtn   = document.getElementById('login-btn');
    const loginModal = document.getElementById('login-modal');
    const modalClose = document.getElementById('modal-close');
    const tabs       = document.querySelectorAll('.modal-tab');
    const tabContents = document.querySelectorAll('.tab-content');

    function openModal() {
        if (loginModal) {
            loginModal.classList.add('active');
            document.body.style.overflow = 'hidden';
        }
    }

    function closeModal() {
        if (loginModal) {
            loginModal.classList.remove('active');
            document.body.style.overflow = '';
        }
    }

    if (loginBtn)   loginBtn.addEventListener('click', openModal);
    if (modalClose) modalClose.addEventListener('click', closeModal);
    if (loginModal) loginModal.addEventListener('click', function(e) {
        if (e.target === loginModal) closeModal();
    });

    // Tab switching
    tabs.forEach(function(tab) {
        tab.addEventListener('click', function() {
            tabs.forEach(t => t.classList.remove('active'));
            tabContents.forEach(c => c.classList.remove('active'));
            this.classList.add('active');
            const target = document.getElementById('tab-' + this.dataset.tab);
            if (target) target.classList.add('active');
        });
    });

    /* =============================================
       CONTACT FORM - AJAX
       ============================================= */
    const contactForm = document.getElementById('contact-form');
    const formResponse = document.getElementById('form-response');

    if (contactForm) {
        contactForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const submitBtn = contactForm.querySelector('[type="submit"]');
            const originalText = submitBtn.textContent;
            submitBtn.textContent = '⏳ Versturen...';
            submitBtn.disabled = true;

            const data = {
                action: 'earthpure_contact',
                nonce: document.querySelector('#ep_nonce') ? document.querySelector('#ep_nonce').value : '',
                name: contactForm.querySelector('[name="name"]').value,
                email: contactForm.querySelector('[name="email"]').value,
                phone: contactForm.querySelector('[name="phone"]').value || '',
                message: contactForm.querySelector('[name="message"]').value,
            };

            $.post(earthpureData.ajaxUrl, data)
                .done(function(response) {
                    if (response.success) {
                        formResponse.style.background = '#E8F5E9';
                        formResponse.style.color = '#2E7D32';
                        formResponse.style.border = '1px solid #A5D6A7';
                        formResponse.textContent = '✅ ' + response.data.msg;
                        contactForm.reset();
                    } else {
                        formResponse.style.background = '#FFEBEE';
                        formResponse.style.color = '#c62828';
                        formResponse.style.border = '1px solid #FFCDD2';
                        formResponse.textContent = '❌ ' + (response.data ? response.data.msg : 'Er is een fout opgetreden.');
                    }
                    formResponse.style.display = 'block';
                })
                .fail(function() {
                    formResponse.style.background = '#FFEBEE';
                    formResponse.textContent = '❌ Verbindingsfout. Probeer het opnieuw.';
                    formResponse.style.display = 'block';
                })
                .always(function() {
                    submitBtn.textContent = originalText;
                    submitBtn.disabled = false;
                    setTimeout(function() { formResponse.style.display = 'none'; }, 6000);
                });
        });
    }

    /* =============================================
       SMOOTH SCROLL for anchors
       ============================================= */
    document.querySelectorAll('a[href^="#"]').forEach(function(anchor) {
        anchor.addEventListener('click', function(e) {
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                e.preventDefault();
                target.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        });
    });

    /* =============================================
       ESCAPE KEY handler
       ============================================= */
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeCart();
            closeModal();
        }
    });

    /* =============================================
       STICKY HEADER shadow on scroll
       ============================================= */
    const siteHeader = document.querySelector('.site-header');
    if (siteHeader) {
        window.addEventListener('scroll', function() {
            siteHeader.style.boxShadow = window.scrollY > 10
                ? '0 4px 20px rgba(0,0,0,0.12)'
                : '0 2px 10px rgba(0,0,0,0.06)';
        }, { passive: true });
    }

})(jQuery);
