<?php
use Plugin\ItemShop\ItemShop;

function itemshopEsc($value) { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }

function itemshopRenderImageUrl($item, $fallback) {
    if(!empty($item['image_file'])) return $fallback;
    $section = isset($item['item_section']) ? (int)$item['item_section'] : -1;
    $index = isset($item['item_index']) ? (int)$item['item_index'] : -1;
    if($section < 0 || $section > 15 || $index < 0 || $index > 511) return $fallback;
    $relative = 'img/itemshop-renders-v1/'.$section.'/'.$index.'.webp';
    if(defined('__PATH_TEMPLATE_ROOT__') && is_file(__PATH_TEMPLATE_ROOT__.$relative)) {
        return __PATH_TEMPLATE_IMG__.'itemshop-renders-v1/'.$section.'/'.$index.'.webp';
    }
    return $fallback;
}

function itemshopDisplayCategory($item) {
    $section = isset($item['item_section']) ? (int)$item['item_section'] : -1;
    $raw = trim((string)($item['category'] ?? ''));
    $rawKey = function_exists('mb_strtolower') ? mb_strtolower($raw, 'UTF-8') : strtolower($raw);
    $generic = in_array($rawKey, array('', 'general', 'destacado', 'destacados', 'seleccion', 'selección', 'featured'), true);

    if(!$generic) {
        if($rawKey === 'equipamiento') return 'Sets';
        if($rawKey === 'alas y orbes') return 'Alas';
        return $raw;
    }

    if($section >= 0 && $section <= 5) return 'Armas';
    if($section >= 6 && $section <= 11) return 'Sets';
    if($section === 12) return 'Alas';
    if($section === 13) {
        $name = function_exists('mb_strtolower') ? mb_strtolower((string)($item['name'] ?? ''), 'UTF-8') : strtolower((string)($item['name'] ?? ''));
        foreach(array('pet','fenrir','horse','caballo','uniria','dinorant','panda','demon','guardian angel','imp','kairuku','mount') as $needle) {
            if(strpos($name, $needle) !== false) return 'Pets';
        }
        return 'Accesorios';
    }
    if($section === 14) return 'Consumibles';
    return 'Especiales';
}

function itemshopCategoryGlyph($category) {
    $key = function_exists('mb_strtolower') ? mb_strtolower((string)$category, 'UTF-8') : strtolower((string)$category);
    if(strpos($key, 'arma') !== false) return '†';
    if(strpos($key, 'set') !== false || strpos($key, 'equip') !== false) return '▣';
    if(strpos($key, 'ala') !== false) return '◇';
    if(strpos($key, 'pet') !== false) return '◉';
    if(strpos($key, 'acces') !== false) return '◌';
    if(strpos($key, 'consum') !== false) return '△';
    if(strpos($key, 'especial') !== false) return '◆';
    return '•';
}

function itemshopBitCount($value) {
    $value = (int)$value & 0x3F;
    $count = 0;
    while($value > 0) { $count += ($value & 1); $value >>= 1; }
    return $count;
}

function itemshopTraits($item) {
    $traits = array();
    $level = (int)($item['item_level'] ?? 0);
    if($level > 0) $traits[] = '+'.$level;
    if(!empty($item['has_skill'])) $traits[] = 'Skill';
    if(!empty($item['has_luck'])) $traits[] = 'Luck';
    $excellent = itemshopBitCount((int)($item['excellent_mask'] ?? 0));
    if($excellent > 0) $traits[] = $excellent > 1 ? 'Excellent ×'.$excellent : 'Excellent';
    if((int)($item['ancient_option'] ?? 0) > 0) $traits[] = 'Ancient';
    if((int)($item['harmony_option'] ?? 0) > 0) $traits[] = 'Harmony';
    $sockets = (int)($item['socket_count'] ?? 0);
    if($sockets > 0) $traits[] = $sockets.' Socket'.($sockets === 1 ? '' : 's');
    if(!empty($item['option_380'])) $traits[] = '380';
    if(count($traits) < 1) $traits[] = 'Configuración base';
    return $traits;
}

function itemshopPrimaryProfile($item) {
    if((int)($item['ancient_option'] ?? 0) > 0) return 'ancient';
    if((int)($item['socket_count'] ?? 0) > 0) return 'socket';
    if((int)($item['harmony_option'] ?? 0) > 0) return 'harmony';
    if((int)($item['excellent_mask'] ?? 0) > 0) return 'excellent';
    if(!empty($item['option_380'])) return 'special';
    return 'normal';
}

