(function(){
    var FOOTERS = [
        '.wc-block-mini-cart__footer-actions',
        '.wc-block-mini-cart__footer-buttons',
        '.wc-block-mini-cart__actions',
        '.widget_shopping_cart_content .buttons'
    ].join(',');

    function ensureButton(container){
        if (!container) return;
        var btn = container.querySelector('.flux-pay-now-mini');
        if (!btn) {
            btn = document.createElement('button');
            btn.type = 'button';
            // keep theme's look if there is an existing button to mirror
            var neighbor = container.querySelector('a,button');
            btn.className = (neighbor ? neighbor.className + ' ' : '') + 'flux-pay-now-mini';
            btn.innerHTML =
                '<span class="flux-spinner" aria-hidden="true"></span>' +
                '<span>Pay Now</span>';
            // tidy up margins without fighting themes
            btn.style.marginInlineStart = '8px';
            container.appendChild(btn);
        }
        if (!btn.dataset.bound) {
            btn.dataset.bound = '1';
            btn.addEventListener('click', submitFluxCheckout, {passive:false});
        }
    }

    function buildPayload(){
        var p = new URLSearchParams();
        p.set('payment_method', 'flux_gateway');
        p.set('terms', 'on');
        p.set('woocommerce-process-checkout-nonce', (window.FLUX_PAYNOW||{}).nonce || '');
        p.set('_wp_http_referer', location.pathname);

        var pre = (window.FLUX_PAYNOW||{}).prefill || {};
        p.set('billing_email', pre.billing_email || '');
        p.set('billing_first_name', pre.billing_first_name || '');
        p.set('billing_last_name', pre.billing_last_name || '');
        return p;
    }

    async function submitFluxCheckout(e){
        e.preventDefault();
        var btn = e.currentTarget;
        if (btn.classList.contains('is-loading')) return; // prevent double submits

        var url = (window.FLUX_PAYNOW||{}).ajax_url || (location.origin + '/?wc-ajax=checkout');

        // loading UI
        btn.classList.add('is-loading');
        btn.setAttribute('aria-busy','true');
        btn.disabled = true;

        try {
            var res = await fetch(url, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                credentials: 'same-origin',
                body: buildPayload().toString()
            });
            var data = await res.json();

            if (data && data.result === 'success') {
                window.location.assign(data.redirect || ((window.FLUX_PAYNOW||{}).checkout_url || '/checkout'));
                return;
            }
            if (data && data.reload === 'true') {
                window.location.assign((window.FLUX_PAYNOW||{}).checkout_url || '/checkout');
                return;
            }

            var msg = (data && (data.messages || data.message)) || 'Checkout failed. Please try again.';
            alert(msg.replace(/<[^>]*>?/gm,'').trim());
        } catch (err) {
            alert('Network error during checkout. Please try again.');
        } finally {
            // reset only if we stayed on the page (no redirect)
            btn.classList.remove('is-loading');
            btn.removeAttribute('aria-busy');
            btn.disabled = false;
        }
    }

    function mount(){ 
        document.querySelectorAll(FOOTERS).forEach(ensureButton); 
    }
    
    mount();
    new MutationObserver(mount).observe(document.body, {subtree:true, childList:true});
})();

