<?php require APP_ROOT . '/views/layouts/header.php'; ?>

<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <!-- Header -->
    <!-- Header -->
    <div class="flex items-center justify-between mb-8">
        <h1 class="text-2xl font-bold text-gray-900 dark:text-gray-100">
            My Wishlist
        </h1>
    </div>

    <!-- Desktop Statistics -->
    <div class="hidden md:grid grid-cols-3 gap-6 mb-8">
        <div class="bg-blue-600 text-white rounded-xl p-6">
            <h3 class="text-lg font-semibold mb-2">Total Items</h3>
            <p class="text-3xl font-bold"><?= $stats['total_items'] ?? 0 ?></p>
        </div>
        <div class="bg-green-600 text-white rounded-xl p-6">
            <h3 class="text-lg font-semibold mb-2">Banknotes</h3>
            <p class="text-3xl font-bold"><?= $stats['banknotes_count'] ?? 0 ?></p>
        </div>
        <div class="bg-cyan-600 text-white rounded-xl p-6">
            <h3 class="text-lg font-semibold mb-2">Coins</h3>
            <p class="text-3xl font-bold"><?= $stats['coins_count'] ?? 0 ?></p>
        </div>
    </div>

    <!-- Mobile Statistics - Horizontal Layout -->
    <div class="md:hidden space-y-2 mb-8">
        <div class="bg-blue-600 text-white rounded-xl p-4 w-full flex justify-between items-center">
            <h3 class="text-sm font-medium">Total Items</h3>
            <p class="text-2xl font-bold"><?= $stats['total_items'] ?? 0 ?></p>
        </div>
        <div class="bg-green-600 text-white rounded-xl p-4 w-full flex justify-between items-center">
            <h3 class="text-sm font-medium">Banknotes</h3>
            <p class="text-2xl font-bold"><?= $stats['banknotes_count'] ?? 0 ?></p>
        </div>
        <div class="bg-cyan-600 text-white rounded-xl p-4 w-full flex justify-between items-center">
            <h3 class="text-sm font-medium">Coins</h3>
            <p class="text-2xl font-bold"><?= $stats['coins_count'] ?? 0 ?></p>
        </div>
    </div>

    <!-- Filter Tabs -->
    <div class="border-b border-gray-200 dark:border-gray-700 mb-6">
        <nav class="-mb-px flex space-x-8" aria-label="Tabs">
            <button class="tab-button active py-2 px-1 border-b-2 border-blue-500 font-medium text-sm text-blue-600" data-tab="all">
                All Items (<?= $stats['total_items'] ?? 0 ?>)
            </button>
            <button class="tab-button py-2 px-1 border-b-2 border-transparent font-medium text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300" data-tab="banknotes">
                Banknotes (<?= $stats['banknotes_count'] ?? 0 ?>)
            </button>
            <button class="tab-button py-2 px-1 border-b-2 border-transparent font-medium text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300" data-tab="coins">
                Coins (<?= $stats['coins_count'] ?? 0 ?>)
            </button>
        </nav>
    </div>

    <!-- Tab Content -->
    <div class="tab-content">
        <!-- All Items Tab -->
        <div class="tab-panel active" id="all-tab-panel">
            <?php if (empty($wishlistItems)): ?>
                <div class="text-center py-12">
                    <svg class="w-16 h-16 mx-auto text-gray-400 mb-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>
                    <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-2">Your wishlist is empty</h3>
                    <p class="text-gray-500 dark:text-gray-400 mb-6">Start adding items to your wishlist to keep track of them!</p>
                    <a href="<?= APP_URL ?>/home" class="btn-gradient btn-gradient-blue btn-gradient-icon btn-gradient-lg">
                        <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 4v16m8-8H4"/>
                        </svg>
                        Browse Collections
                    </a>
                </div>
            <?php else: ?>
                <div class="wishlist-grid grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" id="wishlist-grid">
                    <?php foreach ($wishlistItems as $item): ?>
                        <div class="wishlist-item bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden hover:shadow-lg transition-shadow" data-item-type="<?= htmlspecialchars($item['item_type']) ?>" data-item-id="<?= $item['item_id'] ?>">
                            <div class="p-4">
                                <!-- Image Section -->
                                <div class="mb-4">
                                    <div class="flex space-x-2 justify-center">
                                        <?php if ($item['image_obverse']): ?>
                                            <div class="flex-1">
                                                <p class="text-xs text-gray-400 dark:text-gray-500 mb-1 text-center">Avers</p>
                                                <div class="<?= $item['item_type'] === 'coin' ? 'w-40 h-40 rounded-full' : 'w-full h-20' ?> bg-gray-100 dark:bg-gray-700 rounded-lg flex items-center justify-center">
                                                    <img src="<?= APP_URL ?>/uploads/items/thumbs/<?= htmlspecialchars(pathinfo($item['image_obverse'], PATHINFO_FILENAME)) ?>_thumb.<?= htmlspecialchars(pathinfo($item['image_obverse'], PATHINFO_EXTENSION)) ?>" 
                                                         alt="Avers" class="<?= $item['item_type'] === 'coin' ? 'w-40 h-40 object-cover rounded-full' : 'max-w-full max-h-full object-contain' ?> cursor-zoom-in" onclick="openGallery(<?= $item['item_id'] ?>, 0)">
                                                </div>
                                            </div>
                                        <?php else: ?>
                                            <div class="flex-1">
                                                <p class="text-xs text-gray-400 dark:text-gray-500 mb-1 text-center">Avers</p>
                                                <div class="<?= $item['item_type'] === 'coin' ? 'w-40 h-40 rounded-full' : 'w-full h-20' ?> bg-gray-100 dark:bg-gray-700 rounded-lg flex items-center justify-center">
                                                    <svg class="<?= $item['item_type'] === 'coin' ? 'w-12 h-12' : 'w-8 h-8' ?> text-gray-400" 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>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($item['image_reverse']): ?>
                                            <div class="flex-1">
                                                <p class="text-xs text-gray-400 dark:text-gray-500 mb-1 text-center">Revers</p>
                                                <div class="<?= $item['item_type'] === 'coin' ? 'w-40 h-40 rounded-full' : 'w-full h-20' ?> bg-gray-100 dark:bg-gray-700 rounded-lg flex items-center justify-center">
                                                    <img src="<?= APP_URL ?>/uploads/items/thumbs/<?= htmlspecialchars(pathinfo($item['image_reverse'], PATHINFO_FILENAME)) ?>_thumb.<?= htmlspecialchars(pathinfo($item['image_reverse'], PATHINFO_EXTENSION)) ?>" 
                                                         alt="Revers" class="<?= $item['item_type'] === 'coin' ? 'w-40 h-40 object-cover rounded-full' : 'max-w-full max-h-full object-contain' ?> cursor-zoom-in" onclick="openGallery(<?= $item['item_id'] ?>, 1)">
                                                </div>
                                            </div>
                                        <?php else: ?>
                                            <div class="flex-1">
                                                <p class="text-xs text-gray-400 dark:text-gray-500 mb-1 text-center">Revers</p>
                                                <div class="<?= $item['item_type'] === 'coin' ? 'w-40 h-40 rounded-full' : 'w-full h-20' ?> bg-gray-100 dark:bg-gray-700 rounded-lg flex items-center justify-center">
                                                    <svg class="<?= $item['item_type'] === 'coin' ? 'w-12 h-12' : 'w-8 h-8' ?> text-gray-400" 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>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <!-- Content Section -->
                                <div class="space-y-3">
                                    <!-- Title and Badges -->
                                    <div>
                                        <h3 class="text-base font-medium text-gray-900 dark:text-gray-100 mb-2 truncate">
                                            <?= htmlspecialchars($item['nominal_value'] ?? 'N/A') ?>
                                        </h3>
                                        <div class="flex flex-wrap gap-1">
                                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium <?= $item['item_type'] === 'coin' ? 'bg-cyan-100 text-cyan-800 dark:bg-cyan-900 dark:text-cyan-200' : 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200' ?>">
                                                <?= $item['item_type'] === 'coin' ? 'Coin' : 'Banknote' ?>
                                            </span>
                                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-<?= $item['priority'] === 'high' ? 'red' : ($item['priority'] === 'medium' ? 'yellow' : 'gray') ?>-100 text-<?= $item['priority'] === 'high' ? 'red' : ($item['priority'] === 'medium' ? 'yellow' : 'gray') ?>-800 dark:bg-<?= $item['priority'] === 'high' ? 'red' : ($item['priority'] === 'medium' ? 'yellow' : 'gray') ?>-900 dark:text-<?= $item['priority'] === 'high' ? 'red' : ($item['priority'] === 'medium' ? 'yellow' : 'gray') ?>-200">
                                                <?= ucfirst($item['priority']) ?>
                                            </span>
                                        </div>
                                    </div>
                                    
                                    <!-- Details -->
                                    <div class="space-y-1 text-sm text-gray-600 dark:text-gray-400">
                                        <p class="truncate">
                                            <?= htmlspecialchars($item['country'] ?? 'N/A') ?> - 
                                            <?= htmlspecialchars($item['catalog_number'] ?? 'N/A') ?>
                                        </p>
                                        <p class="truncate">
                                            <?= htmlspecialchars($item['collection_name'] ?? 'N/A') ?> / 
                                            <?= htmlspecialchars($item['subcollection_name'] ?? 'N/A') ?>
                                        </p>
                                        <?php if ($item['target_price']): ?>
                                            <p>
                                                <span class="font-medium">Target:</span> <?= number_format($item['target_price'], 2) ?>
                                            </p>
                                        <?php endif; ?>
                                        <?php if ($item['notes']): ?>
                                            <p class="text-xs italic truncate">
                                                <?= htmlspecialchars(substr($item['notes'], 0, 60)) ?><?= strlen($item['notes']) > 60 ? '...' : '' ?>
                                            </p>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <!-- Actions -->
                                    <div class="flex flex-col space-y-2">
                                        <div class="flex space-x-2">
                                            <a href="<?= APP_URL ?>/<?= $item['item_type'] === 'coin' ? 'coins' : 'items' ?>/<?= $item['item_id'] ?>/edit" 
                                               class="flex-1 btn-gradient btn-gradient-gray btn-gradient-sm">
                                                <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                                                </svg>
                                                View
                                            </a>
                                            <button type="button" class="flex-1 btn-gradient btn-gradient-gray btn-gradient-sm" 
                                                    onclick="editWishlistItem(<?= $item['item_id'] ?>, '<?= $item['item_type'] ?>')">
                                                <svg class="w-3 h-3" 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>
                                                Edit
                                            </button>
                                            <button type="button" class="btn-gradient btn-gradient-red btn-gradient-sm" 
                                                    onclick="removeFromWishlist(<?= $item['item_id'] ?>, '<?= $item['item_type'] ?>')">
                                                DELETE
                                            </button>
                                        </div>
                                        <div class="text-xs text-gray-500 dark:text-gray-400 text-center">
                                            <?= date('M j, Y', strtotime($item['created_at'])) ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

                <!-- Banknotes Tab -->
                <div class="tab-panel hidden" id="banknotes-tab-panel">
                    <div class="wishlist-grid grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" id="banknotes-grid">
                        <!-- Banknotes will be loaded here via JavaScript -->
                    </div>
                </div>

                <!-- Coins Tab -->
                <div class="tab-panel hidden" id="coins-tab-panel">
                    <div class="wishlist-grid grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" id="coins-grid">
                        <!-- Coins will be loaded here via JavaScript -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Wishlist Item Modal -->
