<?php $pageTitle = Lang::get('home') . ' - ' . Lang::get('app_name'); ?>
<?php require APP_ROOT . '/views/layouts/header.php'; ?>

<div class="flex flex-col lg:flex-row gap-8">
    <!-- Sidebar (shown first on mobile) -->
    <div class="lg:hidden">
        <div class="flex flex-col gap-3">
            <button onclick="showCollectionTypePopup()"
               class="w-full 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>
                <?= Lang::get('add_collection') ?>
            </button>
            <a href="<?= APP_URL ?>/literature"
               class="w-full 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="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"/></svg>
                <?= Lang::get('literature') ?>
            </a>
            <a href="<?= APP_URL ?>/lists"
               class="w-full 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="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"/></svg>
                <?= Lang::get('lists') ?>
            </a>
            <a href="<?= APP_URL ?>/marketplace"
               class="w-full 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="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
                <?= Lang::get('marketplace') ?>
            </a>
        </div>
    </div>

    <!-- Main Content -->
    <div class="flex-1">
        <div class="flex items-center justify-between mb-6">
            <h1 class="text-xl sm:text-2xl font-bold"><?= Lang::get('collections') ?></h1>
        </div>

        <?php if (empty($collections)): ?>
            <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="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"/>
                </svg>
                <p class="text-gray-500 dark:text-gray-400 text-lg"><?= Lang::get('no_collections') ?></p>
            </div>
        <?php else: ?>
            <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
                <?php foreach ($collections as $col): ?>
                    <a href="<?= APP_URL ?>/collections/<?= $col['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">
                        <!-- Type indicator + action icons - same row -->
                        <div class="flex items-center justify-between mb-2">
                            <span class="px-2 py-1 text-xs font-medium rounded-full text-orange-900 dark:text-orange-200" style="background-color: rgba(255, 92, 0, 0.3);">
                                <?= $col['type'] === 'coin' ? Lang::get('collection_type_coin') : Lang::get('collection_type_banknote') ?>
                            </span>
                            <div class="flex items-center space-x-0.5">
                                <button type="button" onclick="event.preventDefault(); showShareModal(<?= $col['id'] ?>, '<?= htmlspecialchars($col['name']) ?>')" class="p-1 text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 rounded transition-colors" title="<?= Lang::get('share_collection') ?>" aria-label="<?= Lang::get('share_collection') ?>">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.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>
                                <button type="button" onclick="event.preventDefault(); window.location.href='<?= APP_URL ?>/collections/<?= $col['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 ?>/collections/<?= $col['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 ?>/collections/<?= $col['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 ?>/collections/<?= $col['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>

                        <!-- Collection name - full width -->
                        <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 mb-3">
                            <?= htmlspecialchars($col['name']) ?>
                        </h3>
                        <?php if (!empty($col['description'])): ?>
                            <p class="text-sm text-gray-500 dark:text-gray-400 mb-4 line-clamp-2"><?= htmlspecialchars($col['description']) ?></p>
                        <?php endif; ?>
                        <div class="flex items-center space-x-4 text-xs text-gray-400 dark:text-gray-500">
                            <span class="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="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"/></svg>
                                <span><?= $col['subcollection_count'] ?> <?= Lang::get('subcollections') ?></span>
                            </span>
                            <span class="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><?= $col['item_count'] ?> <?= Lang::get('items') ?></span>
                            </span>
                        </div>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if (!empty($templates)): ?>
            <div class="mt-8">
                <button onclick="showTemplatesPopup()" 
                        class="w-full btn-gradient btn-gradient-orange btn-gradient-icon btn-gradient-lg">
                    <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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/>
                    </svg>
                    <?= Lang::get('import_template') ?>
                </button>
            </div>
        <?php endif; ?>
    </div>

    <!-- Sidebar (desktop only) -->
    <div class="hidden lg:block lg:w-64 flex-shrink-0">
        <div class="space-y-3 lg:sticky lg:top-8">
            <button onclick="showCollectionTypePopup()"
               class="w-full btn-gradient btn-gradient-blue btn-gradient-icon btn-gradient-lg">
                <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="M12 6v6m0 0v6m0-6h6m-6 0H6"/></svg>
                <?= Lang::get('add_collection') ?>
            </button>

            <a href="<?= APP_URL ?>/literature"
               class="w-full btn-gradient btn-gradient-gray btn-gradient-icon btn-gradient-lg">
                <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="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"/></svg>
                <?= Lang::get('literature') ?>
            </a>

            <a href="<?= APP_URL ?>/lists"
               class="w-full btn-gradient btn-gradient-gray btn-gradient-icon btn-gradient-lg">
                <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="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"/></svg>
                <?= Lang::get('lists') ?>
            </a>

            <a href="<?= APP_URL ?>/marketplace"
               class="w-full btn-gradient btn-gradient-green btn-gradient-icon btn-gradient-lg">
                <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="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
                <?= Lang::get('marketplace') ?>
            </a>
        </div>
    </div>
