(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';
            // Show first so offsetWidth/offsetHeight measure real layout,
            // then clamp both axes so the tooltip never bleeds past the
            // viewport. Same shape as sky-wheel.js + wallet.js: 1rem inset
            // margin on every edge.
            tooltip.style.display = 'block';
            var rem = parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
            var ttW = tooltip.offsetWidth;
            var ttH = tooltip.offsetHeight;

            // Horizontal clamp — left edge stays within [rem, viewport-ttW-rem].
            var minLeft = rem;
            var maxLeft = window.innerWidth - ttW - rem;
            var clampedLeft = Math.max(minLeft, Math.min(rect.left, maxLeft));
            tooltip.style.left = clampedLeft + 'px';

            // Vertical: prefer ABOVE the element; flip BELOW when the
            // tooltip is too tall to fit above (e.g. in landscape where
            // the kit bag dialog runs along the top of the right sidebar
            // + tokens row anchors near the top of the viewport).
            var spaceAbove = rect.top - rem;
            if (ttH <= spaceAbove) {
                tooltip.style.bottom = (window.innerHeight - rect.top + 8) + 'px';
                tooltip.style.top = '';
            } else {
                tooltip.style.top = (rect.bottom + 8) + 'px';
                tooltip.style.bottom = '';
            }
        });
        el.addEventListener('mouseleave', function () {
            var tooltip = el.querySelector('.tt');
            if (tooltip) {
                tooltip.style.display = '';
                // Reset positional props so the next show measures fresh.
                tooltip.style.top = '';
                tooltip.style.bottom = '';
            }
        });
    }

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


}());
