<?php $pageTitle = htmlspecialchars($subcollection['name']) . ' - ' . Lang::get('app_name'); ?>
<?php if ($view === 'table') $fullWidth = true; ?>
<?php require APP_ROOT . '/views/layouts/header.php'; ?>

<?php if ($subcollection['type'] === 'coin'): ?>
<script src="<?= APP_URL ?>/js/coins.js"></script>
<input type="hidden" name="csrf_token" value="<?= Session::getCsrfToken() ?>">
<?php endif; ?>

<div class="mb-6">
    <!-- Top row: breadcrumb + buttons -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-2">
        <nav class="text-sm text-gray-400 dark:text-gray-500 min-w-0 overflow-hidden" aria-label="Breadcrumb">
            <ol class="flex items-center space-x-2">
                <li class="flex-shrink-0"><a href="<?= APP_URL ?>/home" class="hover:text-primary-600 dark:hover:text-primary-400 transition-colors"><?= Lang::get('home') ?></a></li>
                <li class="flex-shrink-0" aria-hidden="true">/</li>
                <li class="truncate"><a href="<?= APP_URL ?>/collections/<?= $subcollection['collection_id'] ?>" class="hover:text-primary-600 dark:hover:text-primary-400 transition-colors"><?= htmlspecialchars($subcollection['collection_name']) ?></a></li>
                <li class="flex-shrink-0" aria-hidden="true">/</li>
                <li class="text-gray-700 dark:text-gray-300 truncate" aria-current="page"><?= htmlspecialchars($subcollection['name']) ?></li>
            </ol>
        </nav>
        <div class="flex items-center gap-2 flex-shrink-0 flex-wrap">
            <a href="<?= APP_URL ?>/collections/<?= $subcollection['collection_id'] ?>"
               class="inline-flex items-center justify-center px-3 sm:px-4 h-9 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 text-sm font-medium rounded-lg transition-colors whitespace-nowrap">
                <svg class="w-4 h-4 sm:mr-2 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"/></svg>
                <span class="hidden sm:inline"><?= Lang::get('back') ?></span>
            </a>
            <div class="inline-flex items-center bg-gray-100 dark:bg-gray-700 rounded-lg h-9 p-1">
                <a href="?view=grid" class="inline-flex items-center px-2 sm:px-3 h-7 text-xs font-medium rounded-md transition-colors whitespace-nowrap <?= $view === 'grid' ? 'bg-white dark:bg-gray-600 text-gray-900 dark:text-gray-100 shadow-sm' : 'text-gray-500 dark:text-gray-400 hover:text-gray-700' ?>">
                    <svg class="w-4 h-4 sm:mr-1 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"/></svg>
                    <span class="hidden sm:inline"><?= Lang::get('grid_view') ?></span>
                </a>
                <a href="?view=table" class="inline-flex items-center px-2 sm:px-3 h-7 text-xs font-medium rounded-md transition-colors whitespace-nowrap <?= $view === 'table' ? 'bg-white dark:bg-gray-600 text-gray-900 dark:text-gray-100 shadow-sm' : 'text-gray-500 dark:text-gray-400 hover:text-gray-700' ?>">
                    <svg class="w-4 h-4 sm:mr-1 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M3 14h18m-9-4v8m-7 0h14a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
                    <span class="hidden sm:inline"><?= Lang::get('table_view') ?></span>
                </a>
            </div>
            <!-- Export dropdown -->
            <div class="relative">
                <button onclick="toggleExportDropdown()" class="inline-flex items-center justify-center px-3 sm:px-4 h-9 bg-green-600 hover:bg-green-700 text-white text-sm font-medium rounded-lg transition-colors whitespace-nowrap">
                    <svg class="w-4 h-4 sm:mr-1 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                    </svg>
                    <span class="hidden sm:inline"><?= Lang::get('export') ?></span>
                    <svg class="w-4 h-4 sm:ml-1 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                    </svg>
                </button>
                <div id="exportDropdown" class="hidden absolute right-0 mt-2 w-48 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 z-10">
                    <a href="<?= APP_URL ?>/subcollections/<?= $subcollection['id'] ?>/pdf" class="block px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-t-lg">
                        <?= Lang::get('export_pdf') ?>
                    </a>
                    <a href="<?= APP_URL ?>/subcollections/<?= $subcollection['id'] ?>/xls" class="block px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-b-lg">
                        <?= Lang::get('export_xls') ?>
                    </a>
                </div>
            </div>
            <!-- Import button -->
            <button onclick="openImportModal()" class="btn-gradient btn-gradient-blue btn-gradient-icon btn-gradient-sm">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path>
                </svg>
                <span class="hidden sm:inline"><?= Lang::get('import') ?></span>
            </button>
            <a href="<?= APP_URL ?>/subcollections/<?= $subcollection['id'] ?>/<?= $subcollection['type'] === 'coin' ? 'coins' : 'items' ?>/create?view=<?= $view ?>"
               class="btn-gradient btn-gradient-blue btn-gradient-icon btn-gradient-sm">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"/></svg>
                <span class="hidden sm:inline"><?= $subcollection['type'] === 'coin' ? Lang::get('add_coin') : Lang::get('add_item') ?></span>
            </a>
        </div>
    </div>
    <!-- Title + description below -->
    <h1 class="text-xl sm:text-2xl font-bold"><?= htmlspecialchars($subcollection['name']) ?></h1>
    <?php if (!empty($subcollection['description'])): ?>
        <?php $desc = htmlspecialchars($subcollection['description']); $isLong = mb_strlen($subcollection['description']) > 160; ?>
        <div class="text-gray-500 dark:text-gray-400 text-sm mt-1 max-w-3xl">
            <span class="desc-short"><?= $isLong ? mb_substr($desc, 0, 160) . '...' : $desc ?></span>
            <?php if ($isLong): ?>
                <span class="desc-full hidden"><?= $desc ?></span>
                <button type="button" onclick="toggleDesc(this)" class="text-primary-600 dark:text-primary-400 hover:underline text-xs font-medium ml-1"><?= Lang::get('show_more') ?></button>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<?php if (empty($items)): ?>
    <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-12 text-center">
        <svg class="w-16 h-16 mx-auto text-gray-400 dark:text-gray-500 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4"/>
        </svg>
        <p class="text-gray-500 dark:text-gray-400 text-lg"><?= Lang::get('no_items') ?></p>
    </div>