<div id="editWishlistModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 hidden" role="dialog" aria-modal="true" aria-labelledby="editWishlistHeading">
    <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white dark:bg-gray-800">
        <div class="flex items-center justify-between mb-4">
            <h3 id="editWishlistHeading" class="text-lg font-medium text-gray-900 dark:text-gray-100">Edit Wishlist Item</h3>
            <button type="button" onclick="closeEditModal()" 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="mt-2">
            <form id="editWishlistForm">
                <input type="hidden" id="edit_item_type" name="item_type">
                <input type="hidden" id="edit_item_id" name="item_id">
                <input type="hidden" name="csrf_token" value="<?= Session::getCsrfToken() ?>">
                
                <div class="mb-4">
                    <label for="edit_notes" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Notes</label>
                    <textarea class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500" id="edit_notes" name="notes" rows="3" 
                              placeholder="Add your notes about this item..."></textarea>
                </div>
                
                <div class="mb-4">
                    <label for="edit_target_price" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Target Price</label>
                    <input type="number" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500" id="edit_target_price" name="target_price" 
                           step="0.01" min="0" placeholder="0.00">
                </div>
                
                <div class="mb-4">
                    <label for="edit_priority" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Priority</label>
                    <select class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500" id="edit_priority" name="priority">
                        <option value="low">Low</option>
                        <option value="medium">Medium</option>
                        <option value="high">High</option>
                    </select>
                </div>
            </form>
        </div>
        <div class="flex justify-end space-x-3 mt-6">
            <button type="button" onclick="closeEditModal()" class="btn-gradient btn-gradient-gray btn-gradient-sm">Cancel</button>
            <button type="button" onclick="updateWishlistItem()" class="btn-gradient btn-gradient-blue btn-gradient-sm">Save Changes</button>
        </div>
    </div>
