(function () {
    var btn = document.getElementById('id_kit_btn');
    var dialog = document.getElementById('id_kit_bag_dialog');
    if (!btn || !dialog) return;

    btn.addEventListener('click', function () {
        if (dialog.hasAttribute('open')) {
            dialog.removeAttribute('open');
            btn.classList.remove('active');
            return;
        }
        fetch(btn.dataset.kitUrl, {
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
        })
            .then(function (r) { return r.text(); })
            .then(function (html) {
                dialog.innerHTML = html;
                attachCardListeners();
                btn.classList.add('active');
                dialog.setAttribute('open', '');
            })
            .catch(function () {
                btn.classList.remove('active');
            });
    });

    // Escape key
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && dialog.hasAttribute('open')) {
            dialog.removeAttribute('open');
            btn.classList.remove('active');
        }
    });

    // Click outside (but not on the rails button — let that flow through)
    document.addEventListener('click', function (e) {
        if (!dialog.hasAttribute('open')) return;
        if (dialog.contains(e.target)) return;
        if (e.target === btn || btn.contains(e.target)) return;
        if (e.target.closest('button.token-rails')) return;
        dialog.removeAttribute('open');
        btn.classList.remove('active');
    });

    // Inject token_id before token-rails form submits
    document.addEventListener('click', function (e) {
        var rails = e.target.closest('button.token-rails');
        if (!rails || !window._kitTokenId) return;
        var form = rails.closest('form');
        if (!form) return;
        var existing = form.querySelector('input[name="token_id"]');
        if (existing) existing.remove();
        var hidden = document.createElement('input');
        hidden.type = 'hidden';
        hidden.name = 'token_id';
        hidden.value = window._kitTokenId;
        form.appendChild(hidden);
        if (dialog.hasAttribute('open')) dialog.removeAttribute('open');
    });

    function attachTooltip(el) {
        el.addEventListener('mouseenter', function () {
            var tooltip = el.querySelector('.tt');
            if (!tooltip) return;
            var rect = el.getBoundingClientRect();
            tooltip.style.position = 'fixed';
            tooltip.style.bottom = (window.innerHeight - rect.top + 8) + 'px';
            tooltip.style.left = rect.left + 'px';
            tooltip.style.display = 'block';
        });
        el.addEventListener('mouseleave', function () {
            var tooltip = el.querySelector('.tt');
            if (tooltip) tooltip.style.display = '';
        });
    }

    // gameboard.js re-fetches dialog content after DON and fires this event.
    dialog.addEventListener('kit-content-refreshed', function () {
        attachCardListeners();
    });

    function attachCardListeners() {
        dialog.querySelectorAll('.token[data-token-id]').forEach(function (card) {
            card.addEventListener('click', function () {
                dialog.querySelectorAll('.token[data-token-id].selected').forEach(function (c) {
                    c.classList.remove('selected');
                });
                card.classList.add('selected');
                window._kitTokenId = card.dataset.tokenId;
                var slot = document.querySelector('.token-slot');
                if (slot) slot.classList.add('ready');
            });
            attachTooltip(card);
        });

        dialog.querySelectorAll('.kit-bag-deck').forEach(attachTooltip);
    }


}());