<?php elseif ($view === 'grid'): ?>
    <!-- Grid View -->
    <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
        <?php $isCoin = $subcollection['type'] === 'coin'; ?>
        <?php foreach ($items as $item): ?>
            <?php
                $variants = $itemVariants[$item['id']] ?? [];
                $extraImages = $itemImages[$item['id']] ?? [];
                $hasOwned = false;
                foreach ($variants as $v) { if ($v['owned']) { $hasOwned = true; break; } }
            ?>
            <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden hover:shadow-lg transition-shadow duration-200 h-full">
                <div class="flex h-full">
                    <div class="w-2 flex-shrink-0 <?= $hasOwned ? 'bg-green-500' : 'bg-red-500' ?>"></div>
                    <div class="flex-1 p-4">
                        <!-- Images -->
                        <div class="<?= $isCoin ? 'h-52' : 'h-32' ?>"> <!-- Adjusted height for coin images -->
                            <div class="flex space-x-3 mb-1">
                                <?php $gridImgIdx = 0; ?>
                                <?php if ($item['image_obverse']): ?>
                                    <div class="flex-1">
                                        <p class="text-xs text-gray-400 dark:text-gray-500 mb-1"><?= Lang::get('obverse') ?></p>
                                        <div class="<?= $isCoin ? 'w-40 h-40 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center' : 'w-full h-20 bg-gray-100 dark:bg-gray-700 flex items-center justify-center' ?> rounded-lg">
                                            <img src="<?= APP_URL ?>/uploads/items/thumbs/<?= htmlspecialchars(pathinfo($item['image_obverse'], PATHINFO_FILENAME)) ?>_thumb.<?= htmlspecialchars(pathinfo($item['image_obverse'], PATHINFO_EXTENSION)) ?>" alt="<?= Lang::get('obverse') ?>" class="<?= $isCoin ? 'w-40 h-40 object-cover rounded-full' : 'max-w-full max-h-full object-contain' ?> cursor-zoom-in" tabindex="0" role="button" onclick="openGallery(<?= $item['id'] ?>, <?= $gridImgIdx ?>)" onkeydown="if(event.key==='Enter')openGallery(<?= $item['id'] ?>, <?= $gridImgIdx ?>)">
                                        </div>
                                    </div>
                                <?php else: ?>
                                    <div class="flex-1">
                                        <p class="text-xs text-gray-400 dark:text-gray-500 mb-1"><?= Lang::get('obverse') ?></p>
                                        <div class="<?= $isCoin ? 'w-40 h-40 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center' : 'w-full h-20 bg-gray-100 dark:bg-gray-700 flex items-center justify-center' ?> rounded-lg">
                                            <img src="<?= APP_URL ?>/images/<?= $isCoin ? 'placeholder-coin.svg' : 'placeholder-banknote.svg' ?>" alt="<?= Lang::get('obverse') ?>" class="<?= $isCoin ? 'w-32 h-32 object-contain' : 'max-w-full max-h-full object-contain' ?> opacity-50">
                                        </div>
                                    </div>
                                <?php $gridImgIdx++; endif; ?>
                                <?php if ($item['image_reverse']): ?>
                                    <div class="flex-1">
                                        <p class="text-xs text-gray-400 dark:text-gray-500 mb-1"><?= Lang::get('reverse') ?></p>
                                        <div class="<?= $isCoin ? 'w-40 h-40 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center' : 'w-full h-20 bg-gray-100 dark:bg-gray-700 flex items-center justify-center' ?> rounded-lg">
                                            <img src="<?= APP_URL ?>/uploads/items/thumbs/<?= htmlspecialchars(pathinfo($item['image_reverse'], PATHINFO_FILENAME)) ?>_thumb.<?= htmlspecialchars(pathinfo($item['image_reverse'], PATHINFO_EXTENSION)) ?>" alt="<?= Lang::get('reverse') ?>" class="<?= $isCoin ? 'w-40 h-40 object-cover rounded-full' : 'max-w-full max-h-full object-contain' ?> cursor-zoom-in" tabindex="0" role="button" onclick="openGallery(<?= $item['id'] ?>, <?= $gridImgIdx ?>)" onkeydown="if(event.key==='Enter')openGallery(<?= $item['id'] ?>, <?= $gridImgIdx ?>)">
                                        </div>
                                    </div>
                                <?php else: ?>
                                    <div class="flex-1">
                                        <p class="text-xs text-gray-400 dark:text-gray-500 mb-1"><?= Lang::get('reverse') ?></p>
                                        <div class="<?= $isCoin ? 'w-40 h-40 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center' : 'w-full h-20 bg-gray-100 dark:bg-gray-700 flex items-center justify-center' ?> rounded-lg">
                                            <img src="<?= APP_URL ?>/images/<?= $isCoin ? 'placeholder-coin.svg' : 'placeholder-banknote.svg' ?>" alt="<?= Lang::get('reverse') ?>" class="<?= $isCoin ? 'w-32 h-32 object-contain' : 'max-w-full max-h-full object-contain' ?> opacity-50">
                                        </div>
                                    </div>
                                <?php $gridImgIdx++; endif; ?>
                            </div>
                            <?php if (!empty($extraImages)): ?>
                            <div class="flex items-center gap-1 text-xs text-gray-400 dark:text-gray-500">
                                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                                +<?= count($extraImages) ?> <?= Lang::get('more_images') ?>
                            </div>
                            <?php endif; ?>
                        </div>

                        <!-- Details -->
                        <div class="space-y-1 text-sm">
                            <?php if ($item['country']): ?>
                                <div class="flex justify-between"><span class="text-gray-500 dark:text-gray-400"><?= Lang::get('country') ?>:</span> <span class="font-medium"><?= htmlspecialchars($item['country']) ?></span></div>
                            <?php endif; ?>
                            <?php if ($item['nominal_value']): ?>
                                <div class="flex justify-between"><span class="text-gray-500 dark:text-gray-400"><?= Lang::get('nominal_value') ?>:</span> <span class="font-medium"><?= htmlspecialchars($item['nominal_value']) ?></span></div>
                            <?php endif; ?>
                            <?php if ($subcollection['type'] === 'coin'): ?>
                                <?php if ($item['year_minted']): ?>
                                    <div class="flex justify-between"><span class="text-gray-500 dark:text-gray-400"><?= Lang::get('year_minted') ?>:</span> <span class="font-medium"><?= htmlspecialchars($item['year_minted']) ?></span></div>
                                <?php endif; ?>
                                <?php if ($item['material']): ?>
                                    <div class="flex justify-between"><span class="text-gray-500 dark:text-gray-400"><?= Lang::get('material') ?>:</span> <span class="font-medium"><?= Lang::get('material_' . $item['material']) ?></span></div>
                                <?php endif; ?>
                                <?php if ($item['weight']): ?>
                                    <div class="flex justify-between"><span class="text-gray-500 dark:text-gray-400"><?= Lang::get('weight') ?>:</span> <span class="font-medium"><?= htmlspecialchars($item['weight']) ?>g</span></div>
                                <?php endif; ?>
                                <?php if ($item['diameter']): ?>
                                    <div class="flex justify-between"><span class="text-gray-500 dark:text-gray-400"><?= Lang::get('diameter') ?>:</span> <span class="font-medium"><?= htmlspecialchars($item['diameter']) ?>mm</span></div>
                                <?php endif; ?>
                                <?php if ($item['mintage']): ?>
                                    <div class="flex justify-between"><span class="text-gray-500 dark:text-gray-400"><?= Lang::get('mintage') ?>:</span> <span class="font-medium"><?= number_format($item['mintage']) ?></span></div>
                                <?php endif; ?>
                            <?php else: ?>
                                <?php if ($item['issue_date']): ?>
                                    <div class="flex justify-between"><span class="text-gray-500 dark:text-gray-400"><?= Lang::get('issue_date') ?>:</span> <span class="font-medium"><?= htmlspecialchars($item['issue_date']) ?></span></div>
                                <?php endif; ?>
                                <?php if ($item['dimensions']): ?>
                                    <div class="flex justify-between"><span class="text-gray-500 dark:text-gray-400"><?= Lang::get('dimensions') ?>:</span> <span class="font-medium"><?= htmlspecialchars($item['dimensions']) ?></span></div>
                                <?php endif; ?>
                                <?php if ($item['additional_info']): ?>
                                    <div class="flex justify-between"><span class="text-gray-500 dark:text-gray-400"><?= Lang::get('additional_info') ?>:</span> <span class="font-medium"><?= htmlspecialchars($item['additional_info']) ?></span></div>
                                <?php endif; ?>
                            <?php endif; ?>
                            <?php if ($item['catalog_number']): ?>
                                <div class="flex justify-between"><span class="text-gray-500 dark:text-gray-400"><?= Lang::get('catalog_number') ?>:</span> <span class="font-medium"><?= htmlspecialchars($item['catalog_number']) ?></span></div>
                            <?php endif; ?>
                            <?php if ($item['purchase_price']): ?>
                                <div class="flex justify-between"><span class="text-gray-500 dark:text-gray-400"><?= Lang::get('purchase_price') ?>:</span> <span class="font-medium"><?= htmlspecialchars($item['purchase_price']) ?></span></div>
                            <?php endif; ?>
                            <?php if ($item['note']): ?>
                                <div class="mt-1"><span class="text-gray-500 dark:text-gray-400"><?= Lang::get('note') ?>:</span> <span class="text-gray-700 dark:text-gray-300"><?= htmlspecialchars($item['note']) ?></span></div>
                            <?php endif; ?>
                        </div>

                        <!-- Variants / Owned Status -->
                        <?php if ($subcollection['type'] === 'coin'): ?>
                            <!-- Coin variants -->
                            <?php if (!empty($variants)): ?>
                            <div class="mt-3 space-y-1.5">
                                <?php foreach ($variants as $v): ?>
                                <div class="flex items-center gap-2 text-xs">
                                    <button onclick="toggleCoinVariantOwned(<?= $v['id'] ?>, this)" class="w-5 h-5 rounded-full flex items-center justify-center flex-shrink-0 <?= $v['owned'] ? 'bg-green-500' : 'bg-red-500' ?>" title="<?= $v['owned'] ? Lang::get('owned_yes') : Lang::get('owned_no') ?>">
                                        <?php if ($v['owned']): ?>
                                            <svg class="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"/></svg>
                                        <?php else: ?>
                                            <svg class="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M6 18L18 6M6 6l12 12"/></svg>
                                        <?php endif; ?>
                                    </button>
                                    <span class="text-gray-700 dark:text-gray-300">
                                        <?= $v['condition_label'] ? htmlspecialchars($v['condition_label']) : '' ?>
                                        <?= $v['note'] ? ' - ' . htmlspecialchars($v['note']) : '' ?>
                                    </span>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>
                        <?php else: ?>
                            <!-- Banknote variants -->
                            <?php if (!empty($variants)): ?>
                            <div class="mt-3 space-y-1.5">
                                <?php foreach ($variants as $v): ?>
                                <div class="flex items-center gap-2 text-xs">
                                    <button onclick="toggleVariantOwned(<?= $v['id'] ?>, this)" class="w-5 h-5 rounded-full flex items-center justify-center flex-shrink-0 <?= $v['owned'] ? 'bg-green-500' : 'bg-red-500' ?>" title="<?= $v['owned'] ? Lang::get('owned_yes') : Lang::get('owned_no') ?>">
                                        <?php if ($v['owned']): ?>
                                            <svg class="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"/></svg>
                                        <?php else: ?>
                                            <svg class="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M6 18L18 6M6 6l12 12"/></svg>
                                        <?php endif; ?>
                                    </button>
                                    <span class="text-gray-700 dark:text-gray-300">
                                        <?= $v['condition_label'] ? htmlspecialchars($v['condition_label']) : '' ?>
                                        <?= $v['variant_type_label'] ? ' / ' . htmlspecialchars($v['variant_type_label']) : '' ?>
                                        <?= $v['note'] ? ' - ' . htmlspecialchars($v['note']) : '' ?>
                                    </span>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>
                        <?php endif; ?>

                        <!-- Actions -->
                        <div class="flex items-center justify-end mt-4 pt-3 border-t border-gray-100 dark:border-gray-700">
                            <div class="flex space-x-2">
                                <button type="button" onclick="toggleWishlistQuick('<?= $subcollection['type'] === 'coin' ? 'coin' : 'item' ?>', <?= $item['id'] ?>, this)" class="text-gray-400 hover:text-green-600 dark:hover:text-green-400 transition-colors" title="Toggle Wishlist">
                                    <svg class="wishlist-heart w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
                                    </svg>
                                </button>
                                <button type="button" onclick="moveItem(<?= $item['id'] ?>, 'up', this)" class="text-gray-400 hover:text-green-600 dark:hover:text-green-400 transition-colors" title="<?= Lang::get('move_up') ?>">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7"/></svg>
                                </button>
                                <button type="button" onclick="moveItem(<?= $item['id'] ?>, 'down', this)" class="text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors" title="<?= Lang::get('move_down') ?>">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
                                </button>
                                <button type="button" onclick="duplicateItem(<?= $item['id'] ?>, '<?= $subcollection['type'] === 'coin' ? 'coins' : 'items' ?>', this)" class="text-gray-400 hover:text-purple-600 dark:hover:text-purple-400 transition-colors" title="<?= Lang::get('duplicate') ?>">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
                                </button>
                                <a href="<?= APP_URL ?>/<?= $subcollection['type'] === 'coin' ? 'coins' : 'items' ?>/<?= $item['id'] ?>/edit?view=<?= $view ?>" class="text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 transition-colors" title="<?= Lang::get('edit') ?>">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                                </a>
                                <a href="javascript:void(0)" onclick="confirmDelete('<?= Lang::get('confirm_delete') ?>', function(){ window.location.href='<?= APP_URL ?>/<?= $subcollection['type'] === 'coin' ? 'coins' : 'items' ?>/<?= $item['id'] ?>/delete'; })" class="text-gray-400 hover:text-red-600 dark:hover:text-red-400 transition-colors" title="<?= Lang::get('delete') ?>">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