</div>

<?php
function getPriorityColor($priority) {
    switch($priority) {
        case 'high': return 'danger';
        case 'medium': return 'warning';
        case 'low': return 'secondary';
        default: return 'secondary';
    }
}
?>

<script>
let wishlistItems = <?= json_encode($wishlistItems) ?>;

// Gallery data for zoom functionality
let galleryData = {};
<?php foreach ($wishlistItems as $item): ?>
galleryData[<?= $item['item_id'] ?>] = [];
<?php if ($item['image_obverse']): ?>
galleryData[<?= $item['item_id'] ?>].push('<?= APP_URL ?>/uploads/items/<?= htmlspecialchars($item['image_obverse']) ?>');
<?php endif; ?>
<?php if ($item['image_reverse']): ?>
galleryData[<?= $item['item_id'] ?>].push('<?= APP_URL ?>/uploads/items/<?= htmlspecialchars($item['image_reverse']) ?>');
<?php endif; ?>
<?php endforeach; ?>

// Gallery variables
let galleryCurrentIndex = 0;
let galleryCurrentImages = [];

function openGallery(itemId, startIndex) {
    const images = galleryData[itemId] || [];
    if (images.length === 0) return;

    galleryCurrentImages = images;
    galleryCurrentIndex = startIndex || 0;

    const modal = document.getElementById('galleryModal');
    if (modal) {
        modal.classList.remove('hidden');
        modal.classList.add('flex');
        document.body.style.overflow = 'hidden';
        renderGallery();
    }
}

