<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}
.vtl-globe-row b{color:#a5b4fc;margin-right:4px;font-size:10px;letter-spacing:.04em}
.vtl-globe-row{overflow:hidden;text-overflow:ellipsis;max-width:320px}
</style>
<script>
document.addEventListener('mouseenter',function(e){
    var wrap=e.target.closest&&e.target.closest('.vtl-globe-wrap');
    if(!wrap)return;
    var tip=wrap.querySelector('.vtl-globe-tip');
    if(!tip)return;
    var r=wrap.getBoundingClientRect();
    tip.style.display='block';
    var tw=tip.offsetWidth,th=tip.offsetHeight;
    var left=r.left+r.width/2-tw/2;
    var top=r.top-th-6;
    if(left<4)left=4;
    if(left+tw>window.innerWidth-4)left=window.innerWidth-tw-4;
    if(top<4){top=r.bottom+6;}
    tip.style.left=left+'px';
    tip.style.top=top+'px';
},true);
document.addEventListener('mouseleave',function(e){
    var wrap=e.target.closest&&e.target.closest('.vtl-globe-wrap');
    if(!wrap)return;
    var tip=wrap.querySelector('.vtl-globe-tip');
    if(tip)tip.style.display='none';
},true);
</script>


<?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 = ($currentStatus ?? '') !== '' || ($currentCategory ?? 0) > 0 || ($currentPerformer ?? 0) > 0 || ($currentThumbnail ?? '') !== '' || ($currentSort ?? 'newest') !== 'newest' || ($currentType ?? '') !== '';
?>
<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="videos-table" placeholder="Search videos..." 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="videos-table-count" class="text-xs text-gray-500 whitespace-nowrap hidden sm:inline"></span>
    </div>
    <div class="flex items-center gap-2 flex-wrap">
        <select onchange="adminFilter('status',this.value)" class="<?= $filterStyle ?>">
            <option value="">All statuses</option>
            <option value="published" <?= ($currentStatus ?? '') === 'published' ? 'selected' : '' ?>>Published</option>
            <option value="processing" <?= ($currentStatus ?? '') === 'processing' ? 'selected' : '' ?>>Transcoding</option>
            <option value="error" <?= ($currentStatus ?? '') === 'error' ? 'selected' : '' ?>>Transcode Error</option>
            <option value="draft" <?= ($currentStatus ?? '') === 'draft' ? 'selected' : '' ?>>Draft</option>
            <option value="private" <?= ($currentStatus ?? '') === 'private' ? 'selected' : '' ?>>Private</option>
        </select>
        <select onchange="adminFilter('category',this.value)" class="<?= $filterStyle ?>">
            <option value="">All categories</option>
            <?php foreach ($filterCategories ?? [] as $fc): ?>
                <option value="<?= (int)$fc['id'] ?>" <?= ($currentCategory ?? 0) == $fc['id'] ? 'selected' : '' ?>><?= htmlspecialchars($fc['name']) ?></option>
            <?php endforeach; ?>
        </select>
        <select onchange="adminFilter('performer',this.value)" class="<?= $filterStyle ?>">
            <option value="">All pornstars</option>
            <?php foreach ($filterPerformers ?? [] as $fp): ?>
                <option value="<?= (int)$fp['id'] ?>" <?= ($currentPerformer ?? 0) == $fp['id'] ? 'selected' : '' ?>><?= htmlspecialchars($fp['name']) ?></option>
            <?php endforeach; ?>
        </select>
        <select onchange="adminFilter('thumbnail',this.value)" class="<?= $filterStyle ?>">
            <option value="">All thumbnails</option>
            <option value="yes" <?= ($currentThumbnail ?? '') === 'yes' ? 'selected' : '' ?>>With thumb</option>
            <option value="no" <?= ($currentThumbnail ?? '') === 'no' ? 'selected' : '' ?>>No thumb</option>
        </select>
        <?php if (!empty($showTypeFilter)):
            $typeLabels = Video::typeLabels();
        ?>
        <select onchange="adminFilter('type',this.value)" class="<?= $filterStyle ?>">
            <option value="">All types</option>
            <?php foreach ($availableTypes as $avType): ?>
            <option value="<?= $avType ?>" <?= ($currentType ?? '') === $avType ? 'selected' : '' ?>><?= $typeLabels[$avType] ?? ucfirst($avType) ?></option>
            <?php endforeach; ?>
        </select>
        <?php endif; ?>
        <select onchange="adminFilter('sort',this.value)" class="<?= $filterStyle ?>">
            <option value="newest" <?= ($currentSort ?? 'newest') === 'newest' ? 'selected' : '' ?>>Newest</option>
            <option value="oldest" <?= ($currentSort ?? 'newest') === 'oldest' ? 'selected' : '' ?>>Oldest</option>
            <option value="popular" <?= ($currentSort ?? 'newest') === 'popular' ? 'selected' : '' ?>>Most views</option>
            <option value="most_liked" <?= ($currentSort ?? 'newest') === 'most_liked' ? 'selected' : '' ?>>Most likes</option>
        </select>
        <?php if ($hasFilters): ?>
            <a href="/admin/videos<?= !empty($search) ? '?q=' . urlencode($search) : '' ?>" 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 text-xs">
    <div class="flex items-center gap-3" id="bulkActions">
        <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>
        <?php if ($pagination->total > $pagination->perPage): ?>
        <button type="button" id="bulkSelectAllBtn" onclick="bulkSelectAllMatching()" class="text-xs text-primary-600 hover:text-primary-800 font-medium underline" style="display:none">
            Select all <?= number_format($pagination->total) ?> matching videos
        </button>
        <?php endif; ?>
        <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 id="bulkProgress" class="hidden">
        <div class="flex items-center justify-between mb-1.5">
            <span class="font-medium text-red-700">Deleting... <span id="bulkDeleted">0</span> / <span id="bulkTotal">0</span></span>
            <span class="font-semibold text-red-700"><span id="bulkPct">0</span>%</span>
        </div>
        <div class="h-2 rounded-full bg-red-100 overflow-hidden">
            <div id="bulkProgressBar" class="h-full rounded-full bg-red-500 transition-all duration-300" style="width:0%"></div>
        </div>
        <div class="flex items-center gap-3 mt-1.5">
            <button type="button" onclick="bulkDeleteCancelJob()" class="text-xs text-red-600 hover:text-red-800 font-medium">Cancel</button>
            <span id="bulkEta" class="text-[10px] text-gray-400"></span>
        </div>
    </div>
</div>
<script>
var _bulkSelectAll = false;
var _bulkFilters = <?= json_encode([
    'search' => $search ?? '',
    'status' => $currentStatus ?? '',
    'category_id' => $currentCategory ?? 0,
    'performer_id' => $currentPerformer ?? 0,
    'has_thumbnail' => $currentThumbnail ?? '',
    'sort' => $currentSort ?? 'newest',
    'video_type' => $currentType ?? '',
]) ?>;
var _bulkTotal = <?= (int) $pagination->total ?>;
</script>


<div class="bg-white rounded-lg shadow-sm border border-gray-200">
    <div class="overflow-x-auto">
        <table id="videos-table" class="w-full" data-bulk-delete="/admin/videos/bulk-delete" data-bulk-async data-bulk-noun="video">
            <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-0 py-2 w-4"></th>
                    <th class="px-1 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-gray-500">Title</th>
                    <th class="px-2 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-gray-500 hide-mobile">Status</th>
                    <th class="px-2 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-gray-500">Views</th>
                    <th class="px-2 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-gray-500 hide-mobile">Likes</th>
                    <th class="px-2 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-gray-500 hide-mobile">Date</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($videos)): ?>
                    <?php foreach ($videos as $video): ?>
                        <tr class="hover:bg-gray-50 transition-colors" data-searchable="<?= htmlspecialchars($video['title']) ?>">
                            <td class="px-2 py-1.5"><input type="checkbox" data-bulk-id="<?= (int)$video['id'] ?>" class="rounded border-gray-300 text-primary-600 focus:ring-primary-500"></td>
                            <td class="px-2 py-1.5">
                                <?php $thumbUrl = VideoAsset::thumbUrl($video); ?>
                                <?php if ($thumbUrl !== ''): ?>
                                    <img src="<?= htmlspecialchars($thumbUrl) ?>" alt="" class="w-16 h-9 rounded object-cover" data-zoom-src="<?= htmlspecialchars($thumbUrl) ?>">
                                <?php else: ?>
                                    <div class="w-16 h-9 rounded bg-gray-200 flex items-center justify-center text-[10px] text-gray-400">No img</div>
                                <?php endif; ?>
                            </td>
                            <td class="px-0 py-1.5">
                                <?php $vTrans = $videoTranslations[(int)$video['id']] ?? []; ?>
                                <?php if (!empty($vTrans)): ?>
                                <span class="vtl-globe-wrap">
                                    <svg width="14" height="14" 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 ($vTrans 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; ?>
                            </td>
                            <td class="px-1 py-1.5 text-xs">
                                <a href="/admin/videos/<?= (int)$video['id'] ?>/edit" class="text-blue-600 hover:text-blue-800 font-medium line-clamp-1"><?= htmlspecialchars($video['title']) ?></a>
                            </td>
                            <td class="px-2 py-1.5 text-xs hide-mobile">
                                <?php if ($video['status'] === 'published'): ?>
                                    <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-green-100 text-green-800">Published</span>
                                <?php elseif ($video['status'] === 'processing'):
                                    $hasActive = (bool)Database::fetchOne("SELECT 1 FROM transcode_jobs WHERE video_id = ? AND status = 'processing' LIMIT 1", [(int)$video['id']]);
                                ?>
                                    <?php if ($hasActive): ?>
                                    <a href="/admin/settings?tab=transcode&sub=queue" class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-blue-100 text-blue-700 hover:bg-blue-200 transition-colors"><span class="w-1.5 h-1.5 rounded-full bg-blue-500 animate-pulse"></span>Transcoding</a>
                                    <?php else: ?>
                                    <a href="/admin/settings?tab=transcode&sub=queue" class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-gray-100 text-gray-500 hover:bg-gray-200 transition-colors"><i class="fa-solid fa-clock" style="font-size:8px"></i> Queued</a>
                                    <?php endif; ?>
                                <?php elseif ($video['status'] === 'error'): ?>
                                    <a href="/admin/settings?tab=transcode&sub=queue" class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-red-100 text-red-700 hover:bg-red-200 transition-colors"><i class="fa-solid fa-triangle-exclamation" style="font-size:8px"></i>Transcode Error</a>
                                <?php elseif ($video['status'] === 'draft'): ?>
                                    <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-gray-100 text-gray-600">Draft</span>
                                <?php elseif ($video['status'] === 'private'): ?>
                                    <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-yellow-100 text-yellow-800">Private</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-2 py-1.5 text-xs text-gray-600"><?= number_format((int)($video['views'] ?? 0)) ?></td>
                            <td class="px-2 py-1.5 text-xs text-gray-600 hide-mobile"><?= number_format((int)($video['likes'] ?? 0)) ?></td>
                            <td class="px-2 py-1.5 text-xs text-gray-400 hide-mobile"><?= htmlspecialchars(substr($video['created_at'] ?? '', 0, 10)) ?></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)$video['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/videos/<?= (int)$video['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/videos/<?= (int)$video['id'] ?>/delete" onsubmit="return confirm('Delete this video?');">
                                        <?= 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="9" class="text-center py-8 text-gray-500 text-xs">No videos found.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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

<script>
function adminFilter(k,v){var u=new URL(location);var d={'sort':'newest'};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 = 'video'; $aiTranslateTypeFilter = $currentType ?? ''; include __DIR__ . '/_ai_translate_modal.php'; ?>