</div>

<!-- Collection Type Modal -->
<div id="collectionTypeModal" class="fixed inset-0 bg-black/50 z-50 hidden flex items-center justify-center p-4" role="dialog" aria-modal="true" aria-labelledby="collectionTypeHeading" onclick="if(event.target===this)closeCollectionTypePopup()">
    <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 max-w-md w-full">
        <div class="flex items-center justify-between mb-4">
            <h3 id="collectionTypeHeading" class="text-xl font-bold"><?= Lang::get('add_collection') ?></h3>
            <button onclick="closeCollectionTypePopup()" 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>
        
        <p class="text-sm text-gray-500 dark:text-gray-400 mb-6"><?= Lang::get('choose_collection_type') ?></p>
        
        <div class="space-y-3">
            <button onclick="createCollection('banknote')" 
                    class="w-full flex items-center p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg border border-gray-200 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
                <div class="flex items-center space-x-3">
                    <div class="w-10 h-10 bg-green-100 dark:bg-green-900/30 rounded-lg flex items-center justify-center">
                        <svg class="w-6 h-6 text-green-600 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                        </svg>
                    </div>
                    <div class="text-left">
                        <h4 class="font-medium text-gray-900 dark:text-gray-100"><?= Lang::get('collection_type_banknote') ?></h4>
                        <p class="text-sm text-gray-500 dark:text-gray-400"><?= Lang::get('banknote_collection_desc') ?></p>
                    </div>
                </div>
            </button>
            
            <button onclick="createCollection('coin')" 
                    class="w-full flex items-center p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg border border-gray-200 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
                <div class="flex items-center space-x-3">
                    <div class="w-10 h-10 bg-orange-100 dark:bg-orange-900/30 rounded-lg flex items-center justify-center">
                        <svg class="w-6 h-6 text-orange-600 dark:text-orange-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                        </svg>
                    </div>
                    <div class="text-left">
                        <h4 class="font-medium text-gray-900 dark:text-gray-100"><?= Lang::get('collection_type_coin') ?></h4>
                        <p class="text-sm text-gray-500 dark:text-gray-400"><?= Lang::get('coin_collection_desc') ?></p>
                    </div>
                </div>
            </button>
        </div>
        
        <div class="mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
            <button onclick="closeCollectionTypePopup()" 
                    class="w-full 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>
        </div>
    </div>
</div>

<!-- 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="shareModalHeading" 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="shareModalHeading" 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"><?= Lang::get('home_share_collection_desc') ?></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="<?= Lang::get('home_enter_share_message') ?>"
                              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>

