/**
 * EarthPure Shop Plugin - Frontend JS
 * Winkelwagen, PayPal checkout, login modal, contact form
 */
(function($) {
    'use strict';

    let cart = [];
    const AJAX = epShop.ajaxUrl;
    const NONCE = epShop.nonce;

    /* =============================================
       TOAST NOTIFICATION
       ============================================= */
    function showToast(msg, duration = 3000) {
        let toast = document.getElementById('ep-toast');
        if (!toast) {
            toast = document.createElement('div');
            toast.id = 'ep-toast';
            document.body.appendChild(toast);
        }
        toast.textContent = msg;
        toast.classList.add('show');
        setTimeout(() => toast.classList.remove('show'), duration);
    }

    /* =============================================
       CART SIDEBAR LOGIC
       ============================================= */
    // Inject cart HTML into page
    function injectCartHTML() {
        if (document.getElementById('ep-cart-sidebar')) return;
        const html = `
        <div id="ep-cart-overlay"></div>
        <div id="ep-cart-sidebar">
            <div class="ep-cart-header">
                <h3>🛒 Winkelwagen</h3>
                <button class="ep-cart-close" id="ep-cart-close">✕</button>
            </div>
            <div class="ep-cart-items" id="ep-cart-items">
                <div class="ep-cart-empty">Je winkelwagen is leeg.</div>
            </div>
            <div class="ep-cart-footer">
                <div class="ep-cart-total">
                    <span>Totaal:</span>
                    <span id="ep-cart-total-amount">€0,00</span>
                </div>
                <button class="ep-checkout-btn" id="ep-checkout-btn">Bestelling plaatsen →</button>
            </div>
        </div>

        <!-- Checkout Modal -->
        <div id="ep-checkout-modal">
            <div class="ep-modal-box">
                <button class="ep-modal-close" id="ep-checkout-close">✕</button>
                <h3>📦 Verzendgegevens</h3>
                <textarea class="ep-address-field" id="ep-shipping-address" rows="3" placeholder="Bezorgadres (optioneel)"></textarea>
                <div id="paypal-button-container"></div>
                <p style="text-align:center;color:#999;font-size:0.85rem;margin-top:12px;">Veilig betalen via PayPal</p>
            </div>
        </div>`;
        document.body.insertAdjacentHTML('beforeend', html);
        bindCartEvents();
    }

    function bindCartEvents() {
        document.getElementById('ep-cart-overlay')?.addEventListener('click', closeCart);
        document.getElementById('ep-cart-close')?.addEventListener('click', closeCart);
        document.getElementById('ep-checkout-close')?.addEventListener('click', () => {
            document.getElementById('ep-checkout-modal').classList.remove('open');
        });
        document.getElementById('ep-checkout-btn')?.addEventListener('click', openCheckout);
    }

    window.epOpenCart = function() {
        injectCartHTML();
        document.getElementById('ep-cart-sidebar')?.classList.add('open');
        document.getElementById('ep-cart-overlay')?.classList.add('open');
        document.body.style.overflow = 'hidden';
    };

    function closeCart() {
        document.getElementById('ep-cart-sidebar')?.classList.remove('open');
        document.getElementById('ep-cart-overlay')?.classList.remove('open');
        document.body.style.overflow = '';
    }

    function renderCart(data) {
        cart = data.cart || [];
        const count = data.count || 0;
        const total = data.total || 0;

        // Update count badges
        document.querySelectorAll('#ep-cart-count, .ep-cart-count').forEach(el => {
            el.textContent = count;
        });

        // Update total
        const totalEl = document.getElementById('ep-cart-total-amount');
        if (totalEl) totalEl.textContent = '€' + parseFloat(total).toFixed(2).replace('.', ',');

        // Render items
        const itemsEl = document.getElementById('ep-cart-items');
        if (!itemsEl) return;

        if (cart.length === 0) {
            itemsEl.innerHTML = '<div class="ep-cart-empty">🛒 Je winkelwagen is leeg.</div>';
            return;
        }

        itemsEl.innerHTML = cart.map(item => `
            <div class="ep-cart-item">
                <img src="${item.img || ''}" alt="${item.name}">
                <div class="ep-cart-item-info">
                    <h4>${item.name}</h4>
                    <span class="ep-cart-item-price">${item.qty} × €${parseFloat(item.price).toFixed(2).replace('.',',')}</span>
                </div>
                <button class="ep-cart-item-remove" data-id="${item.id}">✕</button>
            </div>
        `).join('');

        // Remove buttons
        itemsEl.querySelectorAll('.ep-cart-item-remove').forEach(btn => {
            btn.addEventListener('click', function() {
                $.post(AJAX, { action: 'ep_remove_from_cart', nonce: NONCE, product_id: this.dataset.id })
                    .done(r => r.success && renderCart(r.data));
            });
        });
    }

    /* =============================================
       ADD TO CART
       ============================================= */
    $(document).on('click', '.ep-add-to-cart', function() {
        const btn = $(this);
        const id    = btn.data('id');
        const name  = btn.data('name');
        const price = btn.data('price');
        const img   = btn.data('img');
        const orig  = btn.text();

        btn.text('⏳ Toevoegen...').prop('disabled', true);

        $.post(AJAX, { action: 'ep_add_to_cart', nonce: NONCE, product_id: id, name, price, img })
            .done(function(r) {
                if (r.success) {
                    injectCartHTML();
                    renderCart(r.data);
                    showToast('✅ ' + name + ' toegevoegd!');
                    btn.text('✅ Toegevoegd!');
                    setTimeout(epOpenCart, 500);
                } else {
                    btn.text('❌ Fout');
                }
            })
            .fail(() => btn.text('❌ Probeer opnieuw'))
            .always(() => setTimeout(() => { btn.text(orig).prop('disabled', false); }, 2000));
    });

    /* =============================================
       PAYPAL CHECKOUT
       ============================================= */
    function openCheckout() {
        if (cart.length === 0) { showToast('⚠️ Winkelwagen is leeg'); return; }
        document.getElementById('ep-checkout-modal')?.classList.add('open');
        loadPayPalButtons();
    }

    function loadPayPalButtons() {
        const container = document.getElementById('paypal-button-container');
        if (!container || !epShop.paypalId) {
            if (container) container.innerHTML = '<p style="color:#e53935;text-align:center;">⚠️ Stel eerst je PayPal Client ID in via EP Bestellingen → Instellingen.</p>';
            return;
        }
        container.innerHTML = '<p style="text-align:center;color:#999;">PayPal laden...</p>';

        // Load PayPal SDK dynamically
        if (window.paypal) {
            renderPayPalButtons(container);
            return;
        }
        const script = document.createElement('script');
        script.src = `https://www.paypal.com/sdk/js?client-id=${epShop.paypalId}&currency=${epShop.currency}`;
        script.onload = () => renderPayPalButtons(container);
        document.head.appendChild(script);
    }

    function renderPayPalButtons(container) {
        container.innerHTML = '';
        const total = cart.reduce((s, i) => s + i.price * i.qty, 0).toFixed(2);

        window.paypal.Buttons({
            createOrder: (data, actions) => actions.order.create({
                purchase_units: [{
                    amount: { value: total, currency_code: epShop.currency },
                    description: 'EarthPure Shop Bestelling',
                }]
            }),
            onApprove: (data, actions) => actions.order.capture().then(details => {
                const address = document.getElementById('ep-shipping-address')?.value || '';
                $.post(AJAX, { action: 'ep_create_order', nonce: NONCE, address })
                    .done(r => {
                        if (r.success) {
                            $.post(AJAX, { action: 'ep_complete_order', nonce: NONCE, order_id: r.data.order_id, paypal_order_id: data.orderID })
                                .done(() => {
                                    document.getElementById('ep-checkout-modal')?.classList.remove('open');
                                    closeCart();
                                    cart = [];
                                    renderCart({ cart: [], count: 0, total: 0 });
                                    showToast('🎉 Bestelling geplaatst! Bedankt!', 5000);
                                });
                        }
                    });
            }),
            onError: err => showToast('❌ PayPal fout: ' + err.message, 5000),
        }).render('#paypal-button-container');
    }

    /* =============================================
       CONTACT FORM
       ============================================= */
    $(document).on('submit', '#ep-contact-form', function(e) {
        e.preventDefault();
        const form = $(this);
        const btn = form.find('[type="submit"]');
        const resp = $('#ep-contact-response');
        btn.text('⏳ Versturen...').prop('disabled', true);

        $.post(AJAX, {
            action: 'ep_contact_submit',
            nonce: epShop.contactNonce,
            name: form.find('[name="name"]').val(),
            email: form.find('[name="email"]').val(),
            phone: form.find('[name="phone"]').val(),
            message: form.find('[name="message"]').val(),
        }).done(r => {
            if (r.success) {
                resp.css({ display:'block', background:'#E8F5E9', color:'#2e7d32', border:'1px solid #A5D6A7', padding:'12px', borderRadius:'8px' }).text('✅ ' + r.data.msg);
                form[0].reset();
            } else {
                resp.css({ display:'block', background:'#FFEBEE', color:'#c62828', border:'1px solid #FFCDD2', padding:'12px', borderRadius:'8px' }).text('❌ ' + (r.data?.msg || 'Fout'));
            }
        }).always(() => {
            btn.text('✉️ Verstuur bericht').prop('disabled', false);
            setTimeout(() => resp.fadeOut(), 6000);
        });
    });

    /* =============================================
       INIT
       ============================================= */
    $(function() {
        injectCartHTML();
        // Laad cart uit sessie
        $.post(AJAX, { action: 'ep_get_cart', nonce: NONCE })
            .done(r => r.success && renderCart({ cart: r.data, count: r.data.length, total: r.data.reduce((s, i) => s + i.price * i.qty, 0) }));
    });

})(jQuery);
