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');
    });
};

// `WalletTooltips` module — exposes pin/unpin so other JS (eg. wallet-shop.js'
// BUY-flow guard portal) can hold the wallet tooltip open across user
// interactions that would otherwise dismiss it. The internals (hide
// timer, _show/_hide helpers) live inside the singleton's IIFE — only
// pin/unpin/initWalletTooltips are public.
const WalletTooltips = (function () {
    'use strict';

    let _hideTimer = null;
    let _pinned = false;
    const HIDE_DELAY_MS = 200;
    let _portal = null;
    let _miniPortal = null;

    function _hideAll() {
        if (_portal) _portal.classList.remove('active');
        if (_miniPortal) _miniPortal.classList.remove('active');
    }

    function _cancelHide() {
        if (_hideTimer) { clearTimeout(_hideTimer); _hideTimer = null; }
    }

    function _scheduleHide() {
        // Pinned (eg. guard portal open) — suppress the hide. unpin() will
        // call _scheduleHide() again to dismiss after the guard closes.
        if (_pinned) return;
        _cancelHide();
        _hideTimer = setTimeout(() => { _hideAll(); _hideTimer = null; }, HIDE_DELAY_MS);
    }

    function pin()  { _pinned = true;  _cancelHide(); }
    function unpin(){ _pinned = false; _scheduleHide(); }

function initWalletTooltips() {
    const portal = document.getElementById('id_tooltip_portal');
    if (!portal) return;
    _portal = portal;
    // Mini portal — used by shop tiles (BUY ITEM / "Already owned" pill).
    // Tokens applet tiles have no `.tt-micro` sibling so the mini stays
    // hidden on those hovers. Mirrors gameboard.html's mini portal.
    const miniPortal = document.getElementById('id_mini_tooltip_portal');
    _miniPortal = miniPortal;

    // Hover-persistence — keep the portal(s) open while the cursor moves
    // from tile → portal → mini-portal so users can click the BUY-ITEM
    // microbutton. A short hide delay covers the gap between
    // mouseleave-on-tile and mouseenter-on-portal; entering any of the
    // 3 zones cancels the hide.

    function _show(anchor, tooltipHtml, microHtml) {
        _cancelHide();
        const rect = anchor.getBoundingClientRect();
        portal.innerHTML = tooltipHtml;
        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))';

        if (miniPortal && microHtml) {
            miniPortal.innerHTML = microHtml;
            miniPortal.classList.add('active');
            // Pin mini-portal to the bottom-right of the main portal —
            // same anchor pattern as gameboard.js's gameKit tooltips.
            const mainRect = portal.getBoundingClientRect();
            miniPortal.style.left = '';
            miniPortal.style.right = Math.round(window.innerWidth - mainRect.right) + 'px';
            miniPortal.style.top = (mainRect.bottom + 4) + 'px';
        } else if (miniPortal) {
            miniPortal.classList.remove('active');
        }
    }

    function _bindHover(anchor) {
        const tooltip = anchor.querySelector('.tt');
        if (!tooltip) return;
        // `.tt-micro` is a SIBLING of `.tt` (not a child) so it lives
        // alongside the main tooltip content without nesting — keeps the
        // BUY-ITEM btn visually distinct in the mini portal.
        const micro = anchor.querySelector(':scope > .tt-micro');
        const microHtml = micro ? micro.innerHTML : null;
        anchor.addEventListener('mouseenter', () => _show(anchor, tooltip.innerHTML, microHtml));
        anchor.addEventListener('mouseleave', _scheduleHide);
    }

    document.querySelectorAll('.wallet-tokens .token, .wallet-shop .shop-tile')
        .forEach(_bindHover);

    // Re-entering either portal cancels the pending hide — keeps the
    // microbutton clickable. Leaving either restarts the hide timer.
    portal.addEventListener('mouseenter', _cancelHide);
    portal.addEventListener('mouseleave', _scheduleHide);
    if (miniPortal) {
        miniPortal.addEventListener('mouseenter', _cancelHide);
        miniPortal.addEventListener('mouseleave', _scheduleHide);
    }
}

    return { initWalletTooltips: initWalletTooltips, pin: pin, unpin: unpin };
})();

// Expose globally so wallet-shop.js can call WalletTooltips.pin/unpin
// without depending on script-load order.
window.WalletTooltips = WalletTooltips;

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