<?php else: ?>
    <!-- Table View -->
    <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <?php if ($subcollection['type'] === 'coin'): ?>
                <thead>
                    <tr class="bg-gray-50 dark:bg-gray-750 border-b border-gray-200 dark:border-gray-700">
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400 w-20"><?= Lang::get('obverse') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400 w-20"><?= Lang::get('reverse') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('country') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('nominal_value') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('year_minted') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('material') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('weight') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('diameter') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('mintage') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('catalog_number') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('owned') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('actions') ?></th>
                    </tr>
                </thead>
            <?php else: ?>
                <thead>
                    <tr class="bg-gray-50 dark:bg-gray-750 border-b border-gray-200 dark:border-gray-700">
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400 w-20"><?= Lang::get('obverse') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400 w-20"><?= Lang::get('reverse') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('country') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('nominal_value') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('issue_date') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('catalog_number') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('dimensions') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('color') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('description_obverse') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('description_reverse') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('additional_info') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('variants') ?></th>
                        <th class="px-3 py-3 text-left font-medium text-gray-500 dark:text-gray-400"><?= Lang::get('actions') ?></th>
                    </tr>
                </thead>
            <?php endif; ?>
                <tbody class="divide-y divide-gray-100 dark:divide-gray-700">
                    <?php foreach ($items as $item): ?>
                        <?php $variants = $itemVariants[$item['id']] ?? []; ?>
                        <tr class="hover:bg-gray-50 dark:hover:bg-gray-750 transition-colors">
                            <td class="px-3 py-3 w-28">
                                <?php if ($item['image_obverse']): ?>
                                    <div class="<?= $isCoin ? 'w-24 h-24 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center' : 'w-24 h-16 bg-gray-100 dark:bg-gray-700 flex items-center justify-center' ?> rounded">
                                        <img src="<?= APP_URL ?>/uploads/items/thumbs/<?= htmlspecialchars(pathinfo($item['image_obverse'], PATHINFO_FILENAME)) ?>_thumb.<?= htmlspecialchars(pathinfo($item['image_obverse'], PATHINFO_EXTENSION)) ?>" alt="<?= Lang::get('obverse') ?>" class="<?= $isCoin ? 'w-24 h-24 object-cover rounded-full' : 'max-w-full max-h-full object-contain' ?> cursor-zoom-in" onclick="openGallery(<?= $item['id'] ?>, 0)">
                                    </div>
                                <?php else: ?>
                                    <div class="<?= $isCoin ? 'w-24 h-24 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center' : 'w-24 h-16 bg-gray-100 dark:bg-gray-700 flex items-center justify-center' ?> rounded">
                                        <img src="<?= APP_URL ?>/images/<?= $isCoin ? 'placeholder-coin.svg' : 'placeholder-banknote.svg' ?>" alt="<?= Lang::get('obverse') ?>" class="<?= $isCoin ? 'w-20 h-20 object-contain' : 'max-w-full max-h-full object-contain' ?> opacity-50">
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td class="px-3 py-3 w-28">
                                <?php if ($item['image_reverse']): ?>
                                    <div class="<?= $isCoin ? 'w-24 h-24 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center' : 'w-24 h-16 bg-gray-100 dark:bg-gray-700 flex items-center justify-center' ?> rounded">
                                        <img src="<?= APP_URL ?>/uploads/items/thumbs/<?= htmlspecialchars(pathinfo($item['image_reverse'], PATHINFO_FILENAME)) ?>_thumb.<?= htmlspecialchars(pathinfo($item['image_reverse'], PATHINFO_EXTENSION)) ?>" alt="<?= Lang::get('reverse') ?>" class="<?= $isCoin ? 'w-24 h-24 object-cover rounded-full' : 'max-w-full max-h-full object-contain' ?> cursor-zoom-in" onclick="openGallery(<?= $item['id'] ?>, <?= $item['image_obverse'] ? 1 : 0 ?>)">
                                    </div>
                                <?php else: ?>
                                    <div class="<?= $isCoin ? 'w-24 h-24 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center' : 'w-24 h-16 bg-gray-100 dark:bg-gray-700 flex items-center justify-center' ?> rounded">
                                        <img src="<?= APP_URL ?>/images/<?= $isCoin ? 'placeholder-coin.svg' : 'placeholder-banknote.svg' ?>" alt="<?= Lang::get('reverse') ?>" class="<?= $isCoin ? 'w-20 h-20 object-contain' : 'max-w-full max-h-full object-contain' ?> opacity-50">
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td class="px-3 py-3"><?= htmlspecialchars($item['country'] ?? '-') ?></td>
                            <td class="px-3 py-3 font-medium"><?= htmlspecialchars($item['nominal_value'] ?? '-') ?></td>
                            <?php if ($subcollection['type'] === 'coin'): ?>
                            <td class="px-3 py-3"><?= htmlspecialchars($item['year_minted'] ?? '-') ?></td>
                            <td class="px-3 py-3"><?= htmlspecialchars($item['material'] ? Lang::get('material_' . $item['material']) : '-') ?></td>
                            <td class="px-3 py-3"><?= htmlspecialchars($item['weight'] ?? '-') ? htmlspecialchars($item['weight']) . 'g' : '-' ?></td>
                            <td class="px-3 py-3"><?= htmlspecialchars($item['diameter'] ?? '-') ? htmlspecialchars($item['diameter']) . 'mm' : '-' ?></td>
                            <td class="px-3 py-3"><?= htmlspecialchars($item['mintage'] ?? '-') ? number_format($item['mintage']) : '-' ?></td>
                            <td class="px-3 py-3"><?= htmlspecialchars($item['catalog_number'] ?? '-') ?></td>
                            <td class="px-3 py-3">
                                <?php if (!empty($variants)): ?>
                                    <div class="space-y-1">
                                        <?php foreach ($variants as $v): ?>
                                            <div class="flex items-center gap-2 text-xs">
                                                <div class="w-4 h-4 rounded-full flex items-center justify-center flex-shrink-0 <?= $v['owned'] ? 'bg-green-500' : 'bg-red-500' ?>" title="<?= $v['owned'] ? Lang::get('owned_yes') : Lang::get('owned_no') ?>">
                                                    <?php if ($v['owned']): ?>
                                                        <svg class="w-2.5 h-2.5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"/></svg>
                                                    <?php else: ?>
                                                        <svg class="w-2.5 h-2.5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M6 18L18 6M6 6l12 12"/></svg>
                                                    <?php endif; ?>
                                                </div>
                                                <span class="text-gray-700 dark:text-gray-300">
                                                    <?= $v['condition_label'] ? htmlspecialchars($v['condition_label']) : '' ?>
                                                    <?= $v['note'] ? ' - ' . htmlspecialchars($v['note']) : '' ?>
                                                </span>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                <?php else: ?>
                                    <span class="text-gray-300 dark:text-gray-600">-</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-3 py-3">
                                <div class="flex space-x-2">
                                    <button type="button" onclick="toggleWishlistQuick('<?= $subcollection['type'] === 'coin' ? 'coin' : 'item' ?>', <?= $item['id'] ?>, this)" class="text-gray-400 hover:text-green-600 dark:hover:text-green-400 transition-colors" title="Toggle Wishlist">
                                        <svg class="wishlist-heart w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
                                        </svg>
                                    </button>
                                    <button type="button" onclick="moveItem(<?= $item['id'] ?>, 'up', this)" class="text-gray-400 hover:text-green-600 dark:hover:text-green-400 transition-colors" title="<?= Lang::get('move_up') ?>">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7"/></svg>
                                    </button>
                                    <button type="button" onclick="moveItem(<?= $item['id'] ?>, 'down', this)" class="text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors" title="<?= Lang::get('move_down') ?>">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
                                    </button>
                                    <button type="button" onclick="duplicateItem(<?= $item['id'] ?>, '<?= $subcollection['type'] === 'coin' ? 'coins' : 'items' ?>', this)" class="text-gray-400 hover:text-purple-600 dark:hover:text-purple-400 transition-colors" title="<?= Lang::get('duplicate') ?>">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
                                    </button>
                                    <a href="<?= APP_URL ?>/<?= $subcollection['type'] === 'coin' ? 'coins' : 'items' ?>/<?= $item['id'] ?>/edit?view=<?= $view ?>" class="text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 transition-colors" title="<?= Lang::get('edit') ?>">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                                    </a>
                                    <a href="javascript:void(0)" onclick="confirmDelete('<?= Lang::get('confirm_delete') ?>', function(){ window.location.href='<?= APP_URL ?>/<?= $subcollection['type'] === 'coin' ? 'coins' : 'items' ?>/<?= $item['id'] ?>/delete'; })" class="text-gray-400 hover:text-red-600 dark:hover:text-red-400 transition-colors" title="<?= Lang::get('delete') ?>">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                                    </a>
                                </div>
                            </td>
                            <?php else: ?>
                            <!-- Banknote specific columns -->
                            <td class="px-3 py-3"><?= htmlspecialchars($item['issue_date'] ?? '-') ?></td>
                            <td class="px-3 py-3"><?= htmlspecialchars($item['catalog_number'] ?? '-') ?></td>
                            <td class="px-3 py-3"><?= htmlspecialchars($item['dimensions'] ?? '-') ?></td>
                            <td class="px-3 py-3"><?= htmlspecialchars($item['color'] ?? '-') ?></td>
                            <td class="px-3 py-3"><?= htmlspecialchars($item['description_obverse'] ?? '-') ?></td>
                            <td class="px-3 py-3"><?= htmlspecialchars($item['description_reverse'] ?? '-') ?></td>
                            <td class="px-3 py-3"><?= htmlspecialchars($item['additional_info'] ?? '-') ?></td>
                            <td class="px-3 py-3">
                                <?php if (!empty($variants)): ?>
                                    <div class="space-y-1">
                                        <?php foreach ($variants as $v): ?>
                                            <div class="flex items-center gap-2 text-xs">
                                                <div class="w-4 h-4 rounded-full flex items-center justify-center flex-shrink-0 <?= $v['owned'] ? 'bg-green-500' : 'bg-red-500' ?>" title="<?= $v['owned'] ? Lang::get('owned_yes') : Lang::get('owned_no') ?>">
                                                    <?php if ($v['owned']): ?>
                                                        <svg class="w-2.5 h-2.5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7"/></svg>
                                                    <?php else: ?>
                                                        <svg class="w-2.5 h-2.5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M6 18L18 6M6 6l12 12"/></svg>
                                                    <?php endif; ?>
                                                </div>
                                                <span class="text-gray-700 dark:text-gray-300">
                                                    <?= $v['condition_label'] ? htmlspecialchars($v['condition_label']) : '' ?>
                                                    <?= $v['variant_type_label'] ? ' / ' . htmlspecialchars($v['variant_type_label']) : '' ?>
                                                    <?= $v['note'] ? ' - ' . htmlspecialchars($v['note']) : '' ?>
                                                </span>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                <?php else: ?>
                                    <span class="text-gray-300 dark:text-gray-600">-</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-3 py-3">
                                <div class="flex space-x-2">
                                    <button type="button" onclick="toggleWishlistQuick('<?= $subcollection['type'] === 'coin' ? 'coin' : 'item' ?>', <?= $item['id'] ?>, this)" class="text-gray-400 hover:text-green-600 dark:hover:text-green-400 transition-colors" title="Toggle Wishlist">
                                        <svg class="wishlist-heart w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
                                        </svg>
                                    </button>
                                    <button type="button" onclick="moveItem(<?= $item['id'] ?>, 'up', this)" class="text-gray-400 hover:text-green-600 dark:hover:text-green-400 transition-colors" title="<?= Lang::get('move_up') ?>">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7"/></svg>
                                    </button>
                                    <button type="button" onclick="moveItem(<?= $item['id'] ?>, 'down', this)" class="text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors" title="<?= Lang::get('move_down') ?>">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
                                    </button>
                                    <button type="button" onclick="duplicateItem(<?= $item['id'] ?>, '<?= $subcollection['type'] === 'coin' ? 'coins' : 'items' ?>', this)" class="text-gray-400 hover:text-purple-600 dark:hover:text-purple-400 transition-colors" title="<?= Lang::get('duplicate') ?>">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg>
                                    </button>
                                    <a href="<?= APP_URL ?>/<?= $subcollection['type'] === 'coin' ? 'coins' : 'items' ?>/<?= $item['id'] ?>/edit?view=<?= $view ?>" class="text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 transition-colors" title="<?= Lang::get('edit') ?>">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                                    </a>
                                    <a href="javascript:void(0)" onclick="confirmDelete('<?= Lang::get('confirm_delete') ?>', function(){ window.location.href='<?= APP_URL ?>/<?= $subcollection['type'] === 'coin' ? 'coins' : 'items' ?>/<?= $item['id'] ?>/delete'; })" class="text-gray-400 hover:text-red-600 dark:hover:text-red-400 transition-colors" title="<?= Lang::get('delete') ?>">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                                    </a>
                                </div>
                            </td>
                        <?php endif; ?>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