<!-- Templates Popup Modal -->
<div id="templatesModal" class="fixed inset-0 bg-black/50 z-50 hidden flex items-center justify-center p-4" role="dialog" aria-modal="true" aria-labelledby="templatesModalHeading" onclick="if(event.target===this)closeTemplatesPopup()">
    <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 max-w-4xl w-full max-h-[80vh] overflow-hidden flex flex-col">
        <div class="flex items-center justify-between mb-4">
            <h3 id="templatesModalHeading" class="text-xl font-bold"><?= Lang::get('import_template_title') ?></h3>
            <button onclick="closeTemplatesPopup()" 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>
        
        <p class="text-sm text-gray-500 dark:text-gray-400 mb-4"><?= Lang::get('import_template_desc') ?></p>
        
        <!-- Search Input -->
        <div class="mb-4">
            <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="templateSearch" 
                       placeholder="<?= Lang::get('search_templates') ?>"
                       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>
        
        <div class="flex-1 overflow-y-auto">
            <div id="templatesContainer">
                <?php if (empty($templates)): ?>
                    <div class="text-center py-12">
                        <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="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"/>
                        </svg>
                        <p class="text-gray-500 dark:text-gray-400"><?= Lang::get('no_templates_available') ?></p>
                    </div>
                <?php else: ?>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4" id="templatesGrid">
                        <?php foreach ($templates as $tpl): ?>
                            <div class="template-item bg-gray-50 dark:bg-gray-700/50 rounded-lg border border-gray-200 dark:border-gray-600 p-4 hover:shadow-md transition-all duration-200" 
                                 data-name="<?= htmlspecialchars(strtolower($tpl['name'])) ?>" 
                                 data-description="<?= htmlspecialchars(strtolower($tpl['description'] ?? '')) ?>"
                                 data-type="<?= htmlspecialchars(strtolower($tpl['type'] === 'coin' ? Lang::get('collection_type_coin') : Lang::get('collection_type_banknote'))) ?>"
                                 data-owner="<?= htmlspecialchars(strtolower($tpl['owner_name'])) ?>">
                                <!-- Type indicator - top left -->
                                <div class="flex justify-start mb-2">
                                    <span class="px-2 py-1 text-xs font-medium rounded-full text-orange-900 dark:text-orange-200" style="background-color: rgba(255, 92, 0, 0.3);">
                                        <?= $tpl['type'] === 'coin' ? Lang::get('collection_type_coin') : Lang::get('collection_type_banknote') ?>
                                    </span>
                                </div>
                                
                                <!-- Header with template badge -->
                                <div class="flex items-start justify-between mb-3">
                                    <h4 class="text-base font-semibold text-gray-900 dark:text-gray-100 template-name">
                                        <?= htmlspecialchars($tpl['name']) ?>
                                    </h4>
                                    <span class="px-2 py-1 text-xs font-medium rounded-full bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400">
                                        <?= Lang::get('template') ?>
                                    </span>
                                </div>
                                
                                <?php if (!empty($tpl['description'])): ?>
                                    <p class="text-sm text-gray-500 dark:text-gray-400 mb-3 line-clamp-2 template-description"><?= htmlspecialchars($tpl['description']) ?></p>
                                <?php endif; ?>
                                
                                <div class="flex items-center justify-between mb-4">
                                    <div class="flex items-center space-x-3 text-xs text-gray-400 dark:text-gray-500">
                                        <span class="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="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"/></svg>
                                            <span><?= $tpl['subcollection_count'] ?> <?= Lang::get('subcollections') ?></span>
                                        </span>
                                        <span class="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><?= $tpl['item_count'] ?> <?= Lang::get('items') ?></span>
                                        </span>
                                    </div>
                                    <span class="text-xs text-gray-400 template-owner"><?= Lang::get('by') ?> <?= htmlspecialchars($tpl['owner_name']) ?></span>
                                </div>
                                
                                <form method="POST" action="<?= APP_URL ?>/templates/<?= $tpl['id'] ?>/clone" onsubmit="importTemplate(<?= $tpl['id'] ?>, this.querySelector('button')); return false;">
                                    <input type="hidden" name="csrf_token" value="<?= Session::getCsrfToken() ?>">
                                    <button type="submit" class="w-full btn-gradient btn-gradient-blue btn-gradient-sm">
                                        <?= Lang::get('clone_template') ?>
                                    </button>
                                </form>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Loading Modal -->
