(function () {
    'use strict';

    var root = document.querySelector('[data-equipment-root]');
    if (!root) return;

    var api = root.getAttribute('data-equipment-api') || '';
    var refreshButton = root.querySelector('[data-equipment-refresh]');
    var message = root.querySelector('[data-equipment-message]');
    var source = root.querySelector('[data-equipment-source]');
    var online = root.getAttribute('data-equipment-online') === '1';
    var requestRunning = false;

    function setMessage(text) {
        if (!message) return;
        text = String(text || '').trim();
        message.textContent = text;
        message.classList.toggle('is-hidden', text === '');
    }

    function create(tag, className, text) {
        var el = document.createElement(tag);
        if (className) el.className = className;
        if (typeof text !== 'undefined') el.textContent = text;
        return el;
    }

    function rarityClass(item) {
        var allowed = ['normal', 'excellent', 'ancient', 'socket', 'harmony', 'empty'];
        return allowed.indexOf(item.rarity) !== -1 ? item.rarity : 'normal';
    }

    function renderSlot(button, item) {
        if (!button || !item) return;

        var slotLabel = item.slot_label || button.getAttribute('aria-label') || 'Slot';
        button.className = 'nexora-equipment-slot nexora-equipment-slot--' + item.slot + ' rarity-' + rarityClass(item) + (item.occupied ? ' is-occupied' : ' is-empty');
        button.setAttribute('aria-label', item.occupied ? (item.name || slotLabel) : slotLabel + ' vacío');
        button.classList.remove('is-open');
        while (button.firstChild) button.removeChild(button.firstChild);

        button.appendChild(create('span', 'nexora-equipment-slot-label', slotLabel));
        var visual = create('span', 'nexora-equipment-slot-visual');

        if (item.occupied) {
            if (item.image) {
                var img = document.createElement('img');
                img.src = item.image;
                img.alt = item.name || slotLabel;
                img.loading = 'lazy';
                img.decoding = 'async';
                visual.appendChild(img);
            } else {
                visual.appendChild(create('span', 'nexora-equipment-item-code', item.code || '?'));
            }
        } else {
            var mark = create('span', 'nexora-equipment-empty-mark', '+');
            mark.setAttribute('aria-hidden', 'true');
            visual.appendChild(mark);
        }
        button.appendChild(visual);

        if (item.occupied) {
            var tooltip = create('span', 'nexora-equipment-tooltip');
            tooltip.setAttribute('role', 'tooltip');
            tooltip.appendChild(create('strong', 'nexora-equipment-tooltip-name', item.name || slotLabel));
            if (typeof item.level !== 'undefined' && item.level !== null) {
                tooltip.appendChild(create('span', 'nexora-equipment-tooltip-level', '+' + parseInt(item.level, 10)));
            }
            if (Array.isArray(item.details) && item.details.length) {
                var details = create('span', 'nexora-equipment-tooltip-details');
                item.details.forEach(function (detail) {
                    details.appendChild(create('span', '', detail));
                });
                tooltip.appendChild(details);
            }
            button.appendChild(tooltip);
        }
    }

    function render(data) {
        if (!data || !Array.isArray(data.items)) return;
        data.items.forEach(function (item) {
            if (!item || !item.slot) return;
            var button = root.querySelector('[data-equipment-slot="' + item.slot + '"]');
            renderSlot(button, item);
        });

        if (source && data.source_label) {
            var suffix = '';
            if (data.updated_at) {
                var when = new Date(data.updated_at);
                if (!isNaN(when.getTime())) suffix = ' · ' + when.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
            }
            source.textContent = data.source_label + suffix;
        }

        setMessage(data.warning || '');
    }

    function refresh(silent) {
        if (!api || requestRunning) return;
        requestRunning = true;
        var original = refreshButton ? refreshButton.textContent : '';
        if (refreshButton) {
            refreshButton.disabled = true;
            if (!silent) refreshButton.textContent = 'Actualizando...';
        }

        fetch(api, {
            method: 'GET',
            credentials: 'same-origin',
            cache: 'no-store',
            headers: {'Accept': 'application/json'}
        })
        .then(function (response) {
            return response.json().then(function (data) {
                if (!response.ok || !data || data.ok !== true) {
                    throw new Error(data && data.error ? data.error : 'No se pudo actualizar el equipamiento.');
                }
                return data;
            });
        })
        .then(render)
        .catch(function (error) {
            if (!silent) setMessage(error && error.message ? error.message : 'No se pudo actualizar el equipamiento.');
        })
        .finally(function () {
            requestRunning = false;
            if (refreshButton) {
                refreshButton.disabled = false;
                refreshButton.textContent = original || 'Actualizar equipo';
            }
        });
    }

    if (refreshButton) {
        refreshButton.addEventListener('click', function () { refresh(false); });
    }

    // Touch/keyboard tooltip support. Desktop continues to use CSS hover/focus.
    root.addEventListener('click', function (event) {
        var slot = event.target.closest ? event.target.closest('.nexora-equipment-slot.is-occupied') : null;
        if (!slot || !root.contains(slot)) return;
        root.querySelectorAll('.nexora-equipment-slot.is-open').forEach(function (other) {
            if (other !== slot) other.classList.remove('is-open');
        });
        slot.classList.toggle('is-open');
    });

    document.addEventListener('click', function (event) {
        if (root.contains(event.target)) return;
        root.querySelectorAll('.nexora-equipment-slot.is-open').forEach(function (slot) {
            slot.classList.remove('is-open');
        });
    });

    // Poll only on an online character profile, only while the tab is visible.
    if (online) {
        window.setInterval(function () {
            if (document.visibilityState === 'visible') refresh(true);
        }, 30000);
    }
})();
