(function () {
    'use strict';

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

    var cards = Array.prototype.slice.call(root.querySelectorAll('[data-itemshop-card]'));
    var grid = root.querySelector('[data-itemshop-grid]');
    var gridCards = Array.prototype.slice.call(root.querySelectorAll('[data-itemshop-grid-card]'));
    var categoryButtons = Array.prototype.slice.call(root.querySelectorAll('[data-itemshop-category]'));
    var scopeButtons = Array.prototype.slice.call(root.querySelectorAll('[data-itemshop-scope]'));
    var search = root.querySelector('[data-itemshop-search]');
    var sort = root.querySelector('[data-itemshop-sort]');
    var results = root.querySelector('[data-itemshop-results]');
    var empty = root.querySelector('[data-itemshop-empty]');
    var selectionSection = root.querySelector('[data-itemshop-selection-section]');
    var gridSection = root.querySelector('[data-itemshop-grid-section]');
    var activeCategory = '*';
    var activeScope = 'all';
    var searchTerm = '';
    var filterTimer = null;
    var reducedMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    gridCards.forEach(function (card, index) {
        card.setAttribute('data-curated-order', String(index));
    });

    function normalize(value) {
        value = String(value || '').toLocaleLowerCase();
        if (value.normalize) value = value.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
        return value.trim();
    }

    function cardMatchesScope(card) {
        if (activeScope === 'featured') return card.getAttribute('data-featured') === '1';
        if (activeScope === 'sale') return card.getAttribute('data-sale') === '1';
        return true;
    }

    function updateSectionVisibility() {
        if (selectionSection) {
            var selectionVisible = Array.prototype.some.call(selectionSection.querySelectorAll('[data-itemshop-card]'), function (card) {
                return !card.hidden;
            });
            selectionSection.hidden = !selectionVisible;
        }
        if (gridSection) {
            var gridVisible = Array.prototype.some.call(gridSection.querySelectorAll('[data-itemshop-card]'), function (card) {
                return !card.hidden;
            });
            gridSection.hidden = !gridVisible;
        }
    }

    function applyFilters() {
        var visible = 0;
        var needle = normalize(searchTerm);

        cards.forEach(function (card) {
            var categoryMatches = activeCategory === '*' || card.getAttribute('data-category') === activeCategory;
            var scopeMatches = cardMatchesScope(card);
            var textMatches = needle === '' || normalize(card.textContent).indexOf(needle) !== -1;
            var show = categoryMatches && scopeMatches && textMatches;
            card.hidden = !show;
            if (show) visible++;
        });

        if (results) results.textContent = String(visible);
        if (empty) empty.hidden = visible !== 0;
        updateSectionVisibility();
    }

    function setPressed(buttons, selectedButton) {
        buttons.forEach(function (button) {
            var selected = button === selectedButton;
            button.classList.toggle('is-active', selected);
            button.setAttribute('aria-pressed', selected ? 'true' : 'false');
        });
    }

    categoryButtons.forEach(function (button) {
        button.addEventListener('click', function () {
            activeCategory = button.getAttribute('data-itemshop-category') || '*';
            setPressed(categoryButtons, button);
            if (typeof button.scrollIntoView === 'function') {
                button.scrollIntoView({ behavior: reducedMotion ? 'auto' : 'smooth', block: 'nearest', inline: 'center' });
            }
            applyFilters();
        });
    });

    scopeButtons.forEach(function (button) {
        button.addEventListener('click', function () {
            activeScope = button.getAttribute('data-itemshop-scope') || 'all';
            setPressed(scopeButtons, button);
            applyFilters();
        });
    });

    if (search) {
        search.addEventListener('input', function () {
            searchTerm = search.value;
            window.clearTimeout(filterTimer);
            filterTimer = window.setTimeout(applyFilters, 90);
        });

        document.addEventListener('keydown', function (event) {
            if (event.key !== '/' || event.ctrlKey || event.metaKey || event.altKey) return;
            var target = event.target;
            var tag = target && target.tagName ? target.tagName.toLowerCase() : '';
            if (tag === 'input' || tag === 'textarea' || tag === 'select' || (target && target.isContentEditable)) return;
            event.preventDefault();
            search.focus();
        });
    }

    function textValue(card, attribute) {
        return String(card.getAttribute(attribute) || '');
    }

    function numberValue(card, attribute) {
        var value = parseInt(card.getAttribute(attribute), 10);
        return isNaN(value) ? 0 : value;
    }

    function sortGrid(mode) {
        if (!grid || gridCards.length < 2) return;
        var sorted = gridCards.slice();

        sorted.sort(function (a, b) {
            if (mode === 'price-asc') return numberValue(a, 'data-price') - numberValue(b, 'data-price');
            if (mode === 'price-desc') return numberValue(b, 'data-price') - numberValue(a, 'data-price');
            if (mode === 'name') return textValue(a, 'data-name').localeCompare(textValue(b, 'data-name'), 'es', { sensitivity: 'base' });
            if (mode === 'recent') return numberValue(b, 'data-id') - numberValue(a, 'data-id');
            return numberValue(a, 'data-curated-order') - numberValue(b, 'data-curated-order');
        });

        sorted.forEach(function (card) { grid.appendChild(card); });
    }

    if (sort) {
        sort.addEventListener('change', function () {
            sortGrid(sort.value || 'curated');
        });
    }

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

    var panel = modal.querySelector('[data-itemshop-modal-panel]');
    var modalVisual = modal.querySelector('[data-itemshop-modal-visual]');
    var modalImage = modal.querySelector('[data-itemshop-modal-image]');
    var modalPlaceholder = modal.querySelector('[data-itemshop-modal-placeholder]');
    var modalProfile = modal.querySelector('[data-itemshop-modal-profile]');
    var modalName = modal.querySelector('[data-itemshop-modal-name]');
    var modalCategory = modal.querySelector('[data-itemshop-modal-category]');
    var modalTraits = modal.querySelector('[data-itemshop-modal-traits]');
    var modalRealm = modal.querySelector('[data-itemshop-modal-realm]');
    var modalPrice = modal.querySelector('[data-itemshop-modal-price]');
    var modalBalance = modal.querySelector('[data-itemshop-modal-balance]');
    var modalRemaining = modal.querySelector('[data-itemshop-modal-remaining]');
    var modalStock = modal.querySelector('[data-itemshop-modal-stock]');
    var confirmButton = modal.querySelector('[data-itemshop-confirm]');
    var closeButtons = Array.prototype.slice.call(modal.querySelectorAll('[data-itemshop-close]'));
    var currentForm = null;
    var previousFocus = null;

    var profileLabels = {
        normal: 'Base',
        excellent: 'Excellent',
        ancient: 'Ancient',
        socket: 'Socket',
        harmony: 'Harmony',
        special: 'Especial'
    };

    function number(value) {
        var parsed = parseInt(value, 10);
        return isNaN(parsed) ? null : parsed;
    }

    function money(value, currency) {
        if (value === null) return '—';
        return value.toLocaleString('es-VE') + ' ' + currency;
    }

    function resetConfirmButton() {
        if (!confirmButton) return;
        confirmButton.disabled = false;
        confirmButton.innerHTML = 'Confirmar entrega <span aria-hidden="true">→</span>';
    }

    function openModal(form) {
        currentForm = form;
        previousFocus = document.activeElement;

        var price = number(form.getAttribute('data-item-price'));
        var balance = number(form.getAttribute('data-item-balance'));
        var currency = form.getAttribute('data-item-currency') || '';
        var remaining = balance !== null && price !== null ? balance - price : null;
        var name = form.getAttribute('data-item-name') || 'Ítem';
        var image = form.getAttribute('data-item-image') || '';
        var imageMode = form.getAttribute('data-item-image-mode') || 'render';
        var profile = form.getAttribute('data-item-profile') || 'normal';

        if (modalName) modalName.textContent = name;
        if (modalCategory) modalCategory.textContent = form.getAttribute('data-item-category') || '';
        if (modalTraits) modalTraits.textContent = form.getAttribute('data-item-traits') || 'Configuración base';
        if (modalRealm) modalRealm.textContent = form.getAttribute('data-item-realm') || '—';
        if (modalPrice) modalPrice.textContent = money(price, currency);
        if (modalBalance) modalBalance.textContent = money(balance, currency);
        if (modalRemaining) modalRemaining.textContent = money(remaining, currency);
        if (modalStock) modalStock.textContent = form.getAttribute('data-item-stock') || '—';
        if (modalProfile) modalProfile.textContent = profileLabels[profile] || 'Base';
        if (panel) panel.setAttribute('data-profile', profile);

        if (modalVisual) modalVisual.classList.toggle('is-artwork', imageMode === 'artwork');
        if (modalImage && image) {
            modalImage.src = image;
            modalImage.alt = name;
            modalImage.hidden = false;
            if (modalPlaceholder) modalPlaceholder.hidden = true;
        } else {
            if (modalImage) {
                modalImage.src = '';
                modalImage.alt = '';
                modalImage.hidden = true;
            }
            if (modalPlaceholder) modalPlaceholder.hidden = false;
        }

        modal.hidden = false;
        document.documentElement.classList.add('itemshop-modal-open');
        resetConfirmButton();
        if (panel) panel.focus();
    }

    function closeModal() {
        modal.hidden = true;
        document.documentElement.classList.remove('itemshop-modal-open');
        currentForm = null;
        if (previousFocus && typeof previousFocus.focus === 'function') previousFocus.focus();
    }

    root.addEventListener('submit', function (event) {
        var form = event.target;
        if (!form || !form.matches('[data-itemshop-form]')) return;
        event.preventDefault();
        openModal(form);
    });

    closeButtons.forEach(function (button) {
        button.addEventListener('click', closeModal);
    });

    if (confirmButton) {
        confirmButton.addEventListener('click', function () {
            if (!currentForm) return;
            confirmButton.disabled = true;
            confirmButton.textContent = 'Procesando…';
            var form = currentForm;
            currentForm = null;
            form.submit();
        });
    }

    document.addEventListener('keydown', function (event) {
        if (modal.hidden) return;
        if (event.key === 'Escape') closeModal();
    });
}());
