<?php
$stats = TranscodeManager::getStats();
$filter = trim($_GET['filter'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$queue = TranscodeManager::getVideoQueue($filter, $page, 50);
$videos = $queue['videos'];
$totalPages = $queue['pages'];
$total = $queue['total'];
$ic = 'w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none';
$baseUrl = '/admin/settings?tab=transcode&sub=queue';
?>

<div class="space-y-4">

    <div class="flex items-center gap-2 flex-wrap">
        <?php
        $filters = [
            '' => ['label' => 'All', 'count' => $stats['pending'] + $stats['processing'] + $stats['completed'] + $stats['failed'], 'key' => 'all'],
            'pending' => ['label' => 'Pending', 'count' => $stats['pending'], 'key' => 'pending'],
            'processing' => ['label' => 'Processing', 'count' => $stats['processing'], 'key' => 'processing'],
            'completed' => ['label' => 'Completed', 'count' => $stats['completed'], 'key' => 'completed'],
            'failed' => ['label' => 'Failed', 'count' => $stats['failed'], 'key' => 'failed'],
        ];
        foreach ($filters as $fk => $fv):
            $active = $filter === $fk;
        ?>
        <a href="<?= $baseUrl ?><?= $fk !== '' ? '&filter=' . $fk : '' ?>" class="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-lg transition-colors <?= $active ? 'bg-primary-600 text-white' : 'bg-white text-gray-600 border border-gray-200 hover:bg-gray-50' ?>">
            <?= $fv['label'] ?>
            <span id="tqCount<?= $fv['key'] ?>" class="<?= $active ? 'bg-white/20' : 'bg-gray-100 text-gray-500' ?> px-1.5 py-0.5 rounded-full text-[10px] font-bold"><?= number_format($fv['count']) ?></span>
        </a>
        <?php endforeach; ?>
        <?php $failedJobCount = (int)Database::fetchOne("SELECT COUNT(*) as c FROM transcode_jobs WHERE status = 'failed'")['c']; ?>
        <?php if ($failedJobCount > 0): ?>
        <form method="POST" action="/admin/settings" class="inline ml-auto">
            <?= Router::csrfField() ?>
            <input type="hidden" name="_tab" value="transcode">
            <input type="hidden" name="_sub" value="queue">
            <input type="hidden" name="_action" value="retry_failed">
            <button type="submit" class="inline-flex items-center gap-1 px-2.5 py-1 text-xs font-medium text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition-colors border border-red-200">
                <i class="fa-solid fa-rotate-right" style="font-size:9px"></i> Retry <?= $failedJobCount ?> failed job<?= $failedJobCount > 1 ? 's' : '' ?>
            </button>
        </form>
        <?php endif; ?>
    </div>

    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
        <div id="queueEmpty" class="text-center py-8 text-gray-400 text-sm<?= empty($videos) ? '' : ' hidden' ?>">No videos<?= $filter ? ' matching this filter' : ' in queue' ?>.</div>
        <div id="queueTableWrap"<?= empty($videos) ? ' class="hidden"' : '' ?>>
        <table class="w-full text-sm">
            <thead class="bg-gray-50 border-b border-gray-200"><tr>
                <th class="px-3 py-2 text-left text-[10px] font-semibold uppercase tracking-wider text-gray-400" style="width:40%">Video</th>
                <th class="px-3 py-2 text-left text-[10px] font-semibold uppercase tracking-wider text-gray-400">Formats</th>
                <th class="px-3 py-2 text-right text-[10px] font-semibold uppercase tracking-wider text-gray-400 hide-mobile" style="width:80px">Progress</th>
                <th class="px-3 py-2" style="width:40px"></th>
            </tr></thead>
            <tbody class="divide-y divide-gray-50" id="queueTbody">
                <?php foreach ($videos as $v):
                    $total_j = (int)$v['cnt_total'];
                    $done = (int)$v['cnt_completed'];
                    $pct = $total_j > 0 ? round($done / $total_j * 100) : 0;
                    $hasProcessing = (int)$v['cnt_processing'] > 0;
                    $hasFailed = (int)$v['cnt_failed'] > 0;
                    $allDone = $done === $total_j;
                    $vid = (int)$v['video_id'];
                ?>
                <tr class="hover:bg-gray-50 transition-colors">
                    <td class="px-3 py-2">
                        <div class="flex items-center gap-2 min-w-0">
                            <span class="w-1.5 h-1.5 rounded-full shrink-0 <?= $hasFailed ? 'bg-red-500' : ($hasProcessing ? 'bg-blue-500 animate-pulse' : ($allDone ? 'bg-green-500' : 'bg-gray-300')) ?>"></span>
                            <span class="text-sm text-gray-900 truncate"><?= htmlspecialchars($v['video_title'] ?? '#' . $vid) ?></span>
                        </div>
                    </td>
                    <td class="px-3 py-2">
                        <div class="flex items-center gap-1 flex-wrap">
                            <?php foreach ($v['tasks'] as $t):
                                $isDone = $t['status'] === 'completed';
                                $isActive = $t['status'] === 'processing';
                                $isFail = $t['status'] === 'failed';
                                $cls = $isDone ? 'bg-green-100 text-green-700' : ($isActive ? 'bg-blue-100 text-blue-700' : ($isFail ? 'bg-red-100 text-red-700' : 'bg-gray-100 text-gray-400'));
                                 
                                 
                                if ($t['task'] === 'source') $cls = ($isDone ? 'bg-emerald-600 text-white' : ($isActive ? 'bg-blue-600 text-white' : ($isFail ? 'bg-red-600 text-white' : 'bg-indigo-600 text-white'))) . ' font-bold';
                            ?>
                            <span class="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-semibold <?= $cls ?>">
                                <?php if ($isActive): ?><span class="w-1 h-1 rounded-full bg-blue-500 animate-pulse"></span><?php endif; ?>
                                <?php if ($isDone): ?><i class="fa-solid fa-check" style="font-size:7px"></i><?php endif; ?>
                                <?php if ($isFail): ?><i class="fa-solid fa-xmark" style="font-size:7px"></i><?php endif; ?>
                                <?php if ($t['task'] === 'source'): ?><span style="font-size:9px;line-height:1" title="Original / source resolution">&#9733;</span> <?= ($v['source_height'] ?? 0) > 0 ? $v['source_height'] . 'P' : 'SOURCE' ?><?php else: ?><?= strtoupper($t['task']) ?><?php endif; ?><?php if ($isActive): ?><?php $stg = $t['stage'] ?? null; if ($stg === 'downloading'): ?> <i class="fa-solid fa-download" style="font-size:7px"></i><?php elseif ($stg === 'uploading'): ?> <i class="fa-solid fa-upload" style="font-size:7px"></i><?php endif; ?><?php if ($t['progress'] > 0): ?> <?= $t['progress'] ?>%<?php endif; ?><?php endif; ?>
                            </span>
                            <?php endforeach; ?>
                        </div>
                    </td>
                    <td class="px-3 py-2 text-right hide-mobile">
                        <?php if ($allDone): ?>
                            <span class="text-[10px] font-medium text-green-600">Done</span>
                        <?php else: ?>
                            <div class="flex items-center gap-1.5 justify-end">
                                <div class="w-12 h-1.5 bg-gray-100 rounded-full overflow-hidden">
                                    <div class="h-full rounded-full <?= $hasFailed ? 'bg-red-400' : 'bg-blue-500' ?>" style="width:<?= $pct ?>%"></div>
                                </div>
                                <span class="text-[10px] text-gray-400 w-8"><?= $pct ?>%</span>
                            </div>
                        <?php endif; ?>
                    </td>
                    <td class="px-3 py-2 text-right">
                        <button type="button" onclick="tqOpen(<?= $vid ?>)" class="px-2 py-1 text-[10px] font-medium text-gray-500 bg-gray-50 border border-gray-200 rounded hover:bg-gray-100 hover:text-gray-700 transition-colors" title="View details">
                            <i class="fa-solid fa-terminal" style="font-size:9px"></i>
                        </button>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <?php if ($totalPages > 1): ?>
        <div class="px-3 py-2.5 border-t border-gray-200 flex items-center justify-between">
            <span class="text-[10px] text-gray-400"><?= number_format($total) ?> videos &middot; page <?= $page ?>/<?= $totalPages ?></span>
            <div class="flex gap-1">
                <?php if ($page > 1): ?><a href="<?= $baseUrl ?>&filter=<?= $filter ?>&page=<?= $page - 1 ?>" class="px-2 py-1 text-[10px] font-medium text-gray-600 bg-gray-100 rounded hover:bg-gray-200">&laquo;</a><?php endif; ?>
                <?php
                $start = max(1, $page - 3);
                $end = min($totalPages, $page + 3);
                for ($p = $start; $p <= $end; $p++): ?>
                <a href="<?= $baseUrl ?>&filter=<?= $filter ?>&page=<?= $p ?>" class="px-2 py-1 text-[10px] font-medium rounded <?= $p === $page ? 'bg-primary-600 text-white' : 'text-gray-600 bg-gray-100 hover:bg-gray-200' ?>"><?= $p ?></a>
                <?php endfor; ?>
                <?php if ($page < $totalPages): ?><a href="<?= $baseUrl ?>&filter=<?= $filter ?>&page=<?= $page + 1 ?>" class="px-2 py-1 text-[10px] font-medium text-gray-600 bg-gray-100 rounded hover:bg-gray-200">&raquo;</a><?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
        </div>
    </div>

</div>


<div id="tqModal" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)tqClose()">
    <div class="fixed inset-0 bg-black/60"></div>
    <div class="relative bg-gray-900 rounded-xl shadow-2xl w-full max-w-2xl max-h-[80vh] flex flex-col" onclick="event.stopPropagation()">
        <div class="flex items-center justify-between px-4 py-3 border-b border-gray-700">
            <div class="flex items-center gap-2 min-w-0">
                <span class="text-green-400 text-xs font-mono">$</span>
                <span id="tqModalTitle" class="text-sm font-medium text-gray-200 truncate">Transcode Jobs</span>
            </div>
            <div class="flex items-center gap-2">
                <span id="tqLiveBadge" class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-bold bg-red-600 text-white"><span class="w-1.5 h-1.5 rounded-full bg-white animate-pulse"></span>LIVE</span>
                <button type="button" onclick="tqClose()" class="text-gray-500 hover:text-white text-lg leading-none transition-colors">&times;</button>
            </div>
        </div>
        <div id="tqModalBody" class="flex-1 overflow-y-auto p-4 font-mono text-[12px] leading-relaxed text-gray-300 whitespace-pre">
            <span class="text-gray-500">Loading...</span>
        </div>
    </div>
</div>

<script>
var _tqVid = 0, _tqInterval = null;

function tqOpen(vid) {
    _tqVid = vid;
    document.getElementById('tqModal').classList.remove('hidden');
    tqFetch(vid);
    _tqInterval = setInterval(function() { tqFetch(vid); }, 2000);
}

function tqClose() {
    document.getElementById('tqModal').classList.add('hidden');
    if (_tqInterval) { clearInterval(_tqInterval); _tqInterval = null; }
    _tqVid = 0;
}

function tqRefresh() { if (_tqVid) tqFetch(_tqVid); }

function tqFetch(vid) {
    fetch('/admin/settings/transcode-jobs?video_id=' + vid, {credentials:'same-origin'})
    .then(function(r) { return r.json(); })
    .then(function(data) {
        if (data.error) {
            document.getElementById('tqModalBody').innerHTML = '<span class="text-red-400">Error: ' + esc(data.error) + '</span>';
            return;
        }
        document.getElementById('tqModalTitle').textContent = data.title;
        var out = [];
        out.push('<span class="text-green-400">$</span> <span class="text-gray-400">transcode-status</span> <span class="text-gray-600">--video-id=' + vid + '</span>');
        out.push('');

        var done = 0, total = data.jobs.length;

        data.jobs.forEach(function(j) {
            var color = {pending:'text-gray-500',processing:'text-cyan-400',completed:'text-green-400',failed:'text-red-400'}[j.status] || 'text-gray-500';
            var icon = {pending:'⏳',processing:'⚡',completed:'✅',failed:'❌'}[j.status] || '?';
            if (j.status === 'completed') done++;

            var line = icon + '  ';
            line += '<span class="text-gray-600 text-xs">#' + j.id + '</span> ';
            var jLabel = (j.task === 'source') ? ((data.source_height > 0 ? data.source_height + 'P (source)' : 'SOURCE')) : j.task.toUpperCase();
            line += '<span class="text-white font-bold">' + jLabel + '</span>';
            var pad = 12 - jLabel.length; if (pad > 0) line += ' '.repeat(pad);
            line += '<span class="' + color + '">' + j.status + '</span>';
            var pad2 = 14 - j.status.length; if (pad2 > 0) line += ' '.repeat(pad2);

            if (j.worker) {
                line += '<span class="text-purple-400"><i class="fa-solid fa-server" style="font-size:9px"></i> ' + esc(j.worker) + '</span>';
                var pad3 = 20 - j.worker.length; if (pad3 > 0) line += ' '.repeat(Math.max(2, pad3));
            } else {
                line += '<span class="text-gray-600">waiting</span>' + ' '.repeat(15);
            }

            if (j.started_at && j.completed_at) {
                var dur = Math.round((new Date(j.completed_at) - new Date(j.started_at)) / 1000);
                line += '<span class="text-gray-500">' + fmtDur(dur) + '</span>';
            } else if (j.started_at) {
                var elapsed = Math.round((Date.now() - new Date(j.started_at).getTime()) / 1000);
                var stageLabel = j.stage ? '  <span class="text-gray-500">[' + j.stage + ']</span>' : '';
                var pctStr = (j.progress > 0 && j.progress < 100) ? '  <span class="text-cyan-400 font-bold">' + j.progress + '%</span>' : '';
                line += '<span class="text-yellow-400">' + fmtDur(elapsed) + ' ⏱</span>' + stageLabel + pctStr;
            }

            if (j.retry_count > 0) {
                line += '  <span class="text-orange-400">[retry ' + j.retry_count + '/3]</span>';
            }
            out.push(line);
            if (j.error_message && (j.status === 'failed' || j.status === 'pending')) {
                var errColor = j.status === 'failed' ? 'text-red-500/80' : 'text-orange-400/80';
                var parts = j.error_message.split(' | ');
                out.push('    <span class="' + errColor + '">└─ ' + esc(parts[0]) + '</span>');
                for (var p = 1; p < parts.length; p++) {
                    out.push('    <span class="text-gray-500">   ' + esc(parts[p]) + '</span>');
                }
            }
        });

        out.push('');
        out.push('<span class="text-gray-600">─────────────────────────────────────────────────</span>');

        var pct = total > 0 ? Math.round(done / total * 100) : 0;
        var barLen = 30;
        var filled = Math.round(barLen * pct / 100);
        var bar = '<span class="text-green-400">' + '█'.repeat(filled) + '</span><span class="text-gray-700">' + '░'.repeat(barLen - filled) + '</span>';
        out.push(bar + '  <span class="text-white font-bold">' + pct + '%</span> <span class="text-gray-500">(' + done + '/' + total + ' jobs)</span>');

        var allDone = done === total && total > 0;
        var badge = document.getElementById('tqLiveBadge');
        if (allDone) {
            out.push('');
            out.push('<span class="text-green-400 font-bold">✓ All jobs completed.</span>');
            if (_tqInterval) { clearInterval(_tqInterval); _tqInterval = null; }
            badge.className = 'inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-bold bg-green-600 text-white';
            badge.innerHTML = '<i class="fa-solid fa-check" style="font-size:8px"></i> DONE';
        } else {
            badge.className = 'inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-bold bg-red-600 text-white';
            badge.innerHTML = '<span class="w-1.5 h-1.5 rounded-full bg-white animate-pulse"></span>LIVE';
        }

        document.getElementById('tqModalBody').innerHTML = out.join('\n');
    })
    .catch(function() {
        document.getElementById('tqModalBody').innerHTML = '<span class="text-red-400">Network error — retrying...</span>';
    });
}

function fmtDur(s) {
    if (s < 60) return s + 's';
    var m = Math.floor(s / 60); s = s % 60;
    if (m < 60) return m + 'm ' + s + 's';
    var h = Math.floor(m / 60); m = m % 60;
    return h + 'h ' + m + 'm';
}

function esc(s) { var d = document.createElement('div'); d.textContent = s; return d.innerHTML; }


var _queueFilter = '<?= $filter ?>';
var _queuePage = <?= $page ?>;
function tqSetCount(id, value) {
    var el = document.getElementById(id);
    if (el) el.textContent = Number(value || 0).toLocaleString();
}

function tqToggle(id, show) {
    var el = document.getElementById(id);
    if (el) el.classList.toggle('hidden', !show);
}

function refreshQueueStats(s) {
    if (!s) return;
    var pending = s.pending || 0, processing = s.processing || 0;
    tqSetCount('tqCountall', pending + processing + (s.completed || 0) + (s.failed || 0));
    tqSetCount('tqCountpending', pending);
    tqSetCount('tqCountprocessing', processing);
    tqSetCount('tqCountcompleted', s.completed);
    tqSetCount('tqCountfailed', s.failed);
    var active = pending + processing;
    tqSetCount('tqActivePillCount', active);
    tqSetCount('tqSubTabBadge', active);
    tqToggle('tqActivePill', active > 0);
    tqToggle('tqSubTabBadge', active > 0);
}

function refreshQueue() {
    fetch('/admin/settings/transcode-queue-data?filter=' + encodeURIComponent(_queueFilter) + '&page=' + _queuePage, {credentials:'same-origin'})
    .then(function(r) {
        if (!r.ok) throw new Error('HTTP ' + r.status);
        return r.json();
    })
    .then(function(d) {
        refreshQueueStats(d.stats);
        var tbody = document.getElementById('queueTbody');
        if (!tbody || !d.queue || !d.queue.videos) return;
        var videos = d.queue.videos;
        tqToggle('queueEmpty', videos.length === 0);
        tqToggle('queueTableWrap', videos.length > 0);
        var html = '';
        videos.forEach(function(v) {
            var total = v.cnt_total || 0, done = v.cnt_completed || 0;
            var pct = total > 0 ? Math.round(done / total * 100) : 0;
            var hasFail = (v.cnt_failed || 0) > 0;
            var hasProc = (v.cnt_processing || 0) > 0;
            var allDone = done === total;
            var dotCls = hasFail ? 'bg-red-500' : (hasProc ? 'bg-blue-500 animate-pulse' : (allDone ? 'bg-green-500' : 'bg-gray-300'));
            html += '<tr class="hover:bg-gray-50 transition-colors">';
            html += '<td class="px-3 py-2"><div class="flex items-center gap-2 min-w-0"><span class="w-1.5 h-1.5 rounded-full shrink-0 '+dotCls+'"></span><span class="text-sm text-gray-900 truncate">'+esc(v.video_title||'#'+v.video_id)+'</span></div></td>';
            html += '<td class="px-3 py-2"><div class="flex items-center gap-1 flex-wrap">';
            (v.tasks||[]).forEach(function(t) {
                var isDone = t.status==='completed', isActive = t.status==='processing', isFail = t.status==='failed';
                var cls = isDone?'bg-green-100 text-green-700':(isActive?'bg-blue-100 text-blue-700':(isFail?'bg-red-100 text-red-700':'bg-gray-100 text-gray-400'));
                if (t.task === 'source') cls = (isDone?'bg-emerald-600 text-white':(isActive?'bg-blue-600 text-white':(isFail?'bg-red-600 text-white':'bg-indigo-600 text-white'))) + ' font-bold';
                var icon = isActive?'<span class="w-1 h-1 rounded-full bg-blue-500 animate-pulse"></span>':(isDone?'<i class="fa-solid fa-check" style="font-size:7px"></i>':(isFail?'<i class="fa-solid fa-xmark" style="font-size:7px"></i>':''));
                var stageIcon = '';
                if (isActive && t.stage === 'downloading') stageIcon = ' <i class="fa-solid fa-download" style="font-size:7px"></i>';
                else if (isActive && t.stage === 'uploading') stageIcon = ' <i class="fa-solid fa-upload" style="font-size:7px"></i>';
                var pctTxt = (isActive && t.progress > 0) ? ' '+t.progress+'%' : '';
                var tLabel = t.task === 'source' ? ((v.source_height > 0 ? v.source_height + 'P' : 'SOURCE')) : t.task.toUpperCase();
                var srcStar = t.task === 'source' ? '<span style="font-size:9px;line-height:1">★</span> ' : '';
                html += '<span class="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-semibold '+cls+'">'+icon+srcStar+tLabel+stageIcon+pctTxt+'</span>';
            });
            html += '</div></td>';
            html += '<td class="px-3 py-2 text-right hide-mobile">';
            if (allDone) { html += '<span class="text-[10px] font-medium text-green-600">Done</span>'; }
            else { var barCls = hasFail?'bg-red-400':'bg-blue-500'; html += '<div class="flex items-center gap-1.5 justify-end"><div class="w-12 h-1.5 bg-gray-100 rounded-full overflow-hidden"><div class="h-full rounded-full '+barCls+'" style="width:'+pct+'%"></div></div><span class="text-[10px] text-gray-400 w-8">'+pct+'%</span></div>'; }
            html += '</td>';
            html += '<td class="px-3 py-2 text-right"><button type="button" onclick="tqOpen('+v.video_id+')" class="px-2 py-1 text-[10px] font-medium text-gray-500 bg-gray-50 border border-gray-200 rounded hover:bg-gray-100 hover:text-gray-700 transition-colors" title="View details"><i class="fa-solid fa-terminal" style="font-size:9px"></i></button></td>';
            html += '</tr>';
        });
        tbody.innerHTML = html;
    }).catch(function(e) {
        console.error('Transcode queue refresh failed:', e);
    });
}
setInterval(refreshQueue, 3000);
</script>
