(function(){
    var CONF = window.FLUX_PAYNOW || {};
    var mode = CONF.mode || 'redirect';

    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';
            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>';
            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', CONF.nonce || '');
        p.set('_wp_http_referer', location.pathname);

        var pre = CONF.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;

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

        // --- Hosted Fields mode: navigate to the checkout page (where the
        //     inline hosted-fields form lives). Order is created on checkout
        //     submit, no need to pre-create here.
        if (mode === 'hosted_fields') {
            window.location.assign(CONF.checkout_url || '/checkout');
            return;
        }

        // --- Redirect mode (existing behavior) ---
        var url = CONF.ajax_url || (location.origin + '/?wc-ajax=checkout');

        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 || (CONF.checkout_url || '/checkout'));
                return;
            }
            if (data && data.reload === 'true') {
                window.location.assign(CONF.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 {
            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});
})();
