<!DOCTYPE html>
<html lang="en" data-bs-theme="dark">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TA Organizerr Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        :root {
            --bg-dark: #121212;
            --bg-card: #1e1e1e;
            --text-main: #e0e0e0;
            --accent-primary: #0d6efd;
            --accent-success: #198754;
            --accent-warning: #ffc107;
            --accent-danger: #dc3545;
        }

        body {
            background-color: var(--bg-dark);
            color: var(--text-main);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .card {
            background-color: var(--bg-card);
            border: 1px solid #333;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
        }

        .card-header {
            background-color: #252525;
            border-bottom: 1px solid #333;
            font-weight: 600;
        }

        .log-box {
            height: 400px;
            overflow-y: scroll;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 0.85em;
            background-color: #0d0d0d;
            color: #00ff9d;
            border: 1px solid #333;
            padding: 15px;
            border-radius: 4px;
        }

        .status-dot {
            height: 12px;
            width: 12px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 5px;
        }

        .status-green {
            background-color: var(--accent-success);
            box-shadow: 0 0 8px var(--accent-success);
        }

        .status-yellow {
            background-color: var(--accent-warning);
            box-shadow: 0 0 8px var(--accent-warning);
        }

        .status-red {
            background-color: var(--accent-danger);
            box-shadow: 0 0 8px var(--accent-danger);
        }

        .btn-xl {
            padding: 15px 20px;
            font-size: 1.2rem;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        @keyframes spin {
            100% {
                transform: rotate(360deg);
            }
        }

        .spin-anim {
            animation: spin 0.5s linear;
        }
    </style>
</head>

<body>
    <div class="container-fluid p-4" style="max-width: 1600px;">
        <header class="d-flex justify-content-between align-items-center mb-5 border-bottom pb-3"
            style="border-color: #333 !important;">
            <div class="d-flex align-items-center">
                <h1 class="display-6 mb-0 me-3"><i class="bi bi-collection-play-fill text-primary"></i> TA Organizer
                </h1>
                <span class="badge bg-secondary" id="connection-status">Connecting...</span>
            </div>
            <div>
                <button class="btn btn-outline-secondary me-2" onclick="refreshAll()">
                    <i class="bi bi-arrow-clockwise"></i> Refresh
                </button>
                <a href="/transcode" class="btn btn-outline-primary">
                    <i class="bi bi-film"></i> Transcode Manager
                </a>
            </div>
        </header>

        <!-- Stats Row -->
        <div class="row mb-4 g-3">
            <div class="col-md-3">
                <div class="card h-100 border-primary border-opacity-25">
                    <div class="card-body text-center">
                        <h6 class="card-subtitle mb-2 text-muted text-uppercase">Total Videos</h6>
                        <h2 class="card-title display-4 text-primary" id="stat-total">0</h2>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card h-100 border-success border-opacity-25">
                    <div class="card-body text-center">
                        <h6 class="card-subtitle mb-2 text-muted text-uppercase">Linked & Verified</h6>
                        <h2 class="card-title display-4 text-success" id="stat-linked">0</h2>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card h-100 border-warning border-opacity-25">
                    <div class="card-body text-center">
                        <h6 class="card-subtitle mb-2 text-muted text-uppercase">New / Fixed</h6>
                        <h2 class="card-title display-4 text-warning" id="stat-new">0</h2>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card h-100 border-danger border-opacity-25">
                    <div class="card-body text-center">
                        <h6 class="card-subtitle mb-2 text-muted text-uppercase">Missing / Error</h6>
                        <h2 class="card-title display-4 text-danger" id="stat-error">0</h2>
                    </div>
                </div>
            </div>
        </div>

        <!-- Controls & Logs -->
        <div class="row mb-4">
            <div class="col-lg-4 mb-4 mb-lg-0">
                <div class="card h-100">
                    <div class="card-header"><i class="bi bi-joystick"></i> Actions</div>
                    <div class="card-body d-flex flex-column gap-3">
                        <button class="btn btn-primary btn-xl shadow-lg" onclick="triggerScan()">
                            <i class="bi bi-arrow-repeat"></i> Run Full Scan
                        </button>

                        <button class="btn btn-outline-warning" onclick="checkOrphans()">
                            <i class="bi bi-binoculars"></i> Check Orphaned Links
                        </button>

                        <button class="btn btn-outline-info" onclick="showRecoveryModal()">
                            <i class="bi bi-bandaid"></i> Recovery Mode
                        </button>

                        <!-- Clean button disabled as requested -->
                        <!-- 
                        <button class="btn btn-danger" onclick="triggerCleanup()">
                            <i class="bi bi-trash"></i> Clean Old Folders (+00:00)
                        </button>
                        -->
                        <div class="alert alert-dark mt-auto mb-0 text-center">
                            <small class="text-muted d-block mb-1">Auto-scan timer</small>
                            <h4 class="mb-0"><i class="bi bi-clock-history"></i> <span id="next-scan">--</span> min</h4>
                        </div>
                        <div id="orphan-results"></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-8">
                <div class="card h-100">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span><i class="bi bi-terminal"></i> Live Logs</span>
                        <button class="btn btn-sm btn-dark border-secondary" onclick="clearLogs()">Clear</button>
                    </div>
                    <div class="card-body p-2 bg-black">
                        <div class="log-box" id="log-container">
                            <div class="text-muted">Waiting for system logs...</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Recovery Modal -->
        <div class="modal fade" id="recoveryModal" tabindex="-1">
            <div class="modal-dialog modal-xl">
                <div class="modal-content" style="background-color: var(--bg-card); border: 1px solid #444;">
                    <div class="modal-header border-bottom border-secondary">
                        <h5 class="modal-title"><i class="bi bi-bandaid"></i> Advanced Recovery & Cleanup</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="alert alert-info">
                            <i class="bi bi-info-circle"></i> This tool scans for files in your Source and Archive
                            folders to find issues.
                        </div>

                        <div class="d-grid mb-3">
                            <button class="btn btn-primary" onclick="scanRecoveryFiles()">
                                <i class="bi bi-search"></i> Run System Scan
                            </button>
                        </div>

                        <ul class="nav nav-tabs border-secondary mb-3" id="recoveryTabs" role="tablist">
                            <li class="nav-item">
                                <button class="nav-link active text-warning" data-bs-toggle="tab"
                                    data-bs-target="#tab-unindexed">
                                    <i class="bi bi-exclamation-triangle"></i> Unindexed (Import) <span
                                        class="badge bg-secondary ms-1" id="badge-unindexed">0</span>
                                </button>
                            </li>
                            <li class="nav-item">
                                <button class="nav-link text-danger" data-bs-toggle="tab" data-bs-target="#tab-rescue">
                                    <i class="bi bi-life-preserver"></i> Rescue Needed <span
                                        class="badge bg-secondary ms-1" id="badge-rescue">0</span>
                                </button>
                            </li>
                            <li class="nav-item">
                                <button class="nav-link text-muted" data-bs-toggle="tab"
                                    data-bs-target="#tab-redundant">
                                    <i class="bi bi-trash"></i> Redundant Dupes <span class="badge bg-secondary ms-1"
                                        id="badge-redundant">0</span>
                                </button>
                            </li>
                            <li class="nav-item">
                                <button class="nav-link text-white" data-bs-toggle="tab" data-bs-target="#tab-lost">
                                    <i class="bi bi-question-circle"></i> Lost Media <span
                                        class="badge bg-secondary ms-1" id="badge-lost">0</span>
                                </button>
                            </li>
                        </ul>

                        <div class="tab-content">
                            <!-- Unindexed Files -->
                            <div class="tab-pane fade show active" id="tab-unindexed">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <p class="text-muted small mb-0">Files found on disk but missing from TubeArchivist.
                                        Recover them to restore your library.</p>
                                    <button class="btn btn-sm btn-success" onclick="recoverAll('unindexed')"><i
                                            class="bi bi-collection-play"></i> Recover All</button>
                                </div>
                                <div class="table-responsive" style="max-height: 400px;">
                                    <table class="table table-dark table-striped table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>Video ID</th>
                                                <th>Location</th>
                                                <th>Size</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody id="tbody-unindexed">
                                            <tr>
                                                <td colspan="4" class="text-center text-muted">Click Scan to begin...
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <!-- Rescue Files -->
                            <div class="tab-pane fade" id="tab-rescue">
                                <p class="text-danger small"><strong>CRITICAL:</strong> TubeArchivist thinks it has
                                    these videos, but the source file is MISSING. However, we found a copy in your
                                    archives! Recover immediately.</p>
                                <div class="table-responsive" style="max-height: 400px;">
                                    <table class="table table-dark table-striped table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>Video ID</th>
                                                <th>Found At</th>
                                                <th>Missing Source</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody id="tbody-rescue">
                                            <tr>
                                                <td colspan="4" class="text-center text-muted">Click Scan to begin...
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <!-- Redundant Files -->
                            <div class="tab-pane fade" id="tab-redundant">
                                <p class="text-muted small"><strong>SAFE TO DELETE:</strong> These files are duplicates.
                                    TubeArchivist already has a verified copy in the source folder.</p>
                                <div class="table-responsive" style="max-height: 400px;">
                                    <table class="table table-dark table-striped table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>Video ID</th>
                                                <th>Duplicate Path</th>
                                                <th>Verified Source</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody id="tbody-redundant">
                                            <tr>
                                                <td colspan="4" class="text-center text-muted">Click Scan to begin...
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <!-- Lost Media Files -->
                            <div class="tab-pane fade" id="tab-lost">
                                <p class="text-warning small"><strong>VIDEO DELETED:</strong> These files were not found
                                    on YouTube.
                                    You can Force Import them using offline metadata or Delete them.</p>
                                <div class="table-responsive" style="max-height: 400px;">
                                    <table class="table table-dark table-striped table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>Video ID</th>
                                                <th>Filename</th>
                                                <th>Size</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody id="tbody-lost">
                                            <tr>
                                                <td colspan="4" class="text-center text-muted">Click Scan to begin...
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span>Video Matrix</span>
                <div class="d-flex gap-2">
                    <select class="form-select form-select-sm" id="status-filter" style="width: 150px;">
                        <option value="">All Status</option>
                        <option value="linked">Linked</option>
                        <option value="missing">Missing</option>
                    </select>
                    <select class="form-select form-select-sm" id="channel-filter" style="width: 200px;">
                        <option value="">All Channels</option>
                    </select>
                    <input type="text" class="form-control form-control-sm" id="search-input"
                        placeholder="Search videos..." style="width: 200px;">
                </div>
            </div>
            <div class="card-body p-0 table-responsive" style="max-height: 500px;">
                <table class="table table-striped table-hover mb-0">
                    <thead class="table-dark sticky-top">
                        <tr>
                            <th>Status</th>
                            <th>Published</th>
                            <th>Channel</th>
                            <th>Title</th>
                            <th>Video ID</th>
                            <th>Symlink Path</th>
                        </tr>
                    </thead>
                    <tbody id="video-table-body">
                        <!-- Rows injected by JS -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Initial Fetch
        document.addEventListener('DOMContentLoaded', refreshAll);

        let lastLogIndex = 0;

        async function refreshAll() {
            const btn = document.querySelector('button[onclick="refreshAll()"] i');
            if (btn) btn.classList.add('spin-anim');

            await Promise.all([fetchStatus(), fetchLogs()]);

            if (btn) setTimeout(() => btn.classList.remove('spin-anim'), 500);
        }

        async function fetchStatus() {
            try {
                const res = await fetch('/api/status');
                const data = await res.json();

                document.getElementById('connection-status').textContent = 'Connected';
                document.getElementById('connection-status').className = 'badge bg-success';

                // Update stats
                document.getElementById('stat-total').textContent = data.total_videos;
                document.getElementById('stat-linked').textContent = data.verified_links;
                document.getElementById('stat-error').textContent = data.missing_count || 0;

                // Update table if changed (simple check, can be optimized)
                updateTable(data.videos);

            } catch (e) {
                document.getElementById('connection-status').textContent = 'Disconnected';
                document.getElementById('connection-status').className = 'badge bg-danger';
            }
        }

        async function fetchLogs() {
            try {
                const res = await fetch('/api/logs?start=' + lastLogIndex);
                const data = await res.json();
                if (data.logs && data.logs.length > 0) {
                    const logBox = document.getElementById('log-container');
                    data.logs.forEach(line => {
                        const div = document.createElement('div');
                        div.textContent = line;
                        logBox.appendChild(div);
                    });
                    logBox.scrollTop = logBox.scrollHeight;
                    lastLogIndex = data.next_index;
                }
            } catch (e) { console.error(e); }
        }

        async function triggerScan() {
            if (!confirm("Start a full library scan? This may take a moment.")) return;
            await fetch('/api/scan', { method: 'POST' });
            alert("Scan started! Watch the logs.");
        }

        async function triggerCleanup() {
            if (!confirm("Are you sure you want to delete all folders containing '+00:00'?\n\nSafety check: Real files will NOT be deleted.")) return;
            await fetch('/api/cleanup', { method: 'POST' });
            alert("Cleanup started! Watch the logs.");
        }

        async function checkOrphans() {
            const resultsDiv = document.getElementById('orphan-results');
            resultsDiv.innerHTML = '<div class="spinner-border spinner-border-sm" role="status"></div> Checking...';

            const res = await fetch('/api/check-orphans', { method: 'POST' });
            const data = await res.json();

            if (data.count === 0) {
                resultsDiv.innerHTML = '<div class="alert alert-success p-2 mb-0 mt-2">✅ No orphaned links found!</div>';
            } else {
                resultsDiv.innerHTML = `<div class="alert alert-warning p-2 mb-0 mt-2">⚠️ Found ${data.count} orphaned links. Check logs for details.</div>`;
            }

            setTimeout(() => { resultsDiv.innerHTML = ''; }, 10000);
        }

        // Recovery Functions
        const recoveryModal = new bootstrap.Modal(document.getElementById('recoveryModal'));

        function showRecoveryModal() {
            recoveryModal.show();
        }

        let recoveryPollInterval = null;

        async function scanRecoveryFiles() {
            const loadingRow = '<tr><td colspan="4" class="text-center"><div class="spinner-border text-primary" role="status"></div> Scanning in background... (This may take a minute)</td></tr>';
            const ids = ['tbody-unindexed', 'tbody-rescue', 'tbody-redundant', 'tbody-lost'];
            ids.forEach(id => {
                const el = document.getElementById(id);
                if (el) el.innerHTML = loadingRow;
            });

            // CLEAR EXISTING INTERVAL IF ANY
            if (recoveryPollInterval) clearInterval(recoveryPollInterval);

            try {
                // 1. Kick off the scan
                await fetch('/api/recovery/scan', { method: 'POST' });

                // 2. Poll for results
                recoveryPollInterval = setInterval(async () => {
                    try {
                        const res = await fetch('/api/recovery/poll');
                        const state = await res.json();

                        if (state.status === 'done') {
                            clearInterval(recoveryPollInterval);
                            recoveryPollInterval = null;
                            renderResults(state.results);
                        } else if (state.status === 'error') {
                            clearInterval(recoveryPollInterval);
                            recoveryPollInterval = null;
                            alert("Scan Error: " + state.results);
                            resetTables("Error: " + state.results);
                        } else if (state.status === 'idle') {
                            // Scan state lost (server restart?)
                            clearInterval(recoveryPollInterval);
                            recoveryPollInterval = null;
                            alert("Scan state lost (Server Restarted?). Please try again.");
                            resetTables("Scan stopped / State lost.");
                        }
                        // If 'scanning', keep polling...
                    } catch (e) {
                        clearInterval(recoveryPollInterval);
                        recoveryPollInterval = null;
                        console.error("Poll error", e);
                    }
                }, 2000);

            } catch (e) {
                alert("Failed to start scan: " + e);
            }
        }

        function resetTables(msg) {
            const ids = ['tbody-unindexed', 'tbody-rescue', 'tbody-redundant', 'tbody-lost'];
            ids.forEach(id => {
                const el = document.getElementById(id);
                if (el) el.innerHTML = `<tr><td colspan="4" class="text-center text-muted">${msg}</td></tr>`;
            });
        }

        function renderResults(data) {
            // Helper to render rows
            const renderRow = (f, type) => {
                const cleanPath = f.path.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
                if (type === 'unindexed') {
                    return `<tr>
                        <td><code>${f.video_id}</code></td>
                        <td title="${f.path}"><small>${f.filename}</small></td>
                        <td>${f.size_mb} MB</td>
                        <td><button class="btn btn-sm btn-success" onclick="startRecovery('${cleanPath}', this)"><i class="bi bi-cloud-arrow-up"></i> Recover</button></td>
                    </tr>`;
                }
                if (type === 'rescue') {
                    return `<tr>
                        <td><code>${f.video_id}</code></td>
                        <td title="${f.path}"><small>${f.filename}</small></td>
                        <td class="text-danger small">Missing from: ${f.ta_source}</td>
                        <td><button class="btn btn-sm btn-danger" onclick="startRecovery('${cleanPath}', this)"><i class="bi bi-life-preserver"></i> RESCUE</button></td>
                    </tr>`;
                }
                if (type === 'redundant') {
                    return `<tr>
                        <td><code>${f.video_id}</code></td>
                        <td title="${f.path}"><small>${f.filename}</small></td>
                        <td class="text-success small">Exists at: ${f.ta_source}</td>
                        <td><button class="btn btn-sm btn-outline-secondary" onclick="deleteFile('${cleanPath}')"><i class="bi bi-trash"></i> Delete</button></td>
                    </tr>`;
                }
                if (type === 'lost') {
                    return `<tr>
                        <td><code>${f.video_id}</code></td>
                        <td title="${f.path}"><small>${f.filename}</small></td>
                        <td>${f.size_mb} MB</td>
                        <td>
                            <button class="btn btn-sm btn-warning" onclick="forceImport('${cleanPath}')" title="Generate offline metadata"><i class="bi bi-lightning-charge"></i> Force</button>
                            <button class="btn btn-sm btn-outline-danger ms-1" onclick="deleteFile('${cleanPath}')"><i class="bi bi-trash"></i></button>
                        </td>
                    </tr>`;
                }
            };

            const ids = ['tbody-unindexed', 'tbody-rescue', 'tbody-redundant', 'tbody-lost'];
            ids.forEach(id => {
                const el = document.getElementById(id);
                if (el) el.innerHTML = '';
            });

            // Update Badges
            document.getElementById('badge-unindexed').innerText = data.unindexed ? data.unindexed.length : 0;
            document.getElementById('badge-rescue').innerText = data.rescue ? data.rescue.length : 0;
            document.getElementById('badge-redundant').innerText = data.redundant ? data.redundant.length : 0;
            document.getElementById('badge-lost').innerText = data.lost ? data.lost.length : 0;

            // Populate - OPTIMIZED (Build string once)
            const unindexedRows = (data.unindexed || []).map(f => renderRow(f, 'unindexed')).join('');
            document.getElementById('tbody-unindexed').innerHTML = unindexedRows;

            const rescueRows = (data.rescue || []).map(f => renderRow(f, 'rescue')).join('');
            document.getElementById('tbody-rescue').innerHTML = rescueRows;

            const redundantRows = (data.redundant || []).map(f => renderRow(f, 'redundant')).join('');
            document.getElementById('tbody-redundant').innerHTML = redundantRows;

            const lostRows = (data.lost || []).map(f => renderRow(f, 'lost')).join('');
            if (document.getElementById('tbody-lost')) document.getElementById('tbody-lost').innerHTML = lostRows;

            if (!data.unindexed || data.unindexed.length === 0) document.getElementById('tbody-unindexed').innerHTML = '<tr><td colspan="4" class="text-center text-muted">No unindexed files found.</td></tr>';
            if (!data.rescue || data.rescue.length === 0) document.getElementById('tbody-rescue').innerHTML = '<tr><td colspan="4" class="text-center text-muted">No rescue candidates found.</td></tr>';
            if (!data.redundant || data.redundant.length === 0) document.getElementById('tbody-redundant').innerHTML = '<tr><td colspan="4" class="text-center text-muted">No duplicates found.</td></tr>';
            if ((!data.lost || data.lost.length === 0) && document.getElementById('tbody-lost')) document.getElementById('tbody-lost').innerHTML = '<tr><td colspan="4" class="text-center text-muted">No lost media found.</td></tr>';
        }

        async function forceImport(filepath) {
            if (!confirm("FORCE IMPORT: Use offline metadata?\n\nThis will import the file even if it is deleted/private on YouTube. Metadata might be incomplete.")) return;
            try {
                const res = await fetch('/api/recovery/force', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ filepath })
                });
                const data = await res.json();
                if (data.success) {
                    alert("Force import successful! Refreshing list...");
                    scanRecoveryFiles();
                } else {
                    alert("Error: " + (data.error || data.message));
                }
            } catch (e) { alert("Error: " + e); }
        }

        async function startRecovery(filepath, btn, isBatch = false) {
            console.log("startRecovery clicked for:", filepath);
            if (!isBatch && !confirm("Start recovery for this file? This will try to fetch metadata and move it to the Import folder.")) return;

            // Show loading state
            // If btn is not passed (legacy call), try to find it via event, closely.
            if (!btn && typeof event !== 'undefined' && event) {
                btn = event.target.closest('button');
            }

            const originalHtml = btn ? btn.innerHTML : 'Recover';
            if (btn) {
                btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> ...';
                btn.disabled = true;
            }

            try {
                const res = await fetch('/api/recovery/start', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ filepath })
                });
                const data = await res.json();

                if (!isBatch) alert(data.message);

                // If batch, we mark as done visually but don't rescan yet
                if (btn && isBatch && data.success) {
                    btn.innerHTML = '<i class="bi bi-check-lg"></i> Done';
                    btn.classList.remove('btn-success');
                    btn.classList.add('btn-secondary');
                }

                // Refresh the list only if NOT batch (batch does it at end)
                if (!isBatch) scanRecoveryFiles();

                return data.success; // Return status for batch loop

            } catch (e) {
                if (!isBatch) alert("Error: " + e);
                if (btn && isBatch) {
                    btn.innerHTML = '<i class="bi bi-x-lg"></i> Err';
                    btn.classList.add('btn-danger');
                }
                return false;
            } finally {
                // Restore button only if NOT batch (batch keeps them marked done)
                if (btn && !isBatch) {
                    btn.innerHTML = originalHtml;
                    btn.disabled = false;
                }
            }
        }

        async function deleteFile(filepath) {
            if (!confirm("⚠️ DELETE WARNING: Are you sure you want to delete this file?\n\n" + filepath + "\n\nOnly click OK if you are sure TA has a copy.")) return;
            try {
                const res = await fetch('/api/recovery/delete', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ filepath })
                });
                const data = await res.json();
                if (data.success) {
                    alert("File deleted.");
                    // Refresh not automatic for delete in async mode to avoid full rescan
                    // Ideally we remove the row, but for now user can re-scan manually or we can trigger fetch
                    // Let's just alert.
                } else {
                    alert("Error: " + data.error);
                }
            } catch (e) { alert("Error: " + e); }
        }

        function clearLogs() {
            document.getElementById('log-container').innerHTML = '';
        }

        function updateTable(videos) {
            const tbody = document.getElementById('video-table-body');
            const search = document.getElementById('search-input').value.toLowerCase();
            const channelFilter = document.getElementById('channel-filter').value;
            const statusFilter = document.getElementById('status-filter').value;

            // Build unique channel list for dropdown
            const channels = [...new Set(videos.map(v => v.channel))].sort();
            const channelDropdown = document.getElementById('channel-filter');
            const currentValue = channelDropdown.value;

            // Only update dropdown if channel list changed
            if (channelDropdown.options.length !== channels.length + 1) {
                channelDropdown.innerHTML = '<option value="">All Channels</option>';
                channels.forEach(ch => {
                    const opt = document.createElement('option');
                    opt.value = ch;
                    opt.textContent = ch;
                    channelDropdown.appendChild(opt);
                });
                channelDropdown.value = currentValue;
            }

            // Clear and rebuild table
            tbody.innerHTML = '';

            videos.forEach(v => {
                // Apply filters
                if (search && !v.title.toLowerCase().includes(search) && !v.video_id.includes(search)) return;
                if (channelFilter && v.channel !== channelFilter) return;
                if (statusFilter && v.status !== statusFilter) return;

                const tr = document.createElement('tr');
                let statusColor = v.status === 'linked' ? 'status-green' : 'status-red';

                tr.innerHTML = `
                    <td><span class="status-dot ${statusColor}"></span></td>
                    <td>${v.published}</td>
                    <td>${v.channel}</td>
                    <td>${v.title}</td>
                    <td><code>${v.video_id}</code></td>
                    <td class="text-truncate" style="max-width: 300px;">${v.symlink || '-'}</td>
                `;
                tbody.appendChild(tr);
            });
        }

        document.getElementById('search-input').addEventListener('input', () => {
            fetchStatus();
        });

        document.getElementById('channel-filter').addEventListener('change', () => {
            fetchStatus();
        });

        document.getElementById('status-filter').addEventListener('change', () => {
            fetchStatus();
        });

        async function recoverAll(type) {
            if (!confirm("Are you sure you want to BATCH RECOVER all items in '" + type + "'?\n\nThis will process them one by one. Please do not close this tab.")) return;

            const tbody = document.getElementById('tbody-' + type);
            // Select all buttons that trigger recovery
            const buttons = Array.from(tbody.querySelectorAll('button[onclick*="startRecovery"]'));

            if (buttons.length === 0) {
                alert("No items to recover!");
                return;
            }

            let successCount = 0;

            for (const btn of buttons) {
                if (btn.disabled) continue; // Skip if already processing

                // Visual scroll to item
                btn.scrollIntoView({ behavior: 'smooth', block: 'center' });

                // Parse the path
                const onClickText = btn.getAttribute('onclick');
                const match = onClickText.match(/startRecovery\('(.+?)'/);

                if (match) {
                    const path = match[1];
                    try {
                        await startRecovery(path, btn, true);
                        successCount++;
                    } catch (e) {
                        console.error("Batch error for " + path, e);
                    }
                    // Pace it
                    await new Promise(r => setTimeout(r, 500));
                }
            }
            alert("Batch Complete! Processed: " + buttons.length);
            scanRecoveryFiles();
        }
    </script>
</body>

</html>