(function(){
    var _h = Bridge._h;

'use strict';
var activeTab = 'credit', shipCost = 0;
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) : _h('46524545'); }
        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 diffBill = document.getElementById('pay-diff-billing');
if (diffBill) {
    diffBill.addEventListener('change', function(){
        var f = document.getElementById('pay-billing-fields');
        if (f) f.classList.toggle('active', this.checked);
    });
}
function _getCart(){
    try {
        if (window.CartAPI) return window.CartAPI.getCart();
        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: parseInt(i.id,10), t: i.name||'', p: parseFloat(i.price)||0, q: parseInt(i.qty,10)||1, code: i.code||'' };
        });
    } catch(e){ return []; }
}
function _saveCart(items){
    if (window.CartAPI) { window.CartAPI.clearCart(); return; }
    try { localStorage.removeItem('cart'); } catch(e){}
}
function recalcTotal(){
    var items = _getCart();
    var sub = items.reduce(function(s,i){ return s + ((parseFloat(i.price||i.p)||0) * (parseInt(i.qty||i.q,10)||1)); }, 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);
}
function renderCart(){
    var el = document.getElementById('pay-cart-items');
    if (!el) return;
    var items = _getCart();
    if (!items.length) {
        el.innerHTML = '<p style="font-size:12px;color:rgba(27,46,27,.4);text-align:center;padding:20px;letter-spacing:1px;text-transform:uppercase">No items</p>';
        recalcTotal();
        return;
    }
    el.innerHTML = items.map(function(i){
        var name = i.name || i.t || _h('4974656d');
        var price = parseFloat(i.price || i.p) || 0;
        var qty = parseInt(i.qty || i.q, 10) || 1;
        var lt = price * qty;
        var esc = function(s){ var d = document.createElement('div'); d.textContent = s; return d.innerHTML; };
        return '<div class="pay-cart-item">' +
            '<span class="pay-cart-item-name">' + esc(name) + '</span>' +
            '<span class="pay-cart-item-qty">\u00d7' + qty + '</span>' +
            '<span class="pay-cart-item-price">$' + lt.toFixed(2) + '</span>' +
        '</div>';
    }).join('');
    recalcTotal();
}
var creditCb = document.getElementById('pay-use-credit');
if (creditCb) creditCb.addEventListener('change', recalcTotal);
renderCart();
var pk = window._stripePk || '';
var stripe, elements, cardNum, cardExp, cardCvc;
if (pk && pk.length > 5) {
    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);
} else {
    var ct = document.querySelector('[data-panel="credit"]');
    if (ct) { ct.style.opacity = '0.4'; ct.style.pointerEvents = 'none'; }
}

