<?php $pageTitle = htmlspecialchars($collection['name']) . ' - ' . Lang::get('app_name'); ?>
<?php require APP_ROOT . '/views/layouts/header.php'; ?>

<div class="mb-6">
    <!-- First row: breadcrumb and title -->
    <div class="mb-4">
        <div class="flex items-center space-x-3 mb-1">
            <a href="<?= APP_URL ?>/home" class="text-gray-400 dark:text-gray-500 hover:text-primary-600 dark:hover:text-primary-400 text-sm transition-colors flex-shrink-0"><?= Lang::get('home') ?></a>
            <span class="text-gray-400 flex-shrink-0">/</span>
            <h1 class="text-xl sm:text-2xl font-bold truncate"><?= htmlspecialchars($collection['name']) ?></h1>
            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-primary-100 dark:bg-primary-900/30 text-primary-800 dark:text-primary-200">
                <?= $collection['type'] === 'coin' ? Lang::get('collection_type_coin') : Lang::get('collection_type_banknote') ?>
            </span>
        </div>
        <?php if (!empty($collection['description'])): ?>
            <p class="text-gray-500 dark:text-gray-400 text-sm"><?= htmlspecialchars($collection['description']) ?></p>
        <?php endif; ?>
    </div>
    
    <!-- Second row: action buttons -->
    <div class="flex items-center gap-2 flex-wrap justify-end">
        <a href="<?= APP_URL ?>/home"
           class="btn-gradient btn-gradient-gray 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="M10 19l-7-7m0 0l7-7m-7 7h18"/></svg>
            <span class="hidden sm:inline"><?= Lang::get('back') ?></span>
        </a>
        <!-- Export dropdown -->
        <div class="relative">
            <button onclick="toggleExportDropdown()" class="btn-gradient btn-gradient-green 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 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-2" 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 ?>/collections/<?= $collection['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 ?>/collections/<?= $collection['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>
        <?php if ($isOwner): ?>
        <a href="<?= APP_URL ?>/collections/<?= $collection['id'] ?>/subcollections/create"
           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"><?= Lang::get('add_subcollection') ?></span>
        </a>
        <button type="button" onclick="showShareModal(<?= $collection['id'] ?>, '<?= htmlspecialchars($collection['name']) ?>')" class="p-2 text-gray-500 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 rounded-lg transition-colors" title="<?= Lang::get('share_collection') ?>" aria-label="<?= Lang::get('share_collection') ?>">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.367 2.684 3 3 0 00-5.367-2.684z"/></svg>
        </button>
        <a href="<?= APP_URL ?>/collections/<?= $collection['id'] ?>/edit"
           class="p-2 text-gray-500 dark:text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 rounded-lg transition-colors" title="<?= Lang::get('edit') ?>">
            <svg class="w-5 h-5" 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>
        <?php endif; ?>
    </div>
</div>

<?php if (empty($subcollections)): ?>
    <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="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"/>
        </svg>
        <p class="text-gray-500 dark:text-gray-400 text-lg"><?= Lang::get('no_subcollections') ?></p>
    </div>
<?php else: ?>
    <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
        <?php foreach ($subcollections as $sub): ?>
            <a href="<?= APP_URL ?>/subcollections/<?= $sub['id'] ?>" class="group block bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 hover:shadow-lg hover:border-primary-300 dark:hover:border-primary-600 transition-all duration-200">
                <div class="flex items-start justify-between mb-2">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100 group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors">
                        <?= htmlspecialchars($sub['name']) ?>
                    </h3>
                    <?php if ($isOwner): ?>
                    <div class="flex items-center space-x-0.5">
                        <button type="button" onclick="event.preventDefault(); window.location.href='<?= APP_URL ?>/subcollections/<?= $sub['id'] ?>/move-up'" class="p-1 text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 rounded transition-colors" title="<?= Lang::get('move_up') ?>" aria-label="<?= 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="event.preventDefault(); window.location.href='<?= APP_URL ?>/subcollections/<?= $sub['id'] ?>/move-down'" class="p-1 text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 rounded transition-colors" title="<?= Lang::get('move_down') ?>" aria-label="<?= 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="event.preventDefault(); window.location.href='<?= APP_URL ?>/subcollections/<?= $sub['id'] ?>/edit'" class="p-1 text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 rounded transition-colors" title="<?= Lang::get('edit') ?>" aria-label="<?= 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>
                        </button>
                        <button type="button" onclick="event.preventDefault(); confirmDelete('<?= Lang::get('confirm_delete') ?>', function(){ window.location.href='<?= APP_URL ?>/subcollections/<?= $sub['id'] ?>/delete'; })" class="p-1 text-gray-400 hover:text-red-600 dark:hover:text-red-400 rounded transition-colors" title="<?= Lang::get('delete') ?>" aria-label="<?= 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>
                        </button>
                    </div>
                    <?php endif; ?>
                </div>
                <?php if (!empty($sub['description'])): ?>
                    <?php $desc = htmlspecialchars($sub['description']); $isLong = mb_strlen($sub['description']) > 160; ?>
                    <div class="text-sm text-gray-500 dark:text-gray-400 mb-3">
                        <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="event.preventDefault(); 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 class="text-xs text-gray-400 dark:text-gray-500 flex items-center space-x-1">
                    <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="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>
                    <span><?= $sub['item_count'] ?> <?= Lang::get('items') ?></span>
                </div>
            </a>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

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

<!-- Share Collection Modal -->
<div id="shareModal" class="fixed inset-0 bg-black/50 z-50 hidden flex items-center justify-center p-4" role="dialog" aria-modal="true" aria-labelledby="colShareModalHeading" onclick="if(event.target===this)closeShareModal()">
    <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 max-w-2xl w-full max-h-[80vh] overflow-hidden flex flex-col">
        <div class="flex items-center justify-between mb-4">
            <h3 id="colShareModalHeading" class="text-xl font-bold"><?= Lang::get('share_collection') ?></h3>
            <button onclick="closeShareModal()" class="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg transition-colors" aria-label="<?= Lang::get('close') ?>">
                <svg class="w-5 h-5" 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="mb-4">
            <p class="text-sm text-gray-500 dark:text-gray-400">Podelite kolekciju "<span id="shareCollectionName" class="font-semibold"></span>" sa drugim korisnicima.</p>
        </div>

        <!-- Share Tabs -->
        <div class="border-b border-gray-200 dark:border-gray-700 mb-4">
            <nav class="flex space-x-8" aria-label="Tabs">
                <button onclick="switchShareTab('users')" id="usersTab" class="share-tab py-2 px-1 border-b-2 border-primary-500 text-primary-600 dark:text-primary-400 font-medium text-sm">
                    <?= Lang::get('share_with_users') ?>
                </button>
                <button onclick="switchShareTab('email')" id="emailTab" class="share-tab py-2 px-1 border-b-2 border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 font-medium text-sm">
                    <?= Lang::get('share_via_email') ?>
                </button>
            </nav>
        </div>

        <div class="flex-1 overflow-y-auto">
            <!-- Users Tab Content -->
            <div id="usersTabContent" class="space-y-4">
                <!-- Search Users -->
                <div>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                            </svg>
                        </div>
                        <input type="text" 
                               id="userSearch" 
                               placeholder="<?= Lang::get('search_users') ?>"
                               class="w-full pl-10 pr-4 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 placeholder-gray-500 dark:placeholder-gray-400 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:focus:ring-primary-400 dark:focus:border-primary-400">
                    </div>
                </div>

                <!-- Search Results -->
                <div id="userSearchResults" class="max-h-48 overflow-y-auto space-y-2">
                    <!-- Results will be populated here -->
                </div>

                <!-- Selected Users -->
                <div id="selectedUsers" class="space-y-2">
                    <h4 class="text-sm font-medium text-gray-700 dark:text-gray-300"><?= Lang::get('select_users') ?></h4>
                    <div id="selectedUsersList" class="space-y-2">
                        <!-- Selected users will be shown here -->
                    </div>
                </div>
            </div>

            <!-- Email Tab Content -->
            <div id="emailTabContent" class="space-y-4 hidden">
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        <?= Lang::get('email_recipients') ?>
                    </label>
                    <textarea id="emailRecipients" 
                              rows="3" 
                              placeholder="<?= Lang::get('enter_emails') ?>"
                              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 placeholder-gray-500 dark:placeholder-gray-400 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:focus:ring-primary-400 dark:focus:border-primary-400"></textarea>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                        <?= Lang::get('share_message') ?>
                    </label>
                    <textarea id="shareMessage" 
                              rows="4" 
                              placeholder="Unesite poruku za primaoca..."
                              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 placeholder-gray-500 dark:placeholder-gray-400 focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:focus:ring-primary-400 dark:focus:border-primary-400"></textarea>
                </div>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="flex gap-3 justify-end mt-4 pt-4 border-t border-gray-200 dark:border-gray-700">
            <button onclick="closeShareModal()" 
                    class="px-4 py-2 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors">
                <?= Lang::get('cancel') ?>
            </button>
            <button onclick="sendShare()" 
                    class="btn-gradient btn-gradient-blue btn-gradient-icon">
                <?= Lang::get('send_shares') ?>
            </button>
        </div>
    </div>
</div>

<script>
let currentCollectionId = null;
let selectedUsersList = [];
let shareSearchTimeout;
const LANG_NO_USERS = '<?= addslashes(Lang::get("no_users_found")) ?>';

function showShareModal(collectionId, collectionName) {
    currentCollectionId = collectionId;
    document.getElementById('shareCollectionName').textContent = collectionName;
    document.getElementById('shareModal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
    
    // Reset form
    selectedUsersList = [];
    document.getElementById('userSearch').value = '';
    document.getElementById('userSearchResults').innerHTML = '';
    document.getElementById('selectedUsersList').innerHTML = '';
    document.getElementById('emailRecipients').value = '';
    document.getElementById('shareMessage').value = '';
    
    // Focus on search input
    setTimeout(() => {
        document.getElementById('userSearch').focus();
    }, 100);
}

function closeShareModal() {
    document.getElementById('shareModal').classList.add('hidden');
    document.body.style.overflow = '';
    currentCollectionId = null;
    selectedUsersList = [];
}

function switchShareTab(tab) {
    // Update tab styles
    const tabs = document.querySelectorAll('.share-tab');
    tabs.forEach(t => {
        t.classList.remove('border-primary-500', 'text-primary-600', 'dark:text-primary-400');
        t.classList.add('border-transparent', 'text-gray-500', 'hover:text-gray-700', 'dark:text-gray-400', 'dark:hover:text-gray-300');
    });
    
    const activeTab = document.getElementById(tab + 'Tab');
    activeTab.classList.remove('border-transparent', 'text-gray-500', 'hover:text-gray-700', 'dark:text-gray-400', 'dark:hover:text-gray-300');
    activeTab.classList.add('border-primary-500', 'text-primary-600', 'dark:text-primary-400');
    
    // Show/hide content
    document.getElementById('usersTabContent').classList.toggle('hidden', tab !== 'users');
    document.getElementById('emailTabContent').classList.toggle('hidden', tab !== 'email');
}

function searchUsers(query) {
    const resultsContainer = document.getElementById('userSearchResults');
    const lowerQuery = query.toLowerCase().trim();
    
    if (!lowerQuery) {
        resultsContainer.innerHTML = '';
        return;
    }
    
    // Show loading state
    resultsContainer.innerHTML = `
        <div class="text-center py-4 text-gray-500 dark:text-gray-400 text-sm">
            <svg class="w-4 h-4 animate-spin mx-auto mb-2" 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>
            Pretraga...
        </div>
    `;
    
    // Real AJAX call to search users
    fetch(`/api/users/search?q=${encodeURIComponent(query)}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('Search failed');
            }
            return response.json();
        })
        .then(users => {
            // Filter out already selected users
            const filteredUsers = users.filter(user => 
                !selectedUsersList.find(u => u.id === user.id)
            );
            
            if (filteredUsers.length === 0) {
                resultsContainer.innerHTML = `
                    <div class="text-center py-4 text-gray-500 dark:text-gray-400 text-sm">
                        ${LANG_NO_USERS.replace('{query}', query)}
                    </div>
                `;
                return;
            }
            
            resultsContainer.innerHTML = filteredUsers.map(user => `
                <div class="flex items-center justify-between p-2 hover:bg-gray-50 dark:hover:bg-gray-700 rounded-lg cursor-pointer transition-colors" onclick="selectUser(${user.id}, '${user.username}', '${user.display_name.replace(/'/g, "\\'")}')">
                    <div class="flex items-center space-x-3">
                        <div class="w-8 h-8 bg-primary-100 dark:bg-primary-900/30 rounded-full flex items-center justify-center">
                            <span class="text-xs font-medium text-primary-600 dark:text-primary-400">${user.username.charAt(0).toUpperCase()}</span>
                        </div>
                        <div>
                            <p class="text-sm font-medium text-gray-900 dark:text-gray-100">${user.display_name}</p>
                            <p class="text-xs text-gray-500 dark:text-gray-400">@${user.username}</p>
                        </div>
                    </div>
                    <svg class="w-4 h-4 text-gray-400" 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>
                </div>
            `).join('');
        })
        .catch(error => {
            console.error('User search error:', error);
            resultsContainer.innerHTML = `
                <div class="text-center py-4 text-red-500 dark:text-red-400 text-sm">
                    Greška pri pretrazi. Pokušajte ponovo.
                </div>
            `;
        });
}

function selectUser(userId, username, displayName) {
    if (selectedUsersList.find(u => u.id === userId)) return;
    
    selectedUsersList.push({ id: userId, username, displayName });
    
    // Update selected users list
    const selectedContainer = document.getElementById('selectedUsersList');
    selectedContainer.innerHTML = selectedUsersList.map(user => `
        <div class="flex items-center justify-between p-2 bg-gray-50 dark:bg-gray-700 rounded-lg">
            <div class="flex items-center space-x-3">
                <div class="w-8 h-8 bg-primary-100 dark:bg-primary-900/30 rounded-full flex items-center justify-center">
                    <span class="text-xs font-medium text-primary-600 dark:text-primary-400">${user.username.charAt(0).toUpperCase()}</span>
                </div>
                <div>
                    <p class="text-sm font-medium text-gray-900 dark:text-gray-100">${user.displayName}</p>
                    <p class="text-xs text-gray-500 dark:text-gray-400">@${user.username}</p>
                </div>
            </div>
            <button onclick="removeUser(${user.id})" class="p-1 text-red-500 hover:text-red-700 dark:hover:text-red-400 transition-colors">
                <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="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        </div>
    `).join('');
    
    // Clear search
    document.getElementById('userSearch').value = '';
    document.getElementById('userSearchResults').innerHTML = '';
}

function removeUser(userId) {
    selectedUsersList = selectedUsersList.filter(u => u.id !== userId);
    
    // Update selected users list
    const selectedContainer = document.getElementById('selectedUsersList');
    if (selectedUsersList.length === 0) {
        selectedContainer.innerHTML = '<p class="text-sm text-gray-500 dark:text-gray-400">Nema izabranih korisnika</p>';
    } else {
        selectedContainer.innerHTML = selectedUsersList.map(user => `
            <div class="flex items-center justify-between p-2 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <div class="flex items-center space-x-3">
                    <div class="w-8 h-8 bg-primary-100 dark:bg-primary-900/30 rounded-full flex items-center justify-center">
                        <span class="text-xs font-medium text-primary-600 dark:text-primary-400">${user.username.charAt(0).toUpperCase()}</span>
                    </div>
                    <div>
                        <p class="text-sm font-medium text-gray-900 dark:text-gray-100">${user.displayName}</p>
                        <p class="text-xs text-gray-500 dark:text-gray-400">@${user.username}</p>
                    </div>
                </div>
                <button onclick="removeUser(${user.id})" class="p-1 text-red-500 hover:text-red-700 dark:hover:text-red-400 transition-colors">
                    <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="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>
        `).join('');
    }
}

// Custom notification system
function showNotification(message, type = 'success') {
    // Remove existing notifications
    const existing = document.querySelectorAll('.notification-popup');
    existing.forEach(el => el.remove());
    
    const notification = document.createElement('div');
    notification.className = `notification-popup fixed top-4 right-4 z-50 p-4 rounded-lg shadow-lg transform transition-all duration-300 translate-x-full ${
        type === 'success' 
            ? 'bg-green-500 text-white' 
            : 'bg-red-500 text-white'
    }`;
    notification.innerHTML = `
        <div class="flex items-center">
            <svg class="w-5 h-5 mr-3 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                ${type === 'success' 
                    ? '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>'
                    : '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>'
                }
            </svg>
            <span class="text-sm font-medium">${message}</span>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    // Animate in
    setTimeout(() => {
        notification.classList.remove('translate-x-full');
        notification.classList.add('translate-x-0');
    }, 10);
    
    // Auto remove after 3 seconds
    setTimeout(() => {
        notification.classList.remove('translate-x-0');
        notification.classList.add('translate-x-full');
        setTimeout(() => notification.remove(), 300);
    }, 3000);
}

function sendShare() {
    const activeTab = document.querySelector('.share-tab.border-primary-500');
    const isEmailTab = activeTab.id === 'emailTab';
    
    if (isEmailTab) {
        const recipients = document.getElementById('emailRecipients').value.trim();
        const message = document.getElementById('shareMessage').value.trim();
        
        if (!recipients) {
            showNotification('Unesite barem jednu email adresu', 'error');
            return;
        }
        
        // Validate email format
        const emails = recipients.split(',').map(e => e.trim());
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        
        for (const email of emails) {
            if (!emailRegex.test(email)) {
                showNotification(`Neispravan email format: ${email}`, 'error');
                return;
            }
        }
        
        // Send via email
        shareViaEmail(emails, message, currentCollectionId);
    } else {
        if (selectedUsersList.length === 0) {
            showNotification('Izaberite barem jednog korisnika', 'error');
            return;
        }
        
        // Send to users via AJAX
        shareWithUsers(selectedUsersList, currentCollectionId);
    }
    
    closeShareModal();
}

function shareViaEmail(emails, message, collectionId) {
    // Show loading state
    const submitBtn = document.querySelector('button[onclick="sendShare()"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.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>
        Slanje...
    `;
    submitBtn.disabled = true;
    
    fetch(`/collections/${collectionId}/share-email`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `recipients=${encodeURIComponent(emails.join(','))}&message=${encodeURIComponent(message)}&csrf_token=${encodeURIComponent(document.querySelector('meta[name="csrf-token"]').getAttribute('content'))}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'success');
            closeShareModal();
        } else {
            showNotification(data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('Došlo je do greške prilikom slanja email-a', 'error');
    })
    .finally(() => {
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
}

function shareWithUsers(users, collectionId) {
    // Show loading state
    const submitBtn = document.querySelector('button[onclick="sendShare()"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.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>
        Slanje...
    `;
    submitBtn.disabled = true;
    
    // Send each user share request
    const sharePromises = users.map(user => {
        return fetch(`/collections/${collectionId}/share`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `username=${encodeURIComponent(user.username)}&csrf_token=${encodeURIComponent(document.querySelector('meta[name="csrf-token"]').getAttribute('content'))}`
        });
    });
    
    Promise.all(sharePromises)
        .then(responses => Promise.all(responses.map(r => r.text())))
        .then(results => {
            console.log('Share results:', results);
            showNotification('Kolekcija je uspešno podeljena sa izabranim korisnicima!', 'success');
        })
        .catch(error => {
            console.error('Share error:', error);
            showNotification('Greška pri deljenju kolekcije. Pokušajte ponovo.', 'error');
        })
        .finally(() => {
            // Restore button
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        });
}

// Search functionality
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('userSearch');
    if (searchInput) {
        searchInput.addEventListener('input', function(e) {
            clearTimeout(searchTimeout);
            const query = e.target.value;
            
            // Debounce search for better performance
            searchTimeout = setTimeout(() => {
                searchUsers(query);
            }, 300);
        });
        
        // Clear search on Escape key when focused
        searchInput.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                e.target.value = '';
                searchUsers('');
            }
        });
    }
    
    // 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 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 refreshSubcollections() {
    fetch('<?= APP_URL ?>/collections/<?= $collection['id'] ?>/subcollections/json')
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success && data.subcollections) {
                updateSubcollectionsGrid(data.subcollections);
            }
        })
        .catch(error => {
            console.error('Error refreshing subcollections:', error);
        });
}

function updateSubcollectionsGrid(subcollections) {
    // Try multiple selectors to find the grid container
    const container = document.querySelector('.grid.grid-cols-1.md\\:grid-cols-2.xl\\:grid-cols-3') || 
                      document.querySelector('div[class*="grid"]') ||
                      document.querySelector('.grid');
    
    // Try multiple selectors to find the no subcollections message
    const noSubcollectionsDiv = document.querySelector('.bg-white.dark\\:bg-gray-800.rounded-xl.border.border-gray-200.dark\\:border-gray-700.p-12.text-center') ||
                              document.querySelector('.text-center') ||
                              document.querySelector('[class*="text-center"]');
    
    if (subcollections.length === 0) {
        // Hide grid and show no subcollections message
        if (container) container.style.display = 'none';
        if (noSubcollectionsDiv) noSubcollectionsDiv.style.display = 'block';
        return;
    }
    
    // If no container exists, create it
    if (!container) {
        const gridContainer = document.createElement('div');
        gridContainer.className = 'grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6';
        
        // Find the no subcollections message and replace it
        if (noSubcollectionsDiv) {
            noSubcollectionsDiv.parentNode.replaceChild(gridContainer, noSubcollectionsDiv);
        }
    }
    
    // Add new subcollections and update existing ones
    const gridContainer = container || document.querySelector('.grid.grid-cols-1.md\\:grid-cols-2.xl\\:grid-cols-3');
    if (gridContainer) {
        subcollections.forEach(sub => {
            // Check if subcollection already exists - try multiple selectors
            const existingLink = document.querySelector(`a[href="/subcollections/${sub.id}"]`) ||
                               document.querySelector(`a[href*="/subcollections/${sub.id}"]`) ||
                               document.querySelector(`a[href*="${sub.id}"]`);
            
            if (!existingLink) {
                // Add new subcollection
                const subElement = createSubcollectionElement(sub);
                gridContainer.appendChild(subElement);
            } else {
                // Update existing subcollection item count - target the span inside the div with icon
                const countSpan = existingLink.querySelector('.text-xs.text-gray-400.dark\\:text-gray-500 span');
                if (countSpan) {
                    countSpan.textContent = `${sub.item_count || 0} <?= Lang::get('items') ?>`;
                }
            }
        });
    }
}

function createSubcollectionElement(sub) {
    const div = document.createElement('div');
    const appUrl = '<?= APP_URL ?>';
    const expectedHref = `${appUrl}/subcollections/${sub.id}`;
    const isOwner = <?= $isOwner ? 'true' : 'false' ?>;
    
    let actionButtons = '';
    if (isOwner) {
        actionButtons = `
                    <div class="flex items-center space-x-0.5">
                        <button type="button" onclick="event.preventDefault(); window.location.href='<?= APP_URL ?>/subcollections/${sub.id}/move-up'" class="p-1 text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 rounded transition-colors" title="<?= Lang::get('move_up') ?>" aria-label="<?= 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="event.preventDefault(); window.location.href='<?= APP_URL ?>/subcollections/${sub.id}/move-down'" class="p-1 text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 rounded transition-colors" title="<?= Lang::get('move_down') ?>" aria-label="<?= 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="event.preventDefault(); window.location.href='<?= APP_URL ?>/subcollections/${sub.id}/edit'" class="p-1 text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 rounded transition-colors" title="<?= Lang::get('edit') ?>" aria-label="<?= 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>
                        </button>
                        <button type="button" onclick="event.preventDefault(); confirmDelete('<?= Lang::get('confirm_delete') ?>', function(){ window.location.href='<?= APP_URL ?>/subcollections/${sub.id}/delete'; })" class="p-1 text-gray-400 hover:text-red-600 dark:hover:text-red-400 rounded transition-colors" title="<?= Lang::get('delete') ?>" aria-label="<?= 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>
                        </button>
                    </div>`;
    }
    
    div.innerHTML = `
        <a href="${expectedHref}" class="group block bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 hover:shadow-lg hover:border-primary-300 dark:hover:border-primary-600 transition-all duration-200">
            <div class="flex items-start justify-between mb-2">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100 group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors">
                    ${sub.name}
                </h3>
                ${actionButtons}
            </div>
            <div class="text-xs text-gray-400 dark:text-gray-500 flex items-center space-x-1">
                <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="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>
                <span>${sub.item_count || 0} <?= Lang::get('items') ?></span>
            </div>
        </a>
    `;
    return div.firstElementChild;
}

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

function uploadImportFile() {
    const fileInput = document.getElementById('importFile');
    const file = fileInput.files[0];
    
    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;
    }
    
    const formData = new FormData();
    formData.append('importFile', file);
    formData.append('collectionId', '<?= $collection['id'] ?>');
    formData.append('collectionType', '<?= $collection['type'] ?>');
    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.substring(0, 500));
            try {
                return JSON.parse(text);
            } catch (e) {
                throw new Error('Server error: ' + text.substring(0, 300));
            }
        });
    })
    .then(data => {
        // Hide spinner
        spinnerBackdrop.classList.add('hidden');
        spinnerBackdrop.style.display = 'none';
        
        // Show results modal
        showImportResults(data);
        
        // Refresh subcollections if import was successful
        if (data.success) {
            refreshSubcollections();
            // If we're currently viewing a subcollection, reload the page to show new items
            if (window.location.pathname.includes('/subcollections/')) {
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            }
        }
    })
    .catch(error => {
        // Hide spinner
        spinnerBackdrop.classList.add('hidden');
        spinnerBackdrop.style.display = 'none';
        
        console.error('Import 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}
            </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="colImportModalHeading">
    <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="colImportModalHeading" 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 btn-gradient btn-gradient-green btn-gradient-icon">
                        <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 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 btn-gradient btn-gradient-blue btn-gradient-icon">
                        <?= Lang::get('upload_import') ?>
                    </button>
                    <button onclick="closeImportModal()" class="flex-1 btn-gradient btn-gradient-gray btn-gradient-icon">
                        <?= Lang::get('cancel') ?>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

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