/**
 * Packages & memberships storefront ([yatoon_growth_storefront]).
 *
 * Every value this needs arrives on the .yatoon-storefront element as a data
 * attribute, so nothing here is generated by PHP -- which is what made it
 * safe to lift out of the template verbatim.
 */
(function(){
    var root = document.currentScript && document.currentScript.previousElementSibling;
    // Fallback: locate the storefront DOM by class.
    var nodes = document.querySelectorAll('.yatoon-storefront');
    nodes.forEach(function(node){
        if ( node.dataset.bound === '1' ) return;
        node.dataset.bound = '1';
        var stripeReady = node.dataset.stripe === '1';
        var pk          = node.dataset.pk;
        var ajaxUrl     = node.dataset.ajax;
        var nonce       = node.dataset.nonce;

        var modal = node.querySelector('.yatoon-storefront-modal');
        var form  = node.querySelector('.ys-purchase-form');
        var status = node.querySelector('.ys-status');
        var titleEl = node.querySelector('.ys-modal-title');
        var sumEl   = node.querySelector('.ys-modal-summary');
        var submit  = node.querySelector('.ys-submit');
        var errEl   = node.querySelector('.ys-card-error');
        var current = { type:'', id:0, label:'' };

        // 4.4.3: Payment Element instead of the legacy Card Element.
        //
        // The backend has always created PaymentIntents with
        // automatic_payment_methods enabled, but the browser only ever
        // rendered a card field -- so iDEAL, Bancontact, SEPA, Klarna,
        // Alipay and WeChat Pay were being offered by Stripe and then
        // silently thrown away here. Payment Element renders whatever
        // the merchant has enabled and the buyer's country supports.
        //
        // Uses deferred-intent mode ({mode, amount, currency}) so the
        // form can mount before we know which item the customer picks;
        // the amount is pushed in via elements.update() when the modal
        // opens.
        var stripe = null, elements = null, paymentElement = null;
        var currency = (node.dataset.currency || 'usd').toLowerCase();
        if ( stripeReady && pk && window.Stripe ) {
            try {
                stripe   = window.Stripe(pk);
                elements = stripe.elements({
                    mode: 'payment',
                    amount: 1000,          // placeholder, replaced on open
                    currency: currency
                });
                paymentElement = elements.create('payment');
                paymentElement.mount(node.querySelector('.ys-payment-element'));
                paymentElement.on('change', function(e){ errEl.textContent = e.error ? e.error.message : ''; });
            } catch(e){ console.error('Stripe init failed', e); stripeReady = false; }
        }

        // Some methods (iDEAL, Bancontact, Alipay...) take the customer
        // off-site and return via return_url. Finish those here.
        (function resumeRedirectPayment(){
            if ( !stripe ) { return; }
            var params = new URLSearchParams(window.location.search);
            var secret = params.get('payment_intent_client_secret');
            var pending = params.get('yatoon_purchase');
            if ( !secret || !pending ) { return; }

            stripe.retrievePaymentIntent(secret).then(function(res){
                var pi = res && res.paymentIntent;
                if ( !pi ) { return; }
                if ( pi.status !== 'succeeded' && pi.status !== 'processing' ) {
                    status.className = 'ys-status ys-error';
                    status.textContent = 'Payment was not completed.';
                    return;
                }
                var fd = new FormData();
                fd.append('action','yatoon_growth_confirm_purchase');
                fd.append('nonce', nonce);
                fd.append('purchase_id', pending);
                fd.append('intent_id', pi.id);
                fetch(ajaxUrl, { method:'POST', body:fd, credentials:'same-origin' })
                    .then(function(r){ return r.json(); })
                    .then(function(json){
                        status.className = 'ys-status ' + ((json && json.success) ? 'ys-success' : 'ys-error');
                        status.textContent = (json && json.data && json.data.message)
                            ? json.data.message
                            : ((json && json.success) ? 'Activated!' : 'Activation failed. Please contact us.');
                    });
            });
        })();

        function openModal(card){
            current.type  = card.dataset.type;
            current.id    = parseInt(card.dataset.id, 10);
            current.label = card.querySelector('h4').textContent.trim();
            // Payment Element decides which methods to offer partly from
            // the amount, so it has to know the real one before display.
            var amount = parseInt(card.dataset.amount, 10);
            if ( elements && amount > 0 ) {
                try { elements.update({ amount: amount }); } catch(e){}
            }
            titleEl.textContent = current.label;
            sumEl.textContent   = card.querySelector('.ys-meta').textContent.trim();
            status.textContent  = '';
            status.className    = 'ys-status';
            modal.hidden = false;
        }
        function closeModal(){ modal.hidden = true; }

        node.querySelectorAll('.ys-buy-btn').forEach(function(btn){
            btn.addEventListener('click', function(){ openModal(btn.closest('.yatoon-storefront-card')); });
        });
        node.querySelector('.ys-modal-close').addEventListener('click', closeModal);
        modal.addEventListener('click', function(e){ if(e.target===modal) closeModal(); });

        form.addEventListener('submit', function(ev){
            ev.preventDefault();
            submit.disabled = true;
            status.className = 'ys-status';
            status.textContent = '...';

            var fd = new FormData();
            fd.append('action', 'yatoon_growth_create_purchase');
            fd.append('nonce', nonce);
            fd.append('item_type', current.type);
            fd.append('item_id', current.id);
            fd.append('customer_name',  form.customer_name.value);
            fd.append('customer_email', form.customer_email.value);
            fd.append('customer_phone', form.customer_phone.value);

            fetch(ajaxUrl, { method:'POST', body: fd, credentials:'same-origin' })
                .then(function(r){ return r.json(); })
                .then(function(json){
                    if (!json || !json.success) {
                        status.className = 'ys-status ys-error';
                        status.textContent = (json && json.data && json.data.message) ? json.data.message : 'Could not start purchase.';
                        submit.disabled = false;
                        return;
                    }
                    var purchaseId = json.data.purchase_id;
                    if ( stripeReady && json.data.client_secret && stripe && elements ) {
                        status.textContent = 'Confirming payment...';
                        // return_url carries the purchase id so the
                        // redirect handler above can finish activation
                        // for off-site methods. redirect:'if_required'
                        // keeps cards inline exactly as before.
                        var returnUrl = new URL(window.location.href);
                        returnUrl.searchParams.set('yatoon_purchase', purchaseId);
                        elements.submit().then(function(subRes){
                            if (subRes && subRes.error) {
                                status.className = 'ys-status ys-error';
                                status.textContent = subRes.error.message || 'Payment failed.';
                                submit.disabled = false;
                                return null;
                            }
                            return stripe.confirmPayment({
                                elements: elements,
                                clientSecret: json.data.client_secret,
                                confirmParams: {
                                    return_url: returnUrl.toString(),
                                    payment_method_data: {
                                        billing_details: {
                                            name:  form.customer_name.value,
                                            email: form.customer_email.value
                                        }
                                    }
                                },
                                redirect: 'if_required'
                            });
                        }).then(function(result){
                            if (!result) { return; }
                            if (result.error) {
                                status.className = 'ys-status ys-error';
                                status.textContent = result.error.message || 'Payment failed.';
                                submit.disabled = false;
                                return;
                            }
                            var fd2 = new FormData();
                            fd2.append('action','yatoon_growth_confirm_purchase');
                            fd2.append('nonce', nonce);
                            fd2.append('purchase_id', purchaseId);
                            fd2.append('intent_id', result.paymentIntent.id);
                            fetch(ajaxUrl, { method:'POST', body:fd2, credentials:'same-origin' })
                                .then(function(r){ return r.json(); })
                                .then(function(json2){
                                    if (json2 && json2.success) {
                                        status.className = 'ys-status ys-success';
                                        status.textContent = json2.data.message || 'Activated!';
                                        form.reset();
                                    } else {
                                        status.className = 'ys-status ys-error';
                                        status.textContent = (json2 && json2.data && json2.data.message) ? json2.data.message : 'Activation failed. Please contact us.';
                                    }
                                    submit.disabled = false;
                                });
                        });
                    } else {
                        status.className = 'ys-status ys-success';
                        status.textContent = json.data.message || 'Request received. We will contact you shortly.';
                        form.reset();
                        submit.disabled = false;
                    }
                })
                .catch(function(){
                    status.className = 'ys-status ys-error';
                    status.textContent = 'Network error. Please try again.';
                    submit.disabled = false;
                });
        });
    });
})();