<?php endif; ?>

<!-- Hidden CSRF token for AJAX -->
<input type="hidden" id="csrf_token" value="<?= Session::getCsrfToken() ?>">

<!-- Gallery Data -->
<script>
var galleryData = {};
<?php foreach ($items as $item): ?>
<?php
    $imgs = [];
    if ($item['image_obverse']) $imgs[] = APP_URL . '/uploads/items/' . $item['image_obverse'];
    if ($item['image_reverse']) $imgs[] = APP_URL . '/uploads/items/' . $item['image_reverse'];
    foreach (($itemImages[$item['id']] ?? []) as $ei) {
        $imgs[] = APP_URL . '/uploads/items/' . $ei['filename'];
    }
?>
galleryData[<?= $item['id'] ?>] = <?= json_encode($imgs) ?>;
<?php endforeach; ?>

// Move item up/down via AJAX (swap DOM elements without page reload)
function moveItem(itemId, direction, btn) {
    if (btn.disabled) return;
    btn.disabled = true;

    const isCoin = <?= $subcollection['type'] === 'coin' ? 'true' : 'false' ?>;
    const itemType = isCoin ? 'coins' : 'items';
    var url = window.location.origin + '/' + itemType + '/' + itemId + '/move-' + direction;

    fetch(url, {
        method: 'GET',
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(function (response) { return response.json(); })
    .then(function (data) {
        if (data.success) {
            swapElement(btn, direction);
        }
        btn.disabled = false;
    })
    .catch(function (err) {
        console.error('Move failed:', err);
        btn.disabled = false;
    });
}
</script>

<!-- Image Gallery Modal -->
<div id="galleryModal" class="fixed inset-0 bg-black/90 z-50 hidden flex flex-col items-center justify-center" role="dialog" aria-modal="true" aria-label="<?= Lang::get('image_gallery') ?>" onclick="if(event.target===this)closeGallery()">
    <!-- Close button -->
    <button onclick="closeGallery()" class="absolute top-4 right-4 text-white/70 hover:text-white z-10 transition-colors" aria-label="<?= Lang::get('close') ?>">
        <svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
    </button>
    <!-- Counter -->
    <div id="galleryCounter" class="absolute top-4 left-4 text-white/70 text-sm font-medium z-10"></div>
    <!-- Main image area -->
    <div class="flex-1 flex items-center justify-center w-full relative px-16">
        <!-- Prev arrow -->
        <button id="galleryPrev" onclick="galleryNav(-1)" class="absolute left-4 text-white/60 hover:text-white transition-colors z-10">
            <svg class="w-10 h-10" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/></svg>
        </button>
        <!-- Image -->
        <img id="galleryImage" src="" alt="" class="max-w-full max-h-[75vh] rounded-lg shadow-2xl object-contain">
        <!-- Next arrow -->
        <button id="galleryNext" onclick="galleryNav(1)" class="absolute right-4 text-white/60 hover:text-white transition-colors z-10">
            <svg class="w-10 h-10" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
        </button>
    </div>
    <!-- Thumbnails -->
    <div id="galleryThumbnails" class="flex items-center justify-center gap-2 py-4 px-4 overflow-x-auto max-w-full"></div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Close dropdown when clicking outside
    document.addEventListener('click', function(event) {
        const dropdown = document.getElementById('exportDropdown');
        const button = event.target.closest('button[onclick="toggleExportDropdown()"]');
        
        if (!button && !dropdown.contains(event.target)) {
            dropdown.classList.add('hidden');
        }
    });
});