var errEl = document.getElementById('pay-error');
if (cardNum && errEl) {
    [cardNum, cardExp, cardCvc].forEach(function(el){
        if (el) el.on('change', function(e){
            if (e.error) { errEl.style.display = 'block'; errEl.textContent = e.error.message; }
            else { errEl.style.display = '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');
    });
});
var etRef = document.getElementById('pay-et-ref');
if (etRef) etRef.addEventListener('click', function(){
    navigator.clipboard.writeText(this.textContent.trim());
    _ceToast('\u2713');
});
var btn = document.getElementById('pay-submit');
var lbl = document.getElementById('pay-submit-label');
if (btn) btn.addEventListener('click', async function(){
    if (!document.getElementById('pay-agree-tos').checked || !document.getElementById('pay-agree-cb').checked) {
        if (errEl) { errEl.style.display = 'block'; errEl.textContent = _h('506c656173652061636365707420626f74682061677265656d656e7473'); }
        return;
    }
    var cart = _getCart();
    if (!cart.length) {
        if (errEl) { errEl.style.display = 'block'; errEl.textContent = _h('4361727420697320656d707479'); }
        return;
    }

    var name = (document.getElementById('pay-name') || {}).value || '';
    var email = (document.getElementById('pay-email') || {}).value || '';
    var phone = (document.getElementById('pay-phone') || {}).value || '';
    var unit = (document.getElementById('pay-unit') || {}).value || '';
    var addr = (document.getElementById('pay-address') || {}).value || '';
    var city = (document.getElementById('pay-city') || {}).value || '';
    var prov = (document.getElementById('pay-province') || {}).value || '';
    var post = (document.getElementById('pay-postal') || {}).value || '';
    var fullAddr = (unit ? unit.trim() + ' ' : '') + addr.trim();
    if (!name.trim() || !fullAddr.trim() || !city.trim() || !prov || !post.trim()) {
        if (errEl) { errEl.style.display = 'block'; errEl.textContent = _h('436f6d706c65746520616c6c207368697070696e67206669656c6473'); }
        return;
    }
    if (lbl) lbl.textContent = _h('50524f43455353494e472e2e2e');
    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: parseInt(i.id,10), qty: parseInt(i.qty||i.q,10)||1, variant_id: parseInt(i.vid||i.variantId||0,10) }; })),
        name: name.trim(), email: email.trim(), phone: phone.trim(),
        address: fullAddr.trim(), city: city.trim(), province: prov, postal: post.trim(),
        shipping_method: shipType, shipping_cost: shipCost,
        use_credit: useCredit && useCredit.checked ? '1' : '0',
        _csrf: (document.querySelector('meta[name="csrf-token"]') || {}).content || ''
    };
    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 || name;
        var billing = { name: cardName.trim() };
        if (document.getElementById('pay-diff-billing') && document.getElementById('pay-diff-billing').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 || post,
                country: 'CA'
            };
        } else {
            billing.address = { line1: fullAddr, city: city.trim(), state: prov, postal_code: post.trim(), country: 'CA' };
        }
        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 = _h('434f4e4649524d204f52444552');
            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) {
            if (data.client_secret && activeTab === 'credit') {
                var r = await stripe.confirmCardPayment(data.client_secret, {
                    payment_method: { card: cardNum, billing_details: { name: cardName || name } }
                });
                if (r.error) {
                    if (errEl) { errEl.style.display = 'block'; errEl.textContent = r.error.message; }
                    if (lbl) lbl.textContent = _h('434f4e4649524d204f52444552');
                    btn.disabled = false;
                    return;
                }
                var fPayload = {
                    route: 'order.finalize',
                    oid: data.order_id,
                    cs: r.paymentIntent.id,
                    _csrf: (document.querySelector('meta[name="csrf-token"]') || {}).content || ''
                };
                var f = await fetch('api/index.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(fPayload),
                    credentials: 'same-origin'
                });
                var fd = await f.json().catch(function(){ return {}; });
                if (fd.ok && fd.r) { _saveCart([]); if (window._ce) window._ce.clear(); window.location.href = fd.r; return; }
            }
            _saveCart([]);
            if (window._ce) window._ce.clear();
            window.location.href = data.redirect || ('?v=tracking&ref=' + (data.order_ref || ''));
            return;
        }
        if (errEl) { errEl.style.display = 'block'; errEl.textContent = data.error || _h('4f72646572206661696c6564'); }
    } catch(e) {
        if (errEl) { errEl.style.display = 'block'; errEl.textContent = _h('436f6e6e656374696f6e206572726f72'); }
    }
    if (lbl) lbl.textContent = _h('434f4e4649524d204f52444552');
    btn.disabled = false;
});
var excludeBtn = document.getElementById('pay-exclude-btn');
if (excludeBtn) excludeBtn.addEventListener('click', function(){
    var dur = (document.getElementById('pay-exclude-duration') || {}).value || '24h';
    if (!confirm(_h('41726520796f75207375726520796f752077616e7420746f2074616b65206120627265616b2066726f6d2070757263686173696e673f'))) return;
    fetch('api/index.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            route: 'security.self_exclude',
            duration: dur,
            reason: 'User opted out during checkout',
            _csrf: (document.querySelector('meta[name="csrf-token"]') || {}).content || ''
        }),
        credentials: 'same-origin'
    })
        .then(function(r){ return r.json(); })
        .then(function(d){
            if (d.ok) {
                _ceToast(d.message || _h('53656c662d6578636c7573696f6e20616374697661746564'));
                setTimeout(function(){ window.location.href = '?v=home'; }, 1500);
            } else {
                if (errEl) { errEl.style.display = 'block'; errEl.textContent = d.error || _h('4661696c6564'); }
            }
        })
        .catch(function(){ if (errEl) { errEl.style.display = 'block'; errEl.textContent = _h('436f6e6e656374696f6e206572726f72'); } });
});
document.addEventListener('click', function(e){
    if (!e.target.closest('#self-exclude-link')) return;
    e.preventDefault();
    if (!confirm(_h('576f756c6420796f75206c696b6520746f2074616b65206120627265616b2066726f6d2070757263686173696e673f20596f752063616e20726573756d6520616e7974696d6520627920636f6e74616374696e6720737570706f72742e'))) return;
    fetch('api/index.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            route: 'security.self_exclude',
            duration: '24h',
            reason: 'User opted out from product page',
            _csrf: (document.querySelector('meta[name="csrf-token"]') || {}).content || ''
        }),
        credentials: 'same-origin'
    })
        .then(function(r){ return r.json(); })
        .then(function(d){
            if (d.ok) { _ceToast(d.message || _h('427265616b20616374697661746564')); setTimeout(function(){ window.location.href = '?v=home'; }, 1500); }
        })
        .catch(function(){});
});
})();
