const initWallet = () => {
    let stripe, elements;

    const addBtn = document.getElementById('id_add_payment_method');
    const saveBtn = document.getElementById('id_save_payment_method');
    const cancelBtn = document.getElementById('id_cancel_payment_method');
    if (!addBtn) return;

    const getCsrf = () => document.cookie.match(/csrftoken=([^;]+)/)[1];

    addBtn.addEventListener('click', async () => {
        const res = await fetch('/dashboard/wallet/setup-intent', {
            method: 'POST',
            headers: {'X-CSRFToken': getCsrf()},
        });
        const {client_secret, publishable_key} = await res.json();
        stripe = Stripe(publishable_key);
        elements = stripe.elements({clientSecret: client_secret});
        const paymentEl = elements.create('payment');
        paymentEl.mount('#id_stripe_payment_element');
        saveBtn.hidden = false;
        cancelBtn.hidden = false;
        const section = addBtn.closest('section');
        section.style.setProperty('--applet-rows', '15');
    });

    saveBtn.addEventListener('click', async () => {
        const {error, setupIntent} = await stripe.confirmSetup({
            elements,
            redirect: 'if_required',
        });
        if (error) { console.error(error); return; }
        const res = await fetch('/dashboard/wallet/save-payment-method', {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCsrf(),
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `payment_method_id=${setupIntent.payment_method}`,
        });
        const {last4, brand} = await res.json();
        const pm = document.createElement('div');
        pm.textContent = `${brand} ····${last4}`;
        document.getElementById('id_payment_methods').appendChild(pm);
        elements.getElement('payment').unmount();
        elements = null;
        stripe = null;
        saveBtn.hidden = true;
        cancelBtn.hidden = true;
        const section = cancelBtn.closest('section');
        section.style.setProperty('--applet-rows', '3');
    });

    cancelBtn.addEventListener('click', () => {
        if (elements) {
            elements.getElement('payment').unmount();
            elements = null;
            stripe = null;
        }
        saveBtn.hidden = true;
        cancelBtn.hidden = true;
        const section = cancelBtn.closest('section');
        section.style.setProperty('--applet-rows', '3');
    });
};

function initWalletTooltips() {
    const portal = document.getElementById('id_tooltip_portal');
    if (!portal) return;

    document.querySelectorAll('.wallet-tokens .token').forEach(token => {
        const tooltip = token.querySelector('.tt');
        if (!tooltip) return;

        token.addEventListener('mouseenter', () => {
            const rect = token.getBoundingClientRect();
            portal.innerHTML = tooltip.innerHTML;
            portal.classList.add('active');
            const halfW = portal.offsetWidth / 2;
            const rawLeft = rect.left + rect.width / 2;
            const clampedLeft = Math.max(halfW + 8, Math.min(rawLeft, window.innerWidth - halfW - 8));
            portal.style.left = Math.round(clampedLeft) + 'px';
            portal.style.top = Math.round(rect.top) + 'px';
            portal.style.transform = 'translate(-50%, calc(-100% - 0.5rem))';
        });

        token.addEventListener('mouseleave', () => {
            portal.classList.remove('active');
        });
    });
}

document.addEventListener('DOMContentLoaded', initWallet);
document.addEventListener('DOMContentLoaded', initWalletTooltips);