function closeGallery() {
    const modal = document.getElementById('galleryModal');
    if (modal) {
        modal.classList.add('hidden');
        modal.classList.remove('flex');
        document.body.style.overflow = '';
    }
}

function galleryNav(direction) {
    galleryCurrentIndex += direction;
    if (galleryCurrentIndex < 0) galleryCurrentIndex = galleryCurrentImages.length - 1;
    if (galleryCurrentIndex >= galleryCurrentImages.length) galleryCurrentIndex = 0;
    renderGallery();
}

function galleryGoTo(index) {
    galleryCurrentIndex = index;
    renderGallery();
}

function renderGallery() {
    var img = document.getElementById('galleryImage');
    var counter = document.getElementById('galleryCounter');
    var thumbs = document.getElementById('galleryThumbnails');
    var prevBtn = document.getElementById('galleryPrev');
    var nextBtn = document.getElementById('galleryNext');

    if (img) img.src = galleryCurrentImages[galleryCurrentIndex];
    if (counter) counter.textContent = (galleryCurrentIndex + 1) + ' / ' + galleryCurrentImages.length;

    // Show/hide arrows for single image
    var showArrows = galleryCurrentImages.length > 1;
    if (prevBtn) prevBtn.style.display = showArrows ? '' : 'none';
    if (nextBtn) nextBtn.style.display = showArrows ? '' : 'none';

    // Build thumbnails
    if (thumbs) {
        thumbs.innerHTML = '';
        if (galleryCurrentImages.length > 1) {
            galleryCurrentImages.forEach(function (src, idx) {
                var thumb = document.createElement('img');
                thumb.src = src;
                thumb.className = 'w-16 h-12 object-cover rounded cursor-pointer border-2 transition-all flex-shrink-0 ' +
                    (idx === galleryCurrentIndex
                        ? 'border-white opacity-100'
                        : 'border-transparent opacity-50 hover:opacity-80');
                thumb.onclick = function (e) { e.stopPropagation(); galleryGoTo(idx); };
                thumbs.appendChild(thumb);
            });
        }
    }
}