<div id="loadingModal" class="fixed inset-0 bg-black/50 z-50 hidden flex items-center justify-center p-4" role="dialog" aria-modal="true" aria-label="<?= Lang::get('import_template') ?>">
    <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-8 max-w-md w-full text-center">
        <div class="flex flex-col items-center space-y-4">
            <div class="relative">
                <div class="w-16 h-16 border-4 border-gray-200 dark:border-gray-600 border-t-primary-600 rounded-full animate-spin"></div>
                <div class="absolute inset-0 flex items-center justify-center">
                    <svg class="w-8 h-8 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/>
                    </svg>
                </div>
            </div>
            <div>
                <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">Importing Template</h3>
                <p class="text-sm text-gray-500 dark:text-gray-400">Please wait while we import the template and create your collection...</p>
            </div>
        </div>
    </div>
</div>

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

function showCollectionTypePopup() {
    var modal = document.getElementById('collectionTypeModal');
    modal.classList.remove('hidden');
    document.body.style.overflow = 'hidden';
    trapFocus(modal);
}

function closeCollectionTypePopup() {
    var modal = document.getElementById('collectionTypeModal');
    releaseFocus(modal);
    modal.classList.add('hidden');
    document.body.style.overflow = '';
}

function showTemplatesPopup() {
    var modal = document.getElementById('templatesModal');
    modal.classList.remove('hidden');
    document.body.style.overflow = 'hidden';
    trapFocus(modal);
    setTimeout(() => {
        document.getElementById('templateSearch').focus();
    }, 100);
}

function closeTemplatesPopup() {
    var modal = document.getElementById('templatesModal');
    releaseFocus(modal);
    modal.classList.add('hidden');
    document.body.style.overflow = '';
    document.getElementById('templateSearch').value = '';
    filterTemplates('');
}

function filterTemplates(query) {
    const templateItems = document.querySelectorAll('.template-item');
    const grid = document.getElementById('templatesGrid');
    const container = document.getElementById('templatesContainer');
    const lowerQuery = query.toLowerCase().trim();
    
    if (!lowerQuery) {
        // Show all templates
        templateItems.forEach(item => {
            item.style.display = '';
            item.classList.remove('opacity-50', 'scale-95');
        });
        return;
    }
    
    let visibleCount = 0;
    templateItems.forEach(item => {
        const name = item.dataset.name || '';
        const description = item.dataset.description || '';
        const type = item.dataset.type || '';
        const owner = item.dataset.owner || '';
        
        const matches = name.includes(lowerQuery) || 
                       description.includes(lowerQuery) || 
                       type.includes(lowerQuery) || 
                       owner.includes(lowerQuery);
        
        if (matches) {
            item.style.display = '';
            item.classList.remove('opacity-50', 'scale-95');
            visibleCount++;
        } else {
            item.style.display = 'none';
        }
    });
    
    // Show no results message if needed
    if (visibleCount === 0 && grid) {
        if (!document.getElementById('noResultsMessage')) {
            const noResultsDiv = document.createElement('div');
            noResultsDiv.id = 'noResultsMessage';
            noResultsDiv.className = 'text-center py-12 col-span-full';
            noResultsDiv.innerHTML = `
                <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="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
                <p class="text-gray-500 dark:text-gray-400">${LANG_NO_TEMPLATES.replace('{query}', query)}</p>
            `;
            grid.appendChild(noResultsDiv);
        }
    } else {
        const noResultsMsg = document.getElementById('noResultsMessage');
        if (noResultsMsg) {
            noResultsMsg.remove();
        }
    }
}

// Search functionality
document.addEventListener('DOMContentLoaded', function() {
    // Template search
    const templateSearchInput = document.getElementById('templateSearch');
    if (templateSearchInput) {
        let templateSearchTimeout;
        
        templateSearchInput.addEventListener('input', function(e) {
            clearTimeout(templateSearchTimeout);
            const query = e.target.value;
            
            // Debounce search for better performance
            templateSearchTimeout = setTimeout(() => {
                filterTemplates(query);
            }, 150);
        });
        
        // Clear search on Escape key when focused
        templateSearchInput.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                e.target.value = '';
                filterTemplates('');
            }
        });
    }
    
    // User search
    const userSearchInput = document.getElementById('userSearch');
    if (userSearchInput) {
        let userSearchTimeout;
        
        userSearchInput.addEventListener('input', function(e) {
            clearTimeout(userSearchTimeout);
            const query = e.target.value;
            
            // Debounce search for better performance
            userSearchTimeout = setTimeout(() => {
                searchUsers(query);
            }, 300);
        });
        
        // Clear search on Escape key when focused
        userSearchInput.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                e.target.value = '';
                searchUsers('');
            }
        });
    }
});