function toggleExportDropdown() {
    const dropdown = document.getElementById('exportDropdown');
    dropdown.classList.toggle('hidden');
}

function duplicateItem(itemId, itemType, button) {
    const originalContent = button.innerHTML;
    button.disabled = true;
    button.innerHTML = '<svg class="w-4 h-4 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>';
    
    const formData = new FormData();
    const csrfToken = document.getElementById('csrf_token').value;
    formData.append('csrf_token', csrfToken);
    
    fetch(`<?= APP_URL ?>/${itemType}/${itemId}/duplicate`, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Reload the page to show the duplicated item
            window.location.href = window.location.href;
        } else {
            alert(data.error || 'Failed to duplicate item');
            button.disabled = false;
            button.innerHTML = originalContent;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred while duplicating the item');
        button.disabled = false;
        button.innerHTML = originalContent;
    });
}

function openImportModal() {
    document.getElementById('importModal').classList.remove('hidden');
}

function closeImportModal() {
    document.getElementById('importModal').classList.add('hidden');
    document.getElementById('importFile').value = '';
    document.getElementById('importProgress').classList.add('hidden');
    document.getElementById('importResults').classList.add('hidden');
}

function showImportResults(data) {
    const resultsModal = document.createElement('div');
    resultsModal.id = 'importResultsModal';
    resultsModal.className = 'fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4';
    resultsModal.setAttribute('role', 'dialog');
    resultsModal.setAttribute('aria-modal', 'true');
    resultsModal.innerHTML = `
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-700 w-full max-w-md mx-auto">
            <div class="p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100">
                        ${data.success ? 'Import Successful!' : 'Import Failed'}
                    </h3>
                    <button onclick="closeImportResultsModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                    </button>
                </div>
                <div class="${data.success ? 'bg-green-50 border border-green-200 text-green-700' : 'bg-red-50 border border-red-200 text-red-700'} px-4 py-3 rounded">
                    <p class="font-medium">${data.message}</p>
                    ${data.success ? `
                        <p class="mt-2">Items imported: <strong>${data.imported_count}</strong></p>
                        ${data.skipped_count > 0 ? `<p>Items skipped: <strong>${data.skipped_count}</strong></p>` : ''}
                    ` : ''}
                    ${data.errors && data.errors.length > 0 ? `<p class="mt-2">Errors: ${data.errors.join(', ')}</p>` : ''}
                    ${data.trace ? `<details class="mt-2"><summary class="cursor-pointer">Technical Details</summary><pre class="text-xs mt-2 whitespace-pre-wrap">${data.trace}</pre></details>` : ''}
                </div>
                <div class="mt-4 flex justify-end">
                    <button onclick="closeImportResultsModal()" class="px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700">
                        Close
                    </button>
                </div>
            </div>
        </div>
    `;
    document.body.appendChild(resultsModal);
}