// Tab filtering
document.querySelectorAll('.tab-button').forEach(button => {
    button.addEventListener('click', function() {
        const tabName = this.getAttribute('data-tab');
        
        // Update button states
        document.querySelectorAll('.tab-button').forEach(btn => {
            btn.classList.remove('active', 'border-blue-500', 'text-blue-600');
            btn.classList.add('border-transparent', 'text-gray-500', 'hover:text-gray-700', 'hover:border-gray-300');
        });
        
        this.classList.add('active', 'border-blue-500', 'text-blue-600');
        this.classList.remove('border-transparent', 'text-gray-500', 'hover:text-gray-700', 'hover:border-gray-300');
        
        // Show/hide tab panels
        document.querySelectorAll('.tab-panel').forEach(panel => {
            panel.classList.add('hidden');
        });
        
        const targetPanel = document.getElementById(tabName + '-tab-panel');
        if (targetPanel) {
            targetPanel.classList.remove('hidden');
            
            // Filter and display items
            if (tabName === 'all') {
                // All items are already displayed in the PHP, no need to regenerate
                return;
            } else {
                const filteredItems = wishlistItems.filter(item => 
                    (tabName === 'banknotes' && item.item_type === 'item') ||
                    (tabName === 'coins' && item.item_type === 'coin')
                );
                const containerId = tabName === 'banknotes' ? 'banknotes-grid' : 'coins-grid';
                displayWishlistItems(filteredItems, containerId);
            }
        }
    });
});

function displayWishlistItems(items, containerId) {
    const container = document.getElementById(containerId);
    
    if (items.length === 0) {
        container.innerHTML = `
            <div class="text-center py-12 col-span-full">
                <svg class="w-16 h-16 mx-auto text-gray-400 mb-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>
                <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-2">No items found</h3>
                <p class="text-gray-500 dark:text-gray-400">No items match this filter.</p>
            </div>
        `;
        return;
    }
    
    // Set grid container classes
    container.classList.add('grid', 'grid-cols-1', 'md:grid-cols-2', 'lg:grid-cols-3', 'gap-6');
    container.classList.remove('space-y-4');
    
    container.innerHTML = items.map(item => createWishlistItemHTML(item)).join('');
}

function filterWishlistItems(type) {
    const container = type === 'item' ? document.getElementById('banknotes-grid') : document.getElementById('coins-grid');
    const filteredItems = wishlistItems.filter(item => item.item_type === type);
    
    if (filteredItems.length === 0) {
        container.innerHTML = `
            <div class="text-center py-12 col-span-full">
                <svg class="w-16 h-16 mx-auto text-gray-400 mb-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>
                <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-2">No ${type === 'item' ? 'banknotes' : 'coins'} in wishlist</h3>
                <p class="text-gray-500 dark:text-gray-400">Start adding items to see them here.</p>
            </div>
        `;
        return;
    }
    
    container.innerHTML = filteredItems.map(item => createWishlistItemHTML(item)).join('');
}