function createCollection(type) {
    closeCollectionTypePopup();
    window.location.href = '<?= APP_URL ?>/collections/create?type=' + type;
}

// Share Modal Functions
function showShareModal(collectionId, collectionName) {
    currentCollectionId = collectionId;
    document.getElementById('shareCollectionName').textContent = collectionName;
    var modal = document.getElementById('shareModal');
    modal.classList.remove('hidden');
    document.body.style.overflow = 'hidden';
    trapFocus(modal);
    
    // 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() {
    var modal = document.getElementById('shareModal');
    releaseFocus(modal);
    modal.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>
            <?= Lang::get('home_searching') ?>...
        </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">
                    <?= Lang::get('home_search_error') ?>
                </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"><?= Lang::get('home_no_selected_users') ?></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('<?= Lang::get('home_enter_email_address') ?>', '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(`<?= Lang::get('home_invalid_email_format') ?>`.replace('{email}', email), 'error');
                return;
            }
        }
        
        // Send via email
        shareViaEmail(emails, message, currentCollectionId);
    } else {
        if (selectedUsersList.length === 0) {
            showNotification('<?= Lang::get('home_select_at_least_one_user') ?>', 'error');
            return;
        }
        
        // Send to users via AJAX
        shareWithUsers(selectedUsersList, currentCollectionId);
    }
    
    closeShareModal();
}

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>
        <?= Lang::get('home_sending') ?>...
    `;
    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('<?= Lang::get('home_collection_shared_success') ?>', 'success');
        })
        .catch(error => {
            console.error('Share error:', error);
            showNotification('<?= Lang::get('home_share_error') ?>', 'error');
        })
        .finally(() => {
            // Restore button
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        });
}

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>
        <?= Lang::get('home_sending') ?>...
    `;
    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('<?= Lang::get('home_email_send_error') ?>', 'error');
    })
    .finally(() => {
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
}

// User search event listener
document.addEventListener('DOMContentLoaded', function() {
    const userSearchInput = document.getElementById('userSearch');
    if (userSearchInput) {
        let userSearchTimeout;
        
        userSearchInput.addEventListener('input', function(e) {
            clearTimeout(userSearchTimeout);
            const query = e.target.value;
            
            // Debounce search for better performance
            userSearchTimeout = setTimeout(() => {
                searchUsers(query);
            }, 300);
        });
        
        // Clear search on Escape key when focused
        userSearchInput.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                e.target.value = '';
                searchUsers('');
            }
        });
    }
});

// Template import function with loading spinner
function importTemplate(templateId, button) {
    const form = button.closest('form');
    const csrfToken = form.querySelector('input[name="csrf_token"]').value;
    const originalButtonText = button.innerHTML;
    
    // Show loading modal
    showLoadingModal();
    
    // Disable button and show loading state
    button.disabled = true;
    button.innerHTML = '<svg class="w-4 h-4 animate-spin inline-block mr-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> Importing...';
    
    // Submit form via fetch to show loading state
    fetch(`<?= APP_URL ?>/templates/${templateId}/clone`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `csrf_token=${encodeURIComponent(csrfToken)}`
    })
    .then(response => {
        if (response.redirected) {
            // Redirect to the new location
            window.location.href = response.url;
            return;
        }
        throw new Error('Import failed');
    })
    .catch(error => {
        console.error('Error:', error);
        hideLoadingModal();
        button.disabled = false;
        button.innerHTML = originalButtonText;
        showNotification('<?= addslashes(Lang::get('error')) ?>', 'error');
    });
}

// Loading modal functions
function showLoadingModal() {
    document.getElementById('loadingModal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
}

function hideLoadingModal() {
    document.getElementById('loadingModal').classList.add('hidden');
    document.body.style.overflow = '';
}

// Close on Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeCollectionTypePopup();
        closeTemplatesPopup();
        closeShareModal();
    }
});

</script>

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