function closeImportResultsModal() {
    const resultsModal = document.getElementById('importResultsModal');
    if (resultsModal) {
        resultsModal.remove();
    }
}

function downloadSampleFile() {
    const collectionType = '<?= $subcollection['type'] ?>';
    const url = `<?= APP_URL ?>/collections/<?= $subcollection['collection_id'] ?>/sample/${collectionType}`;
    window.open(url, '_blank');
}

function uploadImportFile() {
    console.log('uploadImportFile function called');
    
    const fileInput = document.getElementById('importFile');
    const file = fileInput.files[0];
    
    console.log('Selected file:', file);
    
    if (!file) {
        alert('Please select a file to import');
        return;
    }
    
    if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
        alert('Please select an Excel file (.xlsx or .xls)');
        return;
    }
    
    console.log('File validation passed, preparing import...');
    
    const formData = new FormData();
    formData.append('importFile', file);
    formData.append('collectionId', '<?= $subcollection['collection_id'] ?>');
    formData.append('collectionType', '<?= $subcollection['type'] ?>');
    formData.append('subcollectionId', '<?= $subcollection['id'] ?>');
    formData.append('csrf_token', '<?= Session::getCsrfToken() ?>');
    
    // Close import modal first
    closeImportModal();
    
    // Show spinner backdrop
    let spinnerBackdrop = document.getElementById('importSpinnerBackdrop');
    if (!spinnerBackdrop) {
        // Create spinner backdrop if it doesn't exist
        spinnerBackdrop = document.createElement('div');
        spinnerBackdrop.id = 'importSpinnerBackdrop';
        spinnerBackdrop.className = 'import-backdrop';
        spinnerBackdrop.innerHTML = `
            <div class="import-content">
                <div class="animated-spinner mx-auto mb-4"></div>
                <h3 class="text-lg font-semibold mb-2">Importing...</h3>
                <p class="text-gray-600 dark:text-gray-400">Please wait while we process your Excel file.</p>
            </div>
        `;
        document.body.appendChild(spinnerBackdrop);
    }
    spinnerBackdrop.classList.remove('hidden');
    spinnerBackdrop.style.display = 'flex';
    
    fetch('<?= APP_URL ?>/collections/import', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        console.log('Response status:', response.status);
        console.log('Response headers:', response.headers.get('content-type'));
        return response.text().then(text => {
            console.log('Raw response text:', text);
            try {
                return JSON.parse(text);
            } catch (e) {
                console.error('JSON parse error:', e);
                throw new Error('Invalid JSON response: ' + text.substring(0, 200));
            }
        });
    })
    .then(data => {
        // Hide spinner
        spinnerBackdrop.classList.add('hidden');
        spinnerBackdrop.style.display = 'none';
        
        // Show results modal
        showImportResults(data);
    })
    .catch(error => {
        // Hide spinner
        spinnerBackdrop.classList.add('hidden');
        spinnerBackdrop.style.display = 'none';
        
        console.error('Fetch error:', error);
        document.getElementById('importProgress').classList.add('hidden');
        document.getElementById('importResults').classList.remove('hidden');
        document.getElementById('importResults').innerHTML = `
            <div class="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded">
                <strong>Error!</strong> ${error.message}
                <br><details><summary>Technical Details</summary><pre>${error.stack}</pre></details>
            </div>
        `;
    });
}

