<style>
.vtl-globe-wrap{position:relative;display:inline-flex;align-items:center}
.vtl-globe-tip{display:none;position:fixed;background:#1e293b;color:#f1f5f9;border-radius:8px;padding:8px 10px;font-size:11px;white-space:normal;max-width:340px;z-index:9999;box-shadow:0 4px 12px rgba(0,0,0,.2);line-height:1.6;pointer-events:none}
.vtl-globe-row{display:block;overflow:hidden;text-overflow:ellipsis;max-width:320px}
.vtl-globe-row b{color:#a5b4fc;margin-right:4px;font-size:10px;letter-spacing:.04em}
</style>
<script>
document.addEventListener('mouseenter',function(e){var w=e.target.closest&&e.target.closest('.vtl-globe-wrap');if(!w)return;var t=w.querySelector('.vtl-globe-tip');if(!t)return;var r=w.getBoundingClientRect();t.style.display='block';var tw=t.offsetWidth,th=t.offsetHeight;var left=r.left+r.width/2-tw/2;if(left<8)left=8;if(left+tw>window.innerWidth-8)left=window.innerWidth-tw-8;t.style.left=left+'px';t.style.top=(r.top-th-6)+'px';},true);
document.addEventListener('mouseleave',function(e){var w=e.target.closest&&e.target.closest('.vtl-globe-wrap');if(!w)return;var t=w.querySelector('.vtl-globe-tip');if(t)t.style.display='none';},true);
</script>


<?php if (!empty($showTypeFilter)):
    $typeLabels = Video::typeLabels();
    $typeTabUrl = function(string $type) use ($currentSort, $currentVideoFilter) {
        $p = [];
        if ($type !== '') $p['type'] = $type;
        if (($currentSort ?? 'name') !== 'name') $p['sort'] = $currentSort;
        if (($currentVideoFilter ?? '') !== '') $p['videos'] = $currentVideoFilter;
        return '/admin/albums/categories' . (!empty($p) ? '?' . http_build_query($p) : '');
    };
?>
<div class="mb-4 border-b border-gray-200">
    <nav class="flex gap-0 -mb-px">
        <?php $isAll = ($currentType ?? '') === ''; ?>
        <a href="<?= $typeTabUrl('') ?>" class="px-4 py-2.5 text-xs font-medium border-b-2 <?= $isAll ? 'border-primary-500 text-primary-700' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' ?> transition-colors">
            All <span class="<?= $isAll ? 'text-primary-400' : 'text-gray-400' ?>"><?= array_sum($typeCounts) ?></span>
        </a>
        <?php foreach ($availableTypes as $t): ?>
        <?php $isActive = ($currentType ?? '') === $t; ?>
        <a href="<?= $typeTabUrl($t) ?>" class="px-4 py-2.5 text-xs font-medium border-b-2 <?= $isActive ? 'border-primary-500 text-primary-700' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' ?> transition-colors whitespace-nowrap">
            <?= $typeLabels[$t] ?? ucfirst($t) ?> <span class="<?= $isActive ? 'text-primary-400' : 'text-gray-400' ?>"><?= $typeCounts[$t] ?? 0 ?></span>
        </a>
        <?php endforeach; ?>
    </nav>
</div>
<?php endif; ?>


<?php
$filterStyle = 'px-2 py-1.5 border border-gray-300 rounded-lg text-xs bg-white focus:ring-1 focus:ring-blue-500 focus:border-blue-500 outline-none appearance-none cursor-pointer';
$hasFilters = ($currentVideoFilter ?? '') !== '' || ($currentSort ?? 'name') !== 'name';
?>
<div class="mb-3 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
    <div class="flex items-center gap-3">
        <input type="text" data-search-table="album-categories-table" placeholder="Search album categories..." class="w-full sm:w-64 px-3 py-1.5 border border-gray-300 rounded-lg text-xs focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none">
        <span id="album-categories-table-count" class="hidden sm:inline text-xs text-gray-500 whitespace-nowrap"></span>
    </div>
    <div class="flex items-center gap-2 flex-wrap">
        <select onchange="adminFilter('videos',this.value)" class="<?= $filterStyle ?>">
            <option value="">All album categories</option>
            <option value="with" <?= ($currentVideoFilter ?? '') === 'with' ? 'selected' : '' ?>>With albums</option>
            <option value="empty" <?= ($currentVideoFilter ?? '') === 'empty' ? 'selected' : '' ?>>Empty (0 albums)</option>
        </select>
        <select onchange="adminFilter('sort',this.value)" class="<?= $filterStyle ?>">
            <option value="name" <?= ($currentSort ?? 'name') === 'name' ? 'selected' : '' ?>>Sort: Name</option>
            <option value="videos" <?= ($currentSort ?? 'name') === 'videos' ? 'selected' : '' ?>>Sort: Most albums</option>
            <option value="newest" <?= ($currentSort ?? 'name') === 'newest' ? 'selected' : '' ?>>Sort: Newest</option>
        </select>
        <?php if ($hasFilters): ?>
            <a href="/admin/albums/categories<?= ($currentType ?? '') !== '' ? '?type=' . urlencode($currentType) : '' ?>" class="text-xs text-red-500 hover:text-red-700 whitespace-nowrap">Clear filters</a>
        <?php endif; ?>
    </div>
</div>


<div id="bulkBar" class="hidden mb-2 px-3 py-2 bg-primary-50 border border-primary-200 rounded-lg flex items-center gap-3 text-xs">
    <span class="font-medium text-primary-700"><span id="bulkCount">0</span> selected</span>
    <button type="button" onclick="AT.translateSelected()" class="inline-flex items-center gap-1 px-2.5 py-1 bg-sky-600 text-white text-xs font-medium rounded hover:bg-sky-700 transition-colors">
        <i class="fa-solid fa-language"></i>
        Translate
    </button>
    <button type="button" onclick="bulkDeleteSelected()" class="inline-flex items-center gap-1 px-2.5 py-1 bg-red-600 text-white text-xs font-medium rounded hover:bg-red-700 transition-colors">
        <svg class="w-3 h-3" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" 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>
        Delete
    </button>
    <button type="button" onclick="bulkClearAll()" class="text-xs text-gray-500 hover:text-gray-700">Clear</button>
</div>


<div class="bg-white rounded-lg shadow-sm border border-gray-200">
    <div class="overflow-x-auto">
        <table id="album-categories-table" class="w-full" data-bulk-delete="/admin/albums/categories/bulk-delete" data-bulk-noun="album category" data-bulk-noun-plural="album categories">
            <thead>
                <tr class="bg-gray-50">
                    <th class="px-2 py-2 w-8"><input type="checkbox" data-bulk-select-all class="rounded border-gray-300 text-primary-600 focus:ring-primary-500"></th>
                    <th class="px-2 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-gray-500">Thumb</th>
                    <th class="px-2 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-gray-500">Name</th>
                    <th class="hide-mobile px-2 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-gray-500">Slug</th>
                    <th class="px-2 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-gray-500">Albums</th>
                    <th class="px-2 py-2 text-right text-[11px] font-semibold uppercase tracking-wider text-gray-500">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-100">
                <?php if (!empty($categories)): ?>
                    <?php foreach ($categories as $category): ?>
                        <tr class="hover:bg-gray-50 transition-colors" data-searchable="<?= htmlspecialchars($category['name'] . ' ' . $category['slug']) ?>">
                            <td class="px-2 py-1.5"><input type="checkbox" data-bulk-id="<?= (int)$category['id'] ?>" class="rounded border-gray-300 text-primary-600 focus:ring-primary-500"></td>
                            <td class="px-2 py-1.5">
                                <?php
                                    $catThumbUrl = '';
                                    if (!empty($category['thumbnail'])) {
                                        $catThumbUrl = str_starts_with($category['thumbnail'], 'http') ? $category['thumbnail'] : '/uploads/thumbnails/' . $category['thumbnail'];
                                    } elseif (!empty($category['_fallback_cover'])) {
                                        $catThumbUrl = $category['_fallback_cover'];
                                    }
                                ?>
                                <div class="cat-thumb-wrap cursor-pointer" onclick="this.querySelector('input[type=file]').click()" title="Click to change thumbnail">
                                    <?php if (!empty($catThumbUrl)): ?>
                                        <img src="<?= htmlspecialchars($catThumbUrl) ?>" alt="" class="w-8 h-8 rounded object-cover cat-thumb-img" data-zoom-src="<?= htmlspecialchars($catThumbUrl) ?>" data-cat-id="<?= (int)$category['id'] ?>">
                                    <?php else: ?>
                                        <div class="w-8 h-8 rounded bg-gray-100 flex items-center justify-center cat-thumb-img" data-cat-id="<?= (int)$category['id'] ?>">
                                            <svg class="w-4 h-4 text-gray-300" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M6.827 6.175A2.31 2.31 0 015.186 7.23c-.38.054-.757.112-1.134.175C2.999 7.58 2.25 8.507 2.25 9.574V18a2.25 2.25 0 002.25 2.25h15A2.25 2.25 0 0021.75 18V9.574c0-1.067-.75-1.994-1.802-2.169a47.865 47.865 0 00-1.134-.175 2.31 2.31 0 01-1.64-1.055l-.822-1.316a2.192 2.192 0 00-1.736-1.039 48.774 48.774 0 00-5.232 0 2.192 2.192 0 00-1.736 1.039l-.821 1.316z"/><path stroke-linecap="round" stroke-linejoin="round" d="M16.5 12.75a4.5 4.5 0 11-9 0 4.5 4.5 0 019 0z"/></svg>
                                        </div>
                                    <?php endif; ?>
                                    <input type="file" accept="image/*" class="hidden" onchange="catThumbUpload(this, <?= (int)$category['id'] ?>)">
                                </div>
                            </td>
                            <td class="px-2 py-1.5 text-xs">
                                <div class="flex items-center gap-1.5">
                                    <a href="/admin/albums/categories/<?= (int)$category['id'] ?>/edit" class="text-blue-600 hover:text-blue-800 font-medium"><?= htmlspecialchars($category['name']) ?></a>
                                    <?php $cTrans = $catTranslations[(int)$category['id']] ?? []; ?>
                                    <?php if (!empty($cTrans)): ?>
                                    <span class="vtl-globe-wrap">
                                        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#6366f1" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="cursor:help;flex-shrink:0"><circle cx="12" cy="12" r="10" fill="transparent"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
                                        <span class="vtl-globe-tip"><?php foreach ($cTrans as $lc => $lt) { echo '<span class="vtl-globe-row"><b>' . strtoupper(htmlspecialchars($lc)) . '</b> ' . htmlspecialchars(mb_strimwidth($lt, 0, 60, '...')) . '</span>'; } ?></span>
                                    </span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td class="hide-mobile px-2 py-1.5 text-xs">
                                <code class="text-[11px] bg-gray-100 text-gray-700 px-1.5 py-0.5 rounded"><?= htmlspecialchars($category['slug']) ?></code>
                            </td>
                            <td class="px-2 py-1.5 text-xs"><?php $ac=(int)($category['album_count'] ?? 0); ?><span class="<?= $ac>0 ? 'text-indigo-600 font-medium' : 'text-gray-400' ?>"><?= $ac ?></span></td>
                            <td class="px-2 py-1.5 text-xs text-right">
                                <div class="flex items-center justify-end gap-1">
                                    <button type="button" onclick="AT.translateOne(<?= (int)$category['id'] ?>)" class="px-2 py-1 text-[11px] font-medium rounded border bg-white text-sky-600 border-sky-200 hover:bg-sky-50" title="Translate this one with AI"><i class="fa-solid fa-language"></i></button>
                                    <a href="/admin/albums/categories/<?= (int)$category['id'] ?>/edit" class="px-2 py-1 text-[11px] font-medium rounded border bg-white text-gray-600 border-gray-300 hover:bg-gray-50">Edit</a>
                                    <form method="POST" action="/admin/albums/categories/<?= (int)$category['id'] ?>/delete" onsubmit="return confirm('Delete this album category?');">
                                        <?= Router::csrfField() ?>
                                        <button type="submit" class="px-2 py-1 text-[11px] font-medium rounded border bg-red-600 text-white border-red-600 hover:bg-red-700">Del</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="6" class="text-center py-8 text-gray-500 text-xs">No album categories found.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require APP_ROOT . '/templates/admin/_admin_pagination.php'; ?>


<script>
function catThumbUpload(input, catId) {
    if (!input.files || !input.files[0]) return;
    var fd = new FormData();
    fd.append('thumbnail', input.files[0]);
    fd.append('csrf_token', '<?= Router::csrfToken() ?>');
    var wrap = input.closest('.cat-thumb-wrap');
    wrap.style.opacity = '0.5';
    fetch('/admin/albums/categories/' + catId + '/update-thumbnail', {
        method: 'POST',
        headers: { 'X-CSRF-TOKEN': '<?= Router::csrfToken() ?>' },
        body: fd,
        credentials: 'same-origin'
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
        wrap.style.opacity = '1';
        if (data.success && data.thumbnail) {
            var thumbUrl = data.thumbnail.startsWith('http') ? data.thumbnail : '/uploads/thumbnails/' + data.thumbnail;
            var existing = wrap.querySelector('.cat-thumb-img');
            if (existing.tagName === 'IMG') {
                existing.src = thumbUrl;
                existing.setAttribute('data-zoom-src', thumbUrl);
            } else {
                var img = document.createElement('img');
                img.src = thumbUrl;
                img.className = 'w-8 h-8 rounded object-cover cat-thumb-img';
                img.setAttribute('data-zoom-src', thumbUrl);
                img.setAttribute('data-cat-id', catId);
                existing.replaceWith(img);
            }
        }
    })
    .catch(function() {
        wrap.style.opacity = '1';
        alert('Upload failed. Please try again.');
    });
    input.value = '';
}
function adminFilter(k,v){var u=new URL(location);var d={'sort':'name'};if(v&&v!==(d[k]||''))u.searchParams.set(k,v);else u.searchParams.delete(k);u.searchParams.delete('page');location=u;}
</script>

<?php $skipMpBanner = true; $isConnected = CatalogueClient::isConfigured(); if (!defined('AT_MP_MODAL')) { define('AT_MP_MODAL', 1); include __DIR__ . '/_mp_modal.php'; } ?>
<?php $aiTranslateEntityType = 'album_category'; $aiTranslateTypeFilter = $currentType ?? ''; include __DIR__ . '/_ai_translate_modal.php'; ?>