function createWishlistItemHTML(item) {
    const typeName = item.item_type === 'coin' ? 'Coin' : 'Banknote';
    const typeColor = item.item_type === 'coin' ? 'bg-cyan-100 text-cyan-800 dark:bg-cyan-900 dark:text-cyan-200' : 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200';
    const priorityColor = item.priority === 'high' ? 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200' : (item.priority === 'medium' ? 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200' : 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200');
    
    return `
        <div class="wishlist-item bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden hover:shadow-lg transition-shadow" data-item-type="${item.item_type}" data-item-id="${item.item_id}">
            <div class="p-4">
                <!-- Image Section -->
                <div class="mb-4">
                    <div class="flex space-x-2 justify-center">
                        ${item.image_obverse ? 
                            `<div class="flex-1">
                                <p class="text-xs text-gray-400 dark:text-gray-500 mb-1 text-center">Avers</p>
                                <div class="${item.item_type === 'coin' ? 'w-40 h-40 rounded-full' : 'w-full h-20'} bg-gray-100 dark:bg-gray-700 rounded-lg flex items-center justify-center">
                                    <img src="${APP_URL}/uploads/items/thumbs/${item.image_obverse.split('.').slice(0, -1).join('.')}_thumb.${item.image_obverse.split('.').pop()}" 
                                         alt="Avers" class="${item.item_type === 'coin' ? 'w-40 h-40 object-cover rounded-full' : 'max-w-full max-h-full object-contain'} cursor-zoom-in" onclick="openGallery(${item.item_id}, 0)">
                                </div>
                            </div>` :
                            `<div class="flex-1">
                                <p class="text-xs text-gray-400 dark:text-gray-500 mb-1 text-center">Avers</p>
                                <div class="${item.item_type === 'coin' ? 'w-40 h-40 rounded-full' : 'w-full h-20'} bg-gray-100 dark:bg-gray-700 rounded-lg flex items-center justify-center">
                                    <svg class="${item.item_type === 'coin' ? 'w-12 h-12' : 'w-8 h-8'} text-gray-400" 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>
                                </div>
                            </div>`
                        }
                        
                        ${item.image_reverse ? 
                            `<div class="flex-1">
                                <p class="text-xs text-gray-400 dark:text-gray-500 mb-1 text-center">Revers</p>
                                <div class="${item.item_type === 'coin' ? 'w-40 h-40 rounded-full' : 'w-full h-20'} bg-gray-100 dark:bg-gray-700 rounded-lg flex items-center justify-center">
                                    <img src="${APP_URL}/uploads/items/thumbs/${item.image_reverse.split('.').slice(0, -1).join('.')}_thumb.${item.image_reverse.split('.').pop()}" 
                                         alt="Revers" class="${item.item_type === 'coin' ? 'w-40 h-40 object-cover rounded-full' : 'max-w-full max-h-full object-contain'} cursor-zoom-in" onclick="openGallery(${item.item_id}, 1)">
                                </div>
                            </div>` :
                            `<div class="flex-1">
                                <p class="text-xs text-gray-400 dark:text-gray-500 mb-1 text-center">Revers</p>
                                <div class="${item.item_type === 'coin' ? 'w-40 h-40 rounded-full' : 'w-full h-20'} bg-gray-100 dark:bg-gray-700 rounded-lg flex items-center justify-center">
                                    <svg class="${item.item_type === 'coin' ? 'w-12 h-12' : 'w-8 h-8'} text-gray-400" 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>
                                </div>
                            </div>`
                        }
                    </div>
                </div>
                
                <!-- Content Section -->
                <div class="space-y-3">
                    <!-- Title and Badges -->
                    <div>
                        <h3 class="text-base font-medium text-gray-900 dark:text-gray-100 mb-2 truncate">
                            ${item.nominal_value || 'N/A'}
                        </h3>
                        <div class="flex flex-wrap gap-1">
                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${typeColor}">
                                ${typeName}
                            </span>
                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${priorityColor}">
                                ${item.priority || 'medium'}
                            </span>
                        </div>
                    </div>
                    
                    <!-- Details -->
                    <div class="space-y-1 text-sm text-gray-600 dark:text-gray-400">
                        <p class="truncate">
                            ${item.country || 'N/A'} - ${item.catalog_number || 'N/A'}
                        </p>
                        <p class="truncate">
                            ${item.collection_name || 'N/A'} / ${item.subcollection_name || 'N/A'}
                        </p>
                        ${item.target_price ? `<p><span class="font-medium">Target:</span> ${parseFloat(item.target_price).toFixed(2)}</p>` : ''}
                        ${item.notes ? `<p class="text-xs italic truncate">${item.notes.length > 60 ? item.notes.substring(0, 60) + '...' : item.notes}</p>` : ''}
                    </div>
                    
                    <!-- Actions -->
                    <div class="flex flex-col space-y-2">
                        <div class="flex space-x-2">
                            <a href="${APP_URL}/${item.item_type === 'coin' ? 'coins' : 'items'}/${item.item_id}/edit"
                                class="flex-1 btn-gradient btn-gradient-gray btn-gradient-sm">
                                <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                                </svg>
                                View
                            </a>
                            <button type="button" class="flex-1 btn-gradient btn-gradient-gray btn-gradient-sm"
                                    onclick="editWishlistItem(${item.item_id}, '${item.item_type}')">
                                <svg class="w-3 h-3" 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>
                                Edit
                            </button>
                            <button type="button" class="btn-gradient btn-gradient-red btn-gradient-sm"
                                    onclick="removeFromWishlist(${item.item_id}, '${item.item_type}')">
                                DELETE
                            </button>
                        </div>
                        <div class="text-xs text-gray-500 dark:text-gray-400 text-center">
                            ${new Date(item.created_at).toLocaleDateString()}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
}

// Wishlist operations
function removeFromWishlist(itemId, itemType) {
    if (!confirm('Are you sure you want to remove this item from your wishlist?')) {
        return;
    }
    
    const formData = new FormData();
    formData.append('item_id', itemId);
    formData.append('item_type', itemType);
    formData.append('csrf_token', '<?= Session::getCsrfToken() ?>');
    
    fetch('<?= APP_URL ?>/api/wishlist/remove', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('Item removed from wishlist', 'success');
            location.reload();
        } else {
            showToast(data.message || 'Failed to remove item', 'error');
        }
    })
    .catch(error => {
        showToast('An error occurred', 'error');
    });
}

function editWishlistItem(itemId, itemType) {
    const item = wishlistItems.find(i => i.item_id == itemId && i.item_type === itemType);
    if (!item) return;
    
    document.getElementById('edit_item_type').value = itemType;
    document.getElementById('edit_item_id').value = itemId;
    document.getElementById('edit_notes').value = item.notes || '';
    document.getElementById('edit_target_price').value = item.target_price || '';
    document.getElementById('edit_priority').value = item.priority || 'medium';
    
    // Show Tailwind modal
    document.getElementById('editWishlistModal').classList.remove('hidden');
}

function closeEditModal() {
    document.getElementById('editWishlistModal').classList.add('hidden');
}

function updateWishlistItem() {
    const formData = new FormData(document.getElementById('editWishlistForm'));
    
    fetch('<?= APP_URL ?>/api/wishlist/update', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('Wishlist item updated', 'success');
            closeEditModal();
            location.reload();
        } else {
            showToast(data.message || 'Failed to update item', 'error');
        }
    })
    .catch(error => {
        showToast('An error occurred', 'error');
    });
}

function showToast(message, type = 'info') {
    // Create toast notification (you might need to implement this based on your existing toast system)
    console.log(`${type}: ${message}`);
}
</script>

<style>
.wishlist-grid .wishlist-item {
    transition: transform 0.2s ease-in-out;
}

.wishlist-grid .wishlist-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.wishlist-list .wishlist-item {
    margin-bottom: 1rem;
}
</style>

<!-- 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="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>

<?php require APP_ROOT . '/views/layouts/footer.php'; ?>