// Animated Spinner CSS
const spinnerCSS = `
<style>
.animated-spinner {
    --size: 10rem;
    --color: #ffeb3b;
    --color-2: #9c27b0;
    --color-3: #03a9f4;
    width: var(--size);
    background: conic-gradient(
        from 0deg,
        var(--color),
        var(--color-2),
        var(--color-3),
        transparent 20%
    );
    mask: radial-gradient(
        circle,
        transparent calc(var(--size) / 2 - 1rem),
        black calc(var(--size) / 2 - 1rem)
    );
    filter: drop-shadow(1rem 0 2rem var(--color-3));
    border-radius: 50%;
    aspect-ratio: 1;
    animation: rotate 1.1s ease infinite, line-width 3.3s ease infinite;
}

@keyframes rotate {
    from {
        background: conic-gradient(
            from 0deg,
            var(--color),
            var(--color-2),
            var(--color-3),
            transparent 20%
        );
    }
    50% {
        background: conic-gradient(
            from -180deg,
            var(--color),
            var(--color-2),
            var(--color-3),
            transparent 50%
        );
    }
    70% {
        background: conic-gradient(
            from -252deg,
            var(--color),
            var(--color-2),
            var(--color-3),
            transparent 30%
        );
    }
    90% {
        background: conic-gradient(
            from -324deg,
            var(--color),
            var(--color-2),
            var(--color-3),
            transparent 10%
        );
    }
    to {
        background: conic-gradient(
            from -360deg,
            var(--color),
            var(--color-2),
            var(--color-3),
            transparent 20%
        );
    }
}

@keyframes line-width {
    from, 20%, 70%, to {
        mask: radial-gradient(
            circle,
            transparent calc(var(--size) / 2 - 1rem),
            black calc(var(--size) / 2 - 1rem)
        );
    }
    
    50% {
        mask: radial-gradient(
            circle,
            transparent calc(var(--size) / 2 - 0.1rem),
            black calc(var(--size) / 2 - 0.1rem)
        );
    }
}

.import-backdrop {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 99999;
    display: flex;
    align-items: center;
    justify-content: center;
}

.import-content {
    background: white;
    padding: 2rem;
    border-radius: 1rem;
    text-align: center;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
    max-width: 400px;
    width: 90%;
}

.dark .import-content {
    background: #1f2937;
    color: white;
}
</style>
`;

// Add spinner styles to head
document.head.insertAdjacentHTML('beforeend', spinnerCSS);

// Create spinner backdrop - hidden by default
const spinnerBackdrop = document.createElement('div');
spinnerBackdrop.id = 'importSpinnerBackdrop';
spinnerBackdrop.className = 'import-backdrop hidden';
spinnerBackdrop.style.display = 'none'; // Ensure it's hidden by default
spinnerBackdrop.innerHTML = `
    <div class="import-content">
        <div class="animated-spinner mx-auto mb-4"></div>
        <h3 class="text-lg font-semibold mb-2">Importing...</h3>
        <p class="text-gray-600 dark:text-gray-400">Please wait while we process your Excel file.</p>
    </div>
`;
document.body.appendChild(spinnerBackdrop);
</script>