function itemshopProfileLabel($profile) {
    $labels = array(
        'normal'=>'Base',
        'excellent'=>'Excellent',
        'ancient'=>'Ancient',
        'socket'=>'Socket',
        'harmony'=>'Harmony',
        'special'=>'Especial',
    );
    return isset($labels[$profile]) ? $labels[$profile] : 'Base';
}

function itemshopStockMeta($item) {
    $stock = (int)($item['stock'] ?? 0);
    if($stock < 0) return array('label'=>'Disponibilidad abierta','state'=>'open','short'=>'Abierta');
    if($stock <= 3) return array('label'=>'Últimas '.$stock.' unidades','state'=>'low','short'=>$stock.' restantes');
    return array('label'=>$stock.' unidades disponibles','state'=>'stock','short'=>$stock.' en stock');
}

try {
    $shop = new ItemShop();

    if(($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && isset($_POST['itemshop_purchase'])) {
        try {
            if(!isLoggedIn()) throw new RuntimeException('Inicia sesión para comprar.');
            $itemId = isset($_POST['item_id']) ? (int)$_POST['item_id'] : 0;
            $token = isset($_POST['purchase_token']) ? (string)$_POST['purchase_token'] : '';
            if(!ItemShop::consumePurchaseToken($itemId, $token)) throw new RuntimeException('La solicitud de compra expiró. Recarga el Arsenal e inténtalo nuevamente.');
            $result = $shop->purchase($itemId, $_SESSION['userid'], $_SESSION['username']);
            $_SESSION['itemshop_flash'] = array(
                'type' => 'success',
                'text' => lang('itemshop_success', true).' Saldo restante: '.number_format((int)$result['balance']).' '.$shop->currencyLabel().'.',
            );
        } catch(Throwable $purchaseError) {
            $_SESSION['itemshop_flash'] = array('type' => 'error', 'text' => $purchaseError->getMessage());
        }
        header('Location: '.__ITEMSHOP_HOME__);
        exit;
    }

    if(!empty($_SESSION['itemshop_flash']) && is_array($_SESSION['itemshop_flash'])) {
        $flash = $_SESSION['itemshop_flash'];
        unset($_SESSION['itemshop_flash']);
        message($flash['type'], itemshopEsc($flash['text']));
    }

    $settings = $shop->settings();
    $items = $shop->getCatalog();
    $balance = isLoggedIn() ? $shop->getBalance($_SESSION['username']) : null;
    $purchaseToken = (isLoggedIn() && count($items) > 0) ? ItemShop::issuePurchaseToken(0) : '';
    $realmLabel = $shop->getRealmLabel();
    $currencyLabel = $shop->currencyLabel();

    $categories = array();
    $saleCount = 0;
    $featuredCount = 0;
    foreach($items as $key=>$catalogItem) {
        $displayCategory = itemshopDisplayCategory($catalogItem);
        $items[$key]['_display_category'] = $displayCategory;
        $items[$key]['_profile'] = itemshopPrimaryProfile($catalogItem);
        $items[$key]['_traits'] = itemshopTraits($catalogItem);
        $items[$key]['_sale'] = $shop->isOnSale($catalogItem) ? 1 : 0;
        if(!isset($categories[$displayCategory])) $categories[$displayCategory] = 0;
        $categories[$displayCategory]++;
        if(!empty($items[$key]['_sale'])) $saleCount++;
        if(!empty($catalogItem['featured'])) $featuredCount++;
    }

    $orderedCategories = array();
    foreach(array('Armas','Sets','Alas','Accesorios','Pets','Consumibles','Especiales') as $categoryName) {
        if(isset($categories[$categoryName])) $orderedCategories[$categoryName] = $categories[$categoryName];
    }
    foreach($categories as $categoryName=>$categoryCount) {
        if(!isset($orderedCategories[$categoryName])) $orderedCategories[$categoryName] = $categoryCount;
    }
    $categories = $orderedCategories;

    $selectionItems = array();
    $gridItems = array();
    foreach($items as $item) {
        if(!empty($item['featured']) && count($selectionItems) < 3) $selectionItems[] = $item;
        else $gridItems[] = $item;
    }
?>
<section class="itemshop" aria-labelledby="itemshop-title" data-itemshop-root>
    <header class="itemshop-command">
        <div class="itemshop-command__identity">
            <span class="itemshop-command__sigil" aria-hidden="true">◇</span>
            <div>
                <span class="itemshop__eyebrow">ECONOMÍA NEXORA · <?php echo itemshopEsc(strtoupper($realmLabel)); ?></span>
                <h1 id="itemshop-title">ARSENAL <span>· <?php echo itemshopEsc(strtoupper($realmLabel)); ?></span></h1>
                <?php if($settings['intro'] !== '') { ?><p><?php echo itemshopEsc($settings['intro']); ?></p><?php } ?>
            </div>
        </div>

        <div class="itemshop-command__system" aria-label="Estado del Arsenal">
            <span class="itemshop-status<?php echo $shop->isEnabled() ? ' is-online' : ' is-paused'; ?>"><i aria-hidden="true"></i><?php echo $shop->isEnabled() ? 'Sistema operativo' : 'Sistema pausado'; ?></span>
            <span><b>Entrega</b> Baúl del reino</span>
            <span><b>Reino</b> <?php echo itemshopEsc($realmLabel); ?></span>
        </div>

        <?php if(isLoggedIn()) { ?>
            <div class="itemshop-wallet" aria-label="Saldo disponible">
                <div class="itemshop-wallet__label"><span>Saldo del reino</span><small><?php echo itemshopEsc($currencyLabel); ?></small></div>
                <strong><?php echo $balance === null ? '—' : number_format($balance); ?></strong>
                <span class="itemshop-wallet__realm"><?php echo itemshopEsc($realmLabel); ?> · disponible</span>
            </div>
        <?php } else { ?>
            <a class="itemshop-command__login" href="<?php echo __BASE_URL__; ?>login/"><span>Cuenta</span><strong>Iniciar sesión</strong></a>
        <?php } ?>

        <div class="itemshop-command__rule">
            <span aria-hidden="true">◆</span>
            <div><strong>Entrega protegida</strong><span><?php echo isLoggedIn() ? itemshopEsc(lang('itemshop_offline', true)) : 'Inicia sesión para consultar saldo y preparar una adquisición.'; ?></span></div>
        </div>
    </header>

    <?php if(!$shop->isEnabled()) { message('warning', 'El Arsenal está pausado temporalmente en '.itemshopEsc($realmLabel).'.'); } ?>

    <?php if(count($items) < 1) { ?>
        <div class="itemshop__empty"><?php echo itemshopEsc(lang('itemshop_empty', true)); ?></div>
    <?php } else { ?>
        <div class="itemshop-nav" data-itemshop-nav>
            <div class="itemshop-nav__categories" role="group" aria-label="Categorías del Arsenal">
                <button class="itemshop-category is-active" type="button" data-itemshop-category="*" aria-pressed="true"><span class="itemshop-category__icon" aria-hidden="true">⌁</span><span>Todo</span><b><?php echo number_format(count($items)); ?></b></button>
                <?php foreach($categories as $categoryName => $categoryCount) { ?>
                    <button class="itemshop-category" type="button" data-itemshop-category="<?php echo itemshopEsc($categoryName); ?>" aria-pressed="false"><span class="itemshop-category__icon" aria-hidden="true"><?php echo itemshopEsc(itemshopCategoryGlyph($categoryName)); ?></span><span><?php echo itemshopEsc($categoryName); ?></span><b><?php echo number_format($categoryCount); ?></b></button>
                <?php } ?>
            </div>
            <div class="itemshop-nav__controls">
                <div class="itemshop-scope" role="group" aria-label="Vista del catálogo">
                    <button class="is-active" type="button" data-itemshop-scope="all" aria-pressed="true">Catálogo</button>
                    <?php if($featuredCount > 0) { ?><button type="button" data-itemshop-scope="featured" aria-pressed="false">Selección <span><?php echo (int)$featuredCount; ?></span></button><?php } ?>
                    <?php if($saleCount > 0) { ?><button type="button" data-itemshop-scope="sale" aria-pressed="false">Ofertas <span><?php echo (int)$saleCount; ?></span></button><?php } ?>
                </div>
                <label class="itemshop-search">
                    <span class="sr-only">Buscar en Arsenal</span>
                    <span class="itemshop-search__icon" aria-hidden="true">⌕</span>
                    <input type="search" maxlength="80" autocomplete="off" placeholder="Buscar equipamiento" data-itemshop-search>
                    <kbd aria-hidden="true">/</kbd>
                </label>
                <label class="itemshop-sort">
                    <span class="sr-only">Ordenar Arsenal</span>
                    <select data-itemshop-sort>
                        <option value="curated">Orden: Arsenal</option>
                        <option value="price-asc">Precio: menor</option>
                        <option value="price-desc">Precio: mayor</option>
                        <option value="name">Nombre A–Z</option>
                        <option value="recent">Más recientes</option>
                    </select>
                </label>
                <div class="itemshop-nav__count"><strong data-itemshop-results><?php echo number_format(count($items)); ?></strong><span>piezas activas</span></div>
            </div>
        </div>

        <?php if(count($selectionItems) > 0) { ?>
        <section class="itemshop-selection" aria-labelledby="itemshop-selection-title" data-itemshop-selection-section>
            <div class="itemshop-section-head">
                <div><span>CURADURÍA DEL REINO</span><h2 id="itemshop-selection-title">Selección del Arsenal</h2></div>
                <p>Curaduría compacta de configuraciones destacadas según disponibilidad y momento del reino.</p>
            </div>
            <div class="itemshop-selection__track" data-itemshop-selection-track>
                <?php foreach($selectionItems as $selectionIndex=>$item) {
                    $sale = !empty($item['_sale']);
                    $image = itemshopRenderImageUrl($item, $shop->imageUrl($item));
                    $price = $shop->currentPrice($item);
                    $stock = itemshopStockMeta($item);
                    $canAfford = $balance === null || (int)$balance >= $price;
                    $buttonDisabled = !$shop->isEnabled() || !$canAfford;
                    $buttonText = !$shop->isEnabled() ? 'Arsenal pausado' : (!$canAfford ? 'Saldo insuficiente' : 'Revisar adquisición');
                    $remainingBalance = ($balance !== null && $canAfford) ? ((int)$balance - $price) : null;
                    $visualMode = !empty($item['image_file']) ? 'artwork' : 'render';
                    $traits = $item['_traits'];
                    $profile = $item['_profile'];
                ?>
                <article class="itemshop-feature itemshop-item--<?php echo itemshopEsc($profile); ?>" data-itemshop-card data-itemshop-feature-card
                    data-category="<?php echo itemshopEsc($item['_display_category']); ?>" data-featured="1" data-sale="<?php echo $sale ? '1' : '0'; ?>"
                    data-price="<?php echo (int)$price; ?>" data-name="<?php echo itemshopEsc($item['name']); ?>" data-id="<?php echo (int)$item['id']; ?>">
                    <div class="itemshop-feature__visual itemshop-visual--<?php echo itemshopEsc($visualMode); ?>">
                        <div class="itemshop-feature__scan" aria-hidden="true"></div>
                        <?php if($image !== '') { ?><img src="<?php echo itemshopEsc($image); ?>" alt="<?php echo itemshopEsc($item['name']); ?>" <?php echo $selectionIndex === 0 ? 'loading="eager" fetchpriority="high"' : 'loading="lazy"'; ?> decoding="async"><?php } else { ?><span class="itemshop-visual__placeholder" aria-hidden="true">◇</span><?php } ?>
                        <div class="itemshop-feature__badges">
                            <span class="itemshop-badge itemshop-badge--selection">Selección</span>
                            <span class="itemshop-badge itemshop-badge--profile"><?php echo itemshopEsc(itemshopProfileLabel($profile)); ?></span>
                            <?php if($sale) { ?><span class="itemshop-badge itemshop-badge--sale">-<?php echo (int)$shop->discountPercent($item); ?>%</span><?php } ?>
                        </div>
                    </div>
                    <div class="itemshop-feature__body">
                        <div class="itemshop-feature__meta"><span><?php echo itemshopEsc(itemshopCategoryGlyph($item['_display_category'])); ?> <?php echo itemshopEsc($item['_display_category']); ?></span><span class="itemshop-stock itemshop-stock--<?php echo itemshopEsc($stock['state']); ?>"><i></i><?php echo itemshopEsc($stock['short']); ?></span></div>
                        <h3><?php echo itemshopEsc($item['name']); ?></h3>
                        <?php if(!empty($item['description'])) { ?><p><?php echo itemshopEsc($item['description']); ?></p><?php } ?>
                        <div class="itemshop-traits" aria-label="Configuración del ítem">
                            <?php foreach(array_slice($traits,0,6) as $trait) { ?><span><?php echo itemshopEsc($trait); ?></span><?php } ?>
                        </div>
                        <div class="itemshop-feature__assurance">
                            <span aria-hidden="true">◆</span>
                            <div><strong>Configuración validada</strong><small>Entrega preparada para el baúl de <?php echo itemshopEsc($realmLabel); ?>.</small></div>
                        </div>
                        <div class="itemshop-feature__footer">
                            <div class="itemshop-price"><span>Valor del Arsenal</span><div><?php if($sale) { ?><del><?php echo number_format((int)$item['price_wc']); ?></del><?php } ?><strong><?php echo number_format($price); ?></strong><small><?php echo itemshopEsc($currencyLabel); ?></small></div></div>
                            <div class="itemshop-feature__facts">
                                <?php if(isLoggedIn()) { ?><div class="itemshop-balance-after"><span>Saldo posterior</span><strong><?php echo $remainingBalance === null ? '—' : number_format($remainingBalance); ?> <?php echo itemshopEsc($currencyLabel); ?></strong></div><?php } ?>
                                <div class="itemshop-delivery"><span>Destino</span><strong>Baúl · <?php echo itemshopEsc($realmLabel); ?></strong></div>
                            </div>
                        </div>
                        <?php if(isLoggedIn()) { ?>
                            <form method="post" action="" class="itemshop-purchase" data-itemshop-form
                                data-item-name="<?php echo itemshopEsc($item['name']); ?>"
                                data-item-category="<?php echo itemshopEsc($item['_display_category']); ?>"
                                data-item-realm="<?php echo itemshopEsc($realmLabel); ?>"
                                data-item-price="<?php echo (int)$price; ?>"
                                data-item-balance="<?php echo $balance === null ? '' : (int)$balance; ?>"
                                data-item-currency="<?php echo itemshopEsc($currencyLabel); ?>"
                                data-item-stock="<?php echo itemshopEsc($stock['label']); ?>"
                                data-item-traits="<?php echo itemshopEsc(implode(' · ', $traits)); ?>"
                                data-item-image="<?php echo itemshopEsc($image); ?>"
                                data-item-image-mode="<?php echo itemshopEsc($visualMode); ?>"
                                data-item-profile="<?php echo itemshopEsc($profile); ?>">
                                <input type="hidden" name="itemshop_purchase" value="1">
                                <input type="hidden" name="item_id" value="<?php echo (int)$item['id']; ?>">
                                <input type="hidden" name="purchase_token" value="<?php echo itemshopEsc($purchaseToken); ?>">
                                <button class="itemshop-action" type="submit"<?php echo $buttonDisabled ? ' disabled' : ''; ?>><span><?php echo itemshopEsc($buttonText); ?></span><i aria-hidden="true">→</i></button>
                            </form>
                        <?php } else { ?>
                            <a class="itemshop-action" href="<?php echo __BASE_URL__; ?>login/"><span><?php echo itemshopEsc(lang('itemshop_login', true)); ?></span><i aria-hidden="true">→</i></a>
                        <?php } ?>
                    </div>
                </article>
                <?php } ?>
            </div>
        </section>
        <?php } ?>

        <?php if(count($gridItems) > 0) { ?>
        <section class="itemshop-catalog" aria-labelledby="itemshop-catalog-title" data-itemshop-grid-section>
            <div class="itemshop-section-head itemshop-section-head--catalog">
                <div><span>DISPONIBILIDAD DEL REINO</span><h2 id="itemshop-catalog-title">Inventario del Reino</h2></div>
                <p><?php echo number_format(count($gridItems)); ?> piezas disponibles · <?php echo itemshopEsc($realmLabel); ?></p>
            </div>
            <div class="itemshop-grid" data-itemshop-grid>
            <?php foreach($gridItems as $item) {
                $sale = !empty($item['_sale']);
                $image = itemshopRenderImageUrl($item, $shop->imageUrl($item));
                $price = $shop->currentPrice($item);
                $stock = itemshopStockMeta($item);
                $canAfford = $balance === null || (int)$balance >= $price;
                $buttonDisabled = !$shop->isEnabled() || !$canAfford;
                $buttonText = !$shop->isEnabled() ? 'Arsenal pausado' : (!$canAfford ? 'Saldo insuficiente' : 'Revisar adquisición');
                $visualMode = !empty($item['image_file']) ? 'artwork' : 'render';
                $traits = $item['_traits'];
                $profile = $item['_profile'];
            ?>
                <article class="itemshop-card itemshop-item--<?php echo itemshopEsc($profile); ?><?php echo !empty($item['featured']) ? ' itemshop-card--featured' : ''; ?>" data-itemshop-card data-itemshop-grid-card
                    data-category="<?php echo itemshopEsc($item['_display_category']); ?>" data-featured="<?php echo !empty($item['featured']) ? '1' : '0'; ?>" data-sale="<?php echo $sale ? '1' : '0'; ?>"
                    data-price="<?php echo (int)$price; ?>" data-name="<?php echo itemshopEsc($item['name']); ?>" data-id="<?php echo (int)$item['id']; ?>">
                    <div class="itemshop-card__visual itemshop-visual--<?php echo itemshopEsc($visualMode); ?>">
                        <div class="itemshop-card__badges">
                            <?php if(!empty($item['featured'])) { ?><span class="itemshop-badge itemshop-badge--selection">Selección</span><?php } ?>
                            <span class="itemshop-badge itemshop-badge--profile"><?php echo itemshopEsc(itemshopProfileLabel($profile)); ?></span>
                            <?php if($sale) { ?><span class="itemshop-badge itemshop-badge--sale">-<?php echo (int)$shop->discountPercent($item); ?>%</span><?php } ?>
                        </div>
                        <?php if($image !== '') { ?><img src="<?php echo itemshopEsc($image); ?>" alt="<?php echo itemshopEsc($item['name']); ?>" loading="lazy" decoding="async"><?php } else { ?><span class="itemshop-visual__placeholder" aria-hidden="true">◇</span><?php } ?>
                        <div class="itemshop-card__visual-meta"><span><?php echo itemshopEsc($item['_display_category']); ?></span><span class="itemshop-stock itemshop-stock--<?php echo itemshopEsc($stock['state']); ?>"><i></i><?php echo itemshopEsc($stock['short']); ?></span></div>
                    </div>
                    <div class="itemshop-card__body">
                        <div class="itemshop-card__titleline"><span><?php echo itemshopEsc(itemshopCategoryGlyph($item['_display_category'])); ?> <?php echo itemshopEsc($item['_display_category']); ?></span><small><?php echo itemshopEsc(itemshopProfileLabel($profile)); ?></small></div>
                        <h3><?php echo itemshopEsc($item['name']); ?></h3>
                        <?php if(!empty($item['description'])) { ?><p><?php echo itemshopEsc($item['description']); ?></p><?php } ?>
                        <div class="itemshop-traits" aria-label="Configuración del ítem">
                            <?php foreach(array_slice($traits,0,5) as $trait) { ?><span><?php echo itemshopEsc($trait); ?></span><?php } ?>
                        </div>
                        <div class="itemshop-card__ledger">
                            <div class="itemshop-price"><span>Valor</span><div><?php if($sale) { ?><del><?php echo number_format((int)$item['price_wc']); ?></del><?php } ?><strong><?php echo number_format($price); ?></strong><small><?php echo itemshopEsc($currencyLabel); ?></small></div></div>
                            <div class="itemshop-delivery"><span>Entrega</span><strong>Baúl del reino</strong></div>
                        </div>
                        <?php if(isLoggedIn()) { ?>
                            <form method="post" action="" class="itemshop-purchase" data-itemshop-form
                                data-item-name="<?php echo itemshopEsc($item['name']); ?>"
                                data-item-category="<?php echo itemshopEsc($item['_display_category']); ?>"
                                data-item-realm="<?php echo itemshopEsc($realmLabel); ?>"
                                data-item-price="<?php echo (int)$price; ?>"
                                data-item-balance="<?php echo $balance === null ? '' : (int)$balance; ?>"
                                data-item-currency="<?php echo itemshopEsc($currencyLabel); ?>"
                                data-item-stock="<?php echo itemshopEsc($stock['label']); ?>"
                                data-item-traits="<?php echo itemshopEsc(implode(' · ', $traits)); ?>"
                                data-item-image="<?php echo itemshopEsc($image); ?>"
                                data-item-image-mode="<?php echo itemshopEsc($visualMode); ?>"
                                data-item-profile="<?php echo itemshopEsc($profile); ?>">
                                <input type="hidden" name="itemshop_purchase" value="1">
                                <input type="hidden" name="item_id" value="<?php echo (int)$item['id']; ?>">
                                <input type="hidden" name="purchase_token" value="<?php echo itemshopEsc($purchaseToken); ?>">
                                <button class="itemshop-action" type="submit"<?php echo $buttonDisabled ? ' disabled' : ''; ?>><span><?php echo itemshopEsc($buttonText); ?></span><i aria-hidden="true">→</i></button>
                            </form>
                        <?php } else { ?>
                            <a class="itemshop-action" href="<?php echo __BASE_URL__; ?>login/"><span><?php echo itemshopEsc(lang('itemshop_login', true)); ?></span><i aria-hidden="true">→</i></a>
                        <?php } ?>
                    </div>
                </article>
            <?php } ?>
            </div>
        </section>
        <?php } ?>

        <div class="itemshop__empty itemshop__empty--filtered" data-itemshop-empty hidden>
            <span aria-hidden="true">◇</span><strong>Sin coincidencias en esta configuración</strong><p>Ajusta categoría, vista o búsqueda para consultar otra parte del Arsenal.</p>
        </div>
    <?php } ?>

    <?php if(isLoggedIn() && count($items) > 0) { ?>
    <div class="itemshop-modal" data-itemshop-modal hidden>
        <div class="itemshop-modal__backdrop" data-itemshop-close></div>
        <section class="itemshop-modal__panel" role="dialog" aria-modal="true" aria-labelledby="itemshop-confirm-title" tabindex="-1" data-itemshop-modal-panel>
            <button class="itemshop-modal__close" type="button" aria-label="Cerrar confirmación" data-itemshop-close>×</button>
            <div class="itemshop-modal__visual" data-itemshop-modal-visual>
                <span class="itemshop-modal__visual-grid" aria-hidden="true"></span>
                <img src="" alt="" data-itemshop-modal-image hidden>
                <span class="itemshop-visual__placeholder" data-itemshop-modal-placeholder aria-hidden="true">◇</span>
                <span class="itemshop-modal__profile" data-itemshop-modal-profile>Base</span>
            </div>
            <div class="itemshop-modal__content">
                <span class="itemshop-modal__eyebrow">ORDEN DE ADQUISICIÓN · <?php echo itemshopEsc(strtoupper($realmLabel)); ?></span>
                <h2 id="itemshop-confirm-title" data-itemshop-modal-name>Ítem</h2>
                <p class="itemshop-modal__category" data-itemshop-modal-category></p>
                <div class="itemshop-modal__traits" data-itemshop-modal-traits></div>
                <div class="itemshop-modal__ledger">
                    <div><span>Reino</span><strong data-itemshop-modal-realm>—</strong></div>
                    <div><span>Valor</span><strong data-itemshop-modal-price>—</strong></div>
                    <div><span>Saldo actual</span><strong data-itemshop-modal-balance>—</strong></div>
                    <div><span>Saldo posterior</span><strong data-itemshop-modal-remaining>—</strong></div>
                    <div><span>Destino</span><strong>Baúl del reino</strong></div>
                    <div><span>Disponibilidad</span><strong data-itemshop-modal-stock>—</strong></div>
                </div>
                <div class="itemshop-modal__rule"><span aria-hidden="true">◆</span><p><strong>Entrega protegida.</strong> La cuenta debe permanecer desconectada mientras Arsenal reserva saldo, espacio y serial y actualiza el baúl.</p></div>
                <div class="itemshop-modal__actions">
                    <button class="itemshop-modal__cancel" type="button" data-itemshop-close>Volver</button>
                    <button class="itemshop-modal__confirm" type="button" data-itemshop-confirm>Confirmar entrega <span aria-hidden="true">→</span></button>
                </div>
            </div>
        </section>
    </div>
    <?php } ?>
</section>
<?php
} catch(Throwable $e) {
    message('error', itemshopEsc($e->getMessage()));
}
