(function(){
'use strict';
var activeTab = 'credit', shipCost = 0;

var _getCsrf = Bridge.getCsrf;
window._ceToast = window._ceToast || function(msg) {
    var t = document.createElement('div');
    t.textContent = msg;
    t.style.cssText = 'position:fixed;bottom:24px;left:50%;transform:translateX(-50%);padding:10px 24px;background:var(--accent,#2D6A4F);color:#fff;border-radius:10px;font-size:13px;font-weight:700;z-index:99999;animation:fadeIn .3s';
    document.body.appendChild(t);
    setTimeout(function(){ t.remove(); }, 2000);
};

var tabs = document.getElementById('pay-tabs');
if (tabs) tabs.addEventListener('click', function(e){
    var btn = e.target.closest('.pay-tab');
    if (!btn) return;
    tabs.querySelectorAll('.pay-tab').forEach(function(b){ b.classList.remove('pay-tab-active'); });
    btn.classList.add('pay-tab-active');
    activeTab = btn.dataset.panel;
    document.querySelectorAll('.pay-panel').forEach(function(p){ p.classList.remove('active'); });
    var p = document.getElementById('panel-' + activeTab);
    if (p) p.classList.add('active');
});

document.querySelectorAll('input[name="shipping"]').forEach(function(r){
    r.addEventListener('change', function(){
        shipCost = this.value === 'express' ? 20 : 0;
        var el = document.getElementById('pay-shipping');
        if (el) {
            el.textContent = shipCost > 0 ? '$' + shipCost.toFixed(2) : 'FREE';
            el.className = shipCost > 0 ? '' : 'co-free';
        }
        document.querySelectorAll('.pay-ship-opt').forEach(function(o){ o.classList.remove('pay-ship-active'); });
        if (this.closest('.pay-ship-opt')) this.closest('.pay-ship-opt').classList.add('pay-ship-active');
        recalcTotal();
    });
});

var billingSame = document.getElementById('pay-billing-same');
if (billingSame) {
    billingSame.addEventListener('change', function(){
        var fields = document.getElementById('pay-billing-fields');
        if (fields) fields.style.display = this.checked ? 'none' : 'block';
    });
}

var agreementTimestamps = {};
document.querySelectorAll('.co-agreement-check').forEach(function(cb){
    cb.addEventListener('change', function(){
        if (this.checked) {
            agreementTimestamps[this.id] = Date.now();
            this.setAttribute('data-agreed-at', agreementTimestamps[this.id]);
        } else {
            delete agreementTimestamps[this.id];
            this.removeAttribute('data-agreed-at');
        }
    });
});

function _getCart(){
    try {
        var raw = localStorage.getItem('cart');
        if (!raw) return [];
        var cart = JSON.parse(raw);
        if (!Array.isArray(cart)) return [];
        return cart.map(function(i){
            return {
                id: i.productId || i.id || 0,
                variantId: i.variantId || 0,
                sizeId: i.sizeId || 0,
                t: i.productName || i.name || '',
                variant: i.qualityName || '',
                sizeLabel: i.sizeLabel || '',
                p: parseFloat(i.unitPrice || i.price) || 0,
                q: parseInt(i.quantity || i.qty, 10) || 1,
                img: i.image || '',
                code: i.code || ''
            };
        });
    } catch(e){ return []; }
}

function _saveCart(items){
    try {
        var mapped = items.map(function(i){
            return {
                variantId: i.variantId || 0,
                sizeId: i.sizeId || 0,
                productId: i.id || 0,
                productName: i.t || '',
                qualityName: i.variant || '',
                typeName: '',
                sizeLabel: i.sizeLabel || '',
                unitPrice: i.p || 0,
                quantity: i.q || 1,
                image: i.img || ''
            };
        });
        localStorage.setItem('cart', JSON.stringify(mapped));
        if (typeof Cart !== 'undefined' && Cart.renderDrawer) Cart.renderDrawer();
    } catch(e){}
}

function recalcTotal(){
    var items = _getCart();
    var sub = items.reduce(function(s,i){ return s + (i.p * i.q); }, 0);
    var total = sub + shipCost;
    var creditEl = document.getElementById('pay-use-credit');
    var creditAmt = 0;
    if (creditEl && creditEl.checked) {
        creditAmt = Math.min(parseFloat(creditEl.dataset.amt || '0'), total);
        total = Math.max(0, total - creditAmt);
        var cl = document.getElementById('pay-credit-line');
        var cv = document.getElementById('pay-credit-val');
        if (cl) cl.style.display = '';
        if (cv) cv.textContent = '-$' + creditAmt.toFixed(2);
    } else {
        var cl2 = document.getElementById('pay-credit-line');
        if (cl2) cl2.style.display = 'none';
    }
    var subEl = document.getElementById('pay-subtotal');
    var totalEl = document.getElementById('pay-total');
    if (subEl) subEl.textContent = '$' + sub.toFixed(2);
    if (totalEl) totalEl.textContent = '$' + total.toFixed(2);
    var etAmt = document.getElementById('pay-et-amount');
    if (etAmt) etAmt.textContent = 'Amount: $' + total.toFixed(2) + ' CAD';
}
window.recalcTotal = recalcTotal;

function renderCart(){
    var el = document.getElementById('pay-cart-items');
    var emptyEl = document.getElementById('co-empty');
    if (!el) return;
    var items = _getCart();
    if (!items.length) {
        el.innerHTML = '';
        if (emptyEl) emptyEl.style.display = 'block';
        recalcTotal();
        return;
    }
    if (emptyEl) emptyEl.style.display = 'none';
    el.innerHTML = items.map(function(i){
        var lt = i.p * i.q;
        var esc = function(s){ var d = document.createElement('div'); d.textContent = s; return d.innerHTML; };
        var label = esc(i.t);
        if (i.variant) label += ' <span style="color:#888;font-size:0.8em">(' + esc(i.variant) + ')</span>';
        if (i.sizeLabel) label += ' <span style="color:#888;font-size:0.8em">· ' + esc(i.sizeLabel) + '</span>';
        return '<div class="co-item">' +
            '<div class="co-item-info"><span class="co-item-name">' + label + '</span></div>' +
            '<div class="co-qty-wrap">' +
                '<button class="co-qty-btn" data-vid="' + i.variantId + '" data-sid="' + i.sizeId + '" data-a="d">' +
                    '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="5" y1="12" x2="19" y2="12"/></svg>' +
                '</button>' +
                '<span class="co-qty-val">' + i.q + '</span>' +
                '<button class="co-qty-btn" data-vid="' + i.variantId + '" data-sid="' + i.sizeId + '" data-a="i">' +
                    '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>' +
                '</button>' +
            '</div>' +
            '<button class="co-del-btn" data-vid="' + i.variantId + '" data-sid="' + i.sizeId + '" data-a="x">' +
                '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>' +
            '</button>' +
            '<span class="co-item-price">$' + lt.toFixed(2) + '</span>' +
        '</div>';
    }).join('');
    recalcTotal();
}

var cartList = document.getElementById('pay-cart-items');
if (cartList) cartList.addEventListener('click', function(e){
    var btn = e.target.closest('[data-vid]');
    if (!btn) return;
    var vid = parseInt(btn.dataset.vid), sid = parseInt(btn.dataset.sid), a = btn.dataset.a;
    var items = _getCart();
    if (a === 'x') items = items.filter(function(i){ return !(i.variantId === vid && i.sizeId === sid); });
    else if (a === 'i') { var it = items.find(function(i){ return i.variantId === vid && i.sizeId === sid; }); if (it) it.q++; }
    else if (a === 'd') { var it2 = items.find(function(i){ return i.variantId === vid && i.sizeId === sid; }); if (it2) it2.q = Math.max(1, it2.q - 1); }
    _saveCart(items);
    if (window._ce) { window._ce.items = items; window._ce.badge(); }
    renderCart();
});

var creditCb = document.getElementById('pay-use-credit');
if (creditCb) creditCb.addEventListener('change', recalcTotal);

function generateEtRef(){
    var hex = '';
    for (var i = 0; i < 8; i++) hex += Math.floor(Math.random() * 16).toString(16).toUpperCase();
    return 'CP-' + hex;
}

var etRefEl = document.getElementById('pay-et-ref');
if (etRefEl && !etRefEl.textContent.trim()) {
    etRefEl.textContent = generateEtRef();
}

renderCart();

var pk = window._stripePk || '';
var stripe, elements, cardNum, cardExp, cardCvc;
function _initStripe() {
    if (typeof Stripe === 'undefined') return false;
    stripe = Stripe(pk);
    elements = stripe.elements();
    var ss = {
        base: { fontFamily: "system-ui,sans-serif", fontSize: '14px', color: '#1B2E1B', '::placeholder': { color: '#bbb' } },
        invalid: { color: '#E76F51' }
    };
    cardNum = elements.create('cardNumber', { style: ss, showIcon: true });
    cardExp = elements.create('cardExpiry', { style: ss });
    cardCvc = elements.create('cardCvc', { style: ss });
    var mN = document.getElementById('stripe-card-number');
    var mE = document.getElementById('stripe-card-expiry');
    var mC = document.getElementById('stripe-card-cvc');
    if (mN) cardNum.mount(mN);
    if (mE) cardExp.mount(mE);
    if (mC) cardCvc.mount(mC);
    var errEl2 = document.getElementById('pay-error');
    if (cardNum && errEl2) {
        [cardNum, cardExp, cardCvc].forEach(function(el){
            if (el) el.on('change', function(e){
                if (e.error) { errEl2.style.display = 'block'; errEl2.textContent = e.error.message; }
                else { errEl2.style.display = 'none'; }
            });
        });
    }
    return true;
}
if (pk && pk.length > 5) {
    if (!_initStripe()) {
        var _stripeAttempts = 0;
        var _stripeTimer = setInterval(function(){
            _stripeAttempts++;
            if (_initStripe() || _stripeAttempts > 50) {
                clearInterval(_stripeTimer);
                if (_stripeAttempts > 50) {
                    var ct2 = document.querySelector('[data-panel="credit"]');
                    if (ct2) { ct2.style.opacity = '0.4'; ct2.style.pointerEvents = 'none'; }
                }
            }
        }, 200);
    }
} else {
    var ct = document.querySelector('[data-panel="credit"]');
    if (ct) { ct.style.opacity = '0.4'; ct.style.pointerEvents = 'none'; }
}
document.querySelectorAll('.pay-crypto-btn').forEach(function(btn){
    btn.addEventListener('click', function(){
        document.querySelectorAll('.pay-crypto-btn').forEach(function(b){ b.classList.remove('active'); });
        this.classList.add('active');
        document.querySelectorAll('.pay-wallet').forEach(function(w){ w.classList.remove('active'); });
        var w = document.getElementById('wallet-' + this.dataset.wallet);
        if (w) w.classList.add('active');
    });
});

document.querySelectorAll('.pay-wallet-addr').forEach(function(el){
    el.addEventListener('click', function(){
        navigator.clipboard.writeText(this.textContent.trim());
        _ceToast('\u2713');
    });
});

if (etRefEl) etRefEl.addEventListener('click', function(){
    navigator.clipboard.writeText(this.textContent.trim());
    _ceToast('\u2713');
});

function getFieldsByTab(){
    if (activeTab === 'crypto') {
        return {
            name: (document.getElementById('pay-crypto-name') || {}).value || '',
            email: (document.getElementById('pay-crypto-email') || {}).value || '',
            unit: (document.getElementById('pay-crypto-unit') || {}).value || '',
            addr: (document.getElementById('pay-crypto-address') || {}).value || '',
            city: (document.getElementById('pay-crypto-city') || {}).value || '',
            prov: (document.getElementById('pay-crypto-province') || {}).value || '',
            post: (document.getElementById('pay-crypto-postal') || {}).value || '',
            country: (document.getElementById('pay-crypto-country') || {}).value || 'Canada'
        };
    }
    if (activeTab === 'et') {
        return {
            name: (document.getElementById('pay-et-name') || {}).value || '',
            email: (document.getElementById('pay-et-email') || {}).value || '',
            unit: (document.getElementById('pay-et-unit') || {}).value || '',
            addr: (document.getElementById('pay-et-address') || {}).value || '',
            city: (document.getElementById('pay-et-city') || {}).value || '',
            prov: (document.getElementById('pay-et-province') || {}).value || '',
            post: (document.getElementById('pay-et-postal') || {}).value || '',
            country: (document.getElementById('pay-et-country') || {}).value || 'Canada'
        };
    }
    return {
        name: (document.getElementById('pay-name') || {}).value || '',
        email: (document.getElementById('pay-email') || {}).value || '',
        unit: (document.getElementById('pay-unit') || {}).value || '',
        addr: (document.getElementById('pay-address') || {}).value || '',
        city: (document.getElementById('pay-city') || {}).value || '',
        prov: (document.getElementById('pay-province') || {}).value || '',
        post: (document.getElementById('pay-postal') || {}).value || '',
        country: (document.getElementById('pay-country') || {}).value || 'Canada'
    };
}

function _showSuccess(ref, method, amount) {
    var layout = document.getElementById('co-layout');
    if (!layout) return;
    var ml = method === 'stripe' ? 'Credit Card' : method === 'etransfer' ? 'E-Transfer' : 'Cryptocurrency';
    var shipType = (document.querySelector('input[name="shipping"]:checked') || {}).value || 'standard';
    var isExpress = shipType === 'express';
    var stages = ['Order Placed','Payment Verified','Packaging','Shipped to Partner','Out for Delivery','Delivered'];
    var timelineHtml = '<div class="track-timeline" style="margin:20px 0">';
    for (var i = 0; i < stages.length; i++) {
        var cls = i === 0 ? 'track-tl-done track-tl-current' : '';
        timelineHtml += '<div class="track-tl-step ' + cls + '"><div class="track-tl-dot">' + (i+1) + '</div><div class="track-tl-label">' + stages[i] + '</div></div>';
        if (i < stages.length - 1) timelineHtml += '<div class="track-tl-line"></div>';
    }
    timelineHtml += '</div>';
    layout.innerHTML =
        '<div style="text-align:center;padding:40px 20px;max-width:520px;margin:0 auto">' +
            '<div style="width:72px;height:72px;border-radius:50%;background:linear-gradient(135deg,#2D6A4F,#40916C);margin:0 auto 24px;display:flex;align-items:center;justify-content:center">' +
                '<svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg>' +
            '</div>' +
            '<div style="font-size:22px;font-weight:800;color:#1B4332;margin-bottom:8px">Order Confirmed</div>' +
            '<div style="font-size:14px;color:#555;margin-bottom:20px">Your order has been placed and fulfillment has started.</div>' +
            (isExpress ? '<div class="track-express-badge" style="margin:0 auto 16px;display:inline-flex"><svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M13 2L4 14h7l-2 8 9-12h-7l2-8z"/></svg> Express Post</div>' : '') +
            '<div style="background:#F0F7F4;border-radius:12px;padding:20px;text-align:left;margin-bottom:20px">' +
                '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px"><span style="color:#666;font-size:13px">Tracking #</span><span style="display:flex;align-items:center;gap:8px"><span style="font-weight:700;font-size:14px;color:#1B4332;letter-spacing:0.5px">' + ref + '</span><button onclick="navigator.clipboard.writeText(\'' + ref + '\');if(window._ceToast)window._ceToast(\'Copied!\');" style="background:none;border:1px solid #ccc;border-radius:4px;padding:2px 6px;cursor:pointer;font-size:11px">Copy</button></span></div>' +
                '<div style="display:flex;justify-content:space-between;margin-bottom:10px"><span style="color:#666;font-size:13px">Payment</span><span style="font-weight:600;font-size:13px;color:#2D6A4F">' + ml + '</span></div>' +
                '<div style="display:flex;justify-content:space-between"><span style="color:#666;font-size:13px">Total</span><span style="font-weight:700;font-size:14px;color:#1B4332">$' + amount + ' CAD</span></div>' +
            '</div>' +
            timelineHtml +
            '<div style="font-size:12px;color:#888;margin-bottom:24px">Save your tracking number. You can check your order status anytime.</div>' +
            '<button onclick="if(typeof Router!==\'undefined\')Router.navigate(\'track\',{ref:\'' + ref + '\'}); else window.location.href=\'?v=tracking&ref=' + ref + '\';" style="width:100%;padding:14px;background:linear-gradient(135deg,#2D6A4F,#40916C);color:#fff;border:none;border-radius:10px;font-size:15px;font-weight:700;cursor:pointer;margin-bottom:10px">Track My Order</button>' +
            '<button onclick="if(typeof Router!==\'undefined\')Router.navigate(\'home\');else window.location.href=\'/\';" style="width:100%;padding:12px;background:transparent;color:#2D6A4F;border:1.5px solid #2D6A4F;border-radius:10px;font-size:14px;font-weight:600;cursor:pointer">Continue Shopping</button>' +
        '</div>';
}

var btn = document.getElementById('pay-submit');
var lbl = document.getElementById('pay-submit-label');
var errEl = document.getElementById('pay-error');
if (btn) btn.addEventListener('click', async function(){
    if (!document.getElementById('pay-agree-tos').checked ||
        !document.getElementById('pay-agree-cb').checked ||
        !document.getElementById('pay-agree-fulfillment').checked) {
        if (errEl) { errEl.style.display = 'block'; errEl.textContent = 'Please accept all agreements before placing your order.'; }
        return;
    }
    var cart = _getCart();
    if (!cart.length) {
        if (errEl) { errEl.style.display = 'block'; errEl.textContent = 'Cart is empty'; }
        return;
    }
    var fields = getFieldsByTab();
    var fullAddr = (fields.unit ? fields.unit.trim() + ' ' : '') + fields.addr.trim();
    if (!fields.name.trim() || !fullAddr.trim() || !fields.city.trim() || !fields.prov || !fields.post.trim()) {
        if (errEl) { errEl.style.display = 'block'; errEl.textContent = 'Complete all shipping fields'; }
        return;
    }
    if (lbl) lbl.textContent = 'PROCESSING...';
    btn.disabled = true;
    if (errEl) errEl.style.display = 'none';
    var shipType = (document.querySelector('input[name="shipping"]:checked') || {}).value || 'standard';
    var useCredit = document.getElementById('pay-use-credit');
    var payload = {
        action: 'place_order',
        m: activeTab,
        payment_method: activeTab === 'credit' ? 'stripe' : activeTab === 'et' ? 'etransfer' : 'crypto',
        cart: JSON.stringify(cart.map(function(i){ return { id: i.id, qty: i.q, variant_id: i.vid || i.variantId || 0, size_id: i.sizeId || 0 }; })),
        name: fields.name.trim(),
        email: fields.email.trim(),
        address: fullAddr.trim(),
        city: fields.city.trim(),
        province: fields.prov,
        postal: fields.post.trim(),
        country: fields.country.trim(),
        shipping_method: shipType,
        shipping_cost: shipCost,
        use_credit: useCredit && useCredit.checked ? '1' : '0',
        csrf: _getCsrf(),
        agree_cb_ts: agreementTimestamps['pay-agree-cb'] || '',
        agree_tos_ts: agreementTimestamps['pay-agree-tos'] || '',
        agree_fulfillment_ts: agreementTimestamps['pay-agree-fulfillment'] || ''
    };
    if (activeTab === 'crypto') {
        payload.txhash = (document.getElementById('pay-txhash') || {}).value || '';
        var activeCoin = document.querySelector('.pay-crypto-btn.active');
        payload.crypto_coin = activeCoin ? (activeCoin.dataset.wallet || 'xmr').toUpperCase() : 'XMR';
    } else if (activeTab === 'et') {
        payload.etransfer_ref = (document.getElementById('pay-et-ref') || {}).textContent || '';
    } else {
        var cardName = (document.getElementById('pay-card-name') || {}).value || fields.name;
        var billing = { name: cardName.trim() };
        var billSame = document.getElementById('pay-billing-same');
        if (billSame && !billSame.checked) {
            billing.address = {
                line1: ((document.getElementById('pay-bunit') || {}).value || '').trim() + ' ' + ((document.getElementById('pay-baddr') || {}).value || '').trim(),
                city: (document.getElementById('pay-bcity') || {}).value || '',
                state: (document.getElementById('pay-bprov') || {}).value || '',
                postal_code: (document.getElementById('pay-bpostal') || {}).value || fields.post,
                country: (document.getElementById('pay-bcountry') || {}).value || fields.country
            };
        } else {
            var cardPostal = (document.getElementById('pay-card-postal') || {}).value || fields.post;
            billing.address = { line1: fullAddr, city: fields.city.trim(), state: fields.prov, postal_code: cardPostal.trim() || fields.post.trim(), country: fields.country };
        }
        if (stripe && cardNum) {
            var pm = await stripe.createPaymentMethod({ type: 'card', card: cardNum, billing_details: billing });
            if (pm.error) {
                if (errEl) { errEl.style.display = 'block'; errEl.textContent = pm.error.message; }
                if (lbl) lbl.textContent = 'Confirm Purchase';
                btn.disabled = false;
                return;
            }
            payload.pm_id = pm.paymentMethod.id;
        }
    }
    try {
        payload.route = 'order.place_order';
        var res = await fetch('api/index.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload),
            credentials: 'same-origin'
        });
        var data = await res.json().catch(function(){ return {}; });
        if (data.ok && data.order_ref) {
            if (data.client_secret && activeTab === 'credit' && stripe && cardNum) {
                var r = await stripe.confirmCardPayment(data.client_secret, {
                    payment_method: { card: cardNum, billing_details: { name: cardName || fields.name } }
                });
                if (r.error) {
                    if (errEl) { errEl.style.display = 'block'; errEl.textContent = r.error.message; }
                    if (lbl) lbl.textContent = 'Confirm Purchase';
                    btn.disabled = false;
                    return;
                }
            }
            _saveCart([]);
            if (window._ce) window._ce.clear();
            if (typeof Cart !== 'undefined' && Cart.updateBadge) Cart.updateBadge();
            _showSuccess(data.order_ref, payload.payment_method, data.amount || '0.00');
            return;
        }
        if (errEl) { errEl.style.display = 'block'; errEl.textContent = data.error || 'Order failed'; }
    } catch(e) {
        if (errEl) { errEl.style.display = 'block'; errEl.textContent = 'Connection error'; }
    }
    if (lbl) lbl.textContent = 'Confirm Purchase';
    btn.disabled = false;
});
})();