<!-- Import Modal -->
<div id="importModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4" role="dialog" aria-modal="true" aria-labelledby="subImportModalHeading">
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-700 w-full max-w-md mx-auto">
        <div class="p-6">
            <div class="flex items-center justify-between mb-4">
                <h3 id="subImportModalHeading" class="text-lg font-semibold text-gray-900 dark:text-gray-100"><?= Lang::get('import_items') ?></h3>
                <button onclick="closeImportModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300" aria-label="<?= Lang::get('close') ?>">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>
            
            <div class="space-y-4">
                <div class="bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
                    <h4 class="font-medium text-blue-900 dark:text-blue-100 mb-2"><?= Lang::get('import_instructions') ?></h4>
                    <ul class="text-sm text-blue-800 dark:text-blue-200 space-y-1">
                        <li>1. <?= Lang::get('download_sample_file') ?></li>
                        <li>2. <?= Lang::get('fill_excel_file') ?></li>
                        <li>3. <?= Lang::get('upload_filled_file') ?></li>
                    </ul>
                </div>
                
                <div>
                    <button onclick="downloadSampleFile()" class="w-full flex items-center justify-center px-4 py-2 bg-green-600 hover:bg-green-700 text-white font-medium rounded-lg transition-colors">
                        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                        </svg>
                        <?= Lang::get('download_sample_excel') ?>
                    </button>
                </div>
                
                <div class="border-t pt-4">
                    <label for="importFile" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        <?= Lang::get('select_excel_file') ?>
                    </label>
                    <input type="file" id="importFile" accept=".xlsx,.xls" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                </div>
                
                <div id="importProgress" class="hidden">
                    <div class="flex items-center justify-center py-4">
                        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                        <span class="ml-2 text-gray-600 dark:text-gray-400"><?= Lang::get('importing') ?>...</span>
                    </div>
                </div>
                
                <div id="importResults" class="hidden"></div>
                
                <div class="flex space-x-3">
                    <button onclick="uploadImportFile()" class="flex-1 bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-lg transition-colors">
                        <?= Lang::get('upload_import') ?>
                    </button>
                    <button onclick="closeImportModal()" class="flex-1 bg-gray-300 hover:bg-gray-400 text-gray-700 font-medium py-2 px-4 rounded-lg transition-colors">
                        <?= Lang::get('cancel') ?>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Quick wishlist toggle function
function toggleWishlistQuick(itemType, itemId, button) {
    const svg = button.querySelector('svg');
    const isInWishlist = svg.classList.contains('wishlist-active');
    
    if (isInWishlist) {
        // Remove from wishlist
        removeFromWishlistQuick(itemType, itemId, button);
    } else {
        // Add to wishlist (simple add without modal)
        addToWishlistQuick(itemType, itemId, button);
    }
}

function addToWishlistQuick(itemType, itemId, button) {
    const formData = new FormData();
    formData.append('item_id', itemId);
    formData.append('item_type', itemType);
    formData.append('csrf_token', document.getElementById('csrf_token').value);
    formData.append('priority', 'medium'); // Default priority
    
    fetch('<?= APP_URL ?>/api/wishlist/add', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const svg = button.querySelector('svg');
            svg.classList.add('wishlist-active');
            svg.setAttribute('fill', 'currentColor');
            button.classList.add('text-green-600');
            button.classList.remove('text-gray-400');
            showToast('Item added to wishlist', 'success');
        } else {
            showToast(data.message || 'Failed to add to wishlist', 'error');
        }
    })
    .catch(error => {
        showToast('An error occurred', 'error');
    });
}

function removeFromWishlistQuick(itemType, itemId, button) {
    if (!confirm('Remove this item from wishlist?')) {
        return;
    }
    
    const formData = new FormData();
    formData.append('item_id', itemId);
    formData.append('item_type', itemType);
    formData.append('csrf_token', document.getElementById('csrf_token').value);
    
    fetch('<?= APP_URL ?>/api/wishlist/remove', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const svg = button.querySelector('svg');
            svg.classList.remove('wishlist-active');
            svg.setAttribute('fill', 'none');
            button.classList.remove('text-green-600');
            button.classList.add('text-gray-400');
            showToast('Item removed from wishlist', 'success');
        } else {
            showToast(data.message || 'Failed to remove from wishlist', 'error');
        }
    })
    .catch(error => {
        showToast('An error occurred', 'error');
    });
}

function showToast(message, type = 'info') {
    // Simple toast notification
    const toastHtml = `
        <div class="position-fixed top-0 end-0 p-3" style="z-index: 11">
            <div class="toast show" role="alert">
                <div class="toast-header bg-${type === 'success' ? 'success' : type === 'error' ? 'danger' : 'info'} text-white">
                    <strong class="me-auto">Wishlist</strong>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
                </div>
                <div class="toast-body">
                    ${message}
                </div>
            </div>
        </div>
    `;
    
    const toastElement = document.createElement('div');
    toastElement.innerHTML = toastHtml;
    document.body.appendChild(toastElement);
    
    setTimeout(() => {
        toastElement.remove();
    }, 3000);
}

// Check wishlist status for all items on page load
document.addEventListener('DOMContentLoaded', function() {
    const wishlistButtons = document.querySelectorAll('[onclick*="toggleWishlistQuick"]');
    wishlistButtons.forEach(button => {
        const onclick = button.getAttribute('onclick');
        const matches = onclick.match(/toggleWishlistQuick\('([^']+)',\s*(\d+)/);
        if (matches) {
            const itemType = matches[1];
            const itemId = matches[2];
            checkWishlistStatusQuick(itemType, itemId, button);
        }
    });
});

function checkWishlistStatusQuick(itemType, itemId, button) {
    fetch(`<?= APP_URL ?>/api/wishlist/check?item_type=${itemType}&item_id=${itemId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.is_in_wishlist) {
                const svg = button.querySelector('svg');
                svg.classList.add('wishlist-active');
                svg.setAttribute('fill', 'currentColor');
                button.classList.add('text-green-600');
                button.classList.remove('text-gray-400');
            }
        })
        .catch(error => {
            console.error('Error checking wishlist status:', error);
        });
}
</script>

<?php $extraJs = ['items.js']; ?>
<?php require APP_ROOT . '/views/layouts/footer.php'; ?>
