<?php
 
 
 
 
 
 

$selectedId = isset($_GET['id']) ? (int) $_GET['id'] : 0;

$statusColors = [
    'pending'   => 'bg-yellow-100 text-yellow-800',
    'reviewed'  => 'bg-primary-100 text-primary-800',
    'resolved'  => 'bg-green-100 text-green-800',
    'dismissed' => 'bg-gray-100 text-gray-500',
];
$reasonColors = [
    'illegal'   => 'bg-red-100 text-red-800',
    'copyright' => 'bg-purple-100 text-purple-800',
    'spam'      => 'bg-orange-100 text-orange-800',
    'broken'    => 'bg-gray-100 text-gray-600',
    'underage'  => 'bg-red-200 text-red-900',
    'other'     => 'bg-gray-100 text-gray-600',
];
$relTime = function (string $dt): string {
    $diff = time() - strtotime($dt);
    if ($diff < 60)     return $diff . 's';
    if ($diff < 3600)   return floor($diff / 60) . 'm';
    if ($diff < 86400)  return floor($diff / 3600) . 'h';
    if ($diff < 604800) return floor($diff / 86400) . 'd';
    return date('M j', strtotime($dt));
};
?>


<div class="inbox-toolbar mb-3 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
    <div class="flex items-center gap-3 flex-1 min-w-0">
        <input type="text" id="rep-search" placeholder="Search reports..."
               class="w-full sm:w-72 px-3 py-2 sm:py-1.5 border border-gray-300 rounded-lg text-sm sm:text-xs focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none">
        <span class="text-xs text-gray-500 whitespace-nowrap hidden sm:inline">
            <?= number_format($totalReports) ?> report<?= $totalReports !== 1 ? 's' : '' ?>
        </span>
    </div>
    <div class="inbox-pills flex items-center gap-2">
        <a href="/admin/inbox?tab=reports<?= $currentReason !== 'all' ? '&reason=' . urlencode($currentReason) : '' ?>"
           class="px-2.5 py-1 text-xs font-medium rounded border <?= $currentStatus === 'all' ? 'bg-primary-600 text-white border-primary-600' : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50' ?>">All</a>
        <a href="/admin/inbox?tab=reports&status=pending<?= $currentReason !== 'all' ? '&reason=' . urlencode($currentReason) : '' ?>"
           class="px-2.5 py-1 text-xs font-medium rounded border <?= $currentStatus === 'pending' ? 'bg-primary-600 text-white border-primary-600' : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50' ?>">
            Pending<?php if ($pendingCount > 0): ?> <span class="ml-1 inline-flex items-center justify-center min-w-[16px] h-4 px-1 text-[10px] font-bold rounded-full <?= $currentStatus === 'pending' ? 'bg-white/25 text-white' : 'bg-red-500 text-white' ?>"><?= $pendingCount ?></span><?php endif; ?>
        </a>
        <a href="/admin/inbox?tab=reports&status=reviewed<?= $currentReason !== 'all' ? '&reason=' . urlencode($currentReason) : '' ?>"
           class="px-2.5 py-1 text-xs font-medium rounded border <?= $currentStatus === 'reviewed' ? 'bg-primary-600 text-white border-primary-600' : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50' ?>">Under review</a>
        <a href="/admin/inbox?tab=reports&status=resolved<?= $currentReason !== 'all' ? '&reason=' . urlencode($currentReason) : '' ?>"
           class="px-2.5 py-1 text-xs font-medium rounded border <?= $currentStatus === 'resolved' ? 'bg-primary-600 text-white border-primary-600' : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50' ?>">Resolved</a>
        <a href="/admin/inbox?tab=reports&status=dismissed<?= $currentReason !== 'all' ? '&reason=' . urlencode($currentReason) : '' ?>"
           class="px-2.5 py-1 text-xs font-medium rounded border <?= $currentStatus === 'dismissed' ? 'bg-primary-600 text-white border-primary-600' : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50' ?>">Dismissed</a>

        <select onchange="var u=new URL(window.location);u.searchParams.set('tab','reports');if(this.value==='all'){u.searchParams.delete('reason')}else{u.searchParams.set('reason',this.value)}u.searchParams.delete('page');u.searchParams.delete('id');window.location=u"
                class="ml-1 px-2.5 py-1 border border-gray-300 rounded text-xs bg-white focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none">
            <option value="all">All reasons</option>
            <?php foreach (Report::REASON_LABELS as $key => $label): ?>
                <option value="<?= $key ?>" <?= $currentReason === $key ? 'selected' : '' ?>><?= $label ?></option>
            <?php endforeach; ?>
        </select>
    </div>
</div>


<div id="rep-bulk" class="inbox-bulk hidden mb-3 px-3 py-2 bg-primary-50 border border-primary-200 rounded-lg text-xs">
    <div class="flex items-center gap-2 flex-wrap">
        <span class="font-medium text-primary-700 mr-1"><span id="rep-bulk-count">0</span> selected</span>
        <button type="button" onclick="repBulkStatus('reviewed')" class="inline-flex items-center gap-1 px-3 py-1.5 bg-white text-gray-700 border border-gray-300 text-xs font-medium rounded hover:bg-gray-50">Reviewed</button>
        <button type="button" onclick="repBulkStatus('resolved')" class="inline-flex items-center gap-1 px-3 py-1.5 bg-white text-gray-700 border border-gray-300 text-xs font-medium rounded hover:bg-gray-50">Resolved</button>
        <button type="button" onclick="repBulkStatus('dismissed')" class="inline-flex items-center gap-1 px-3 py-1.5 bg-white text-gray-700 border border-gray-300 text-xs font-medium rounded hover:bg-gray-50">Dismiss</button>
        <button type="button" onclick="repBulkDelete()" class="inline-flex items-center gap-1 px-3 py-1.5 bg-red-600 text-white text-xs font-medium rounded hover:bg-red-700">
            <i class="fa-regular fa-trash-can text-[11px]"></i> Delete
        </button>
        <button type="button" onclick="repBulkClear()" class="ml-auto text-xs text-gray-500 hover:text-gray-700 px-2 py-1">Clear</button>
    </div>
</div>


<div class="inbox-shell grid grid-cols-1 lg:grid-cols-[440px_1fr] gap-4 items-start" data-pane="list" id="rep-shell">

    
    <div class="inbox-list-pane space-y-3 min-w-0">
        <?php if (empty($reports)): ?>
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-12 text-center">
                <i class="fa-solid fa-flag text-5xl text-gray-200 mb-3"></i>
                <p class="text-sm font-medium text-gray-700">No reports here.</p>
                <p class="text-xs text-gray-400 mt-1">When users flag videos, they will show up in this list.</p>
            </div>
        <?php else: ?>
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="px-3 py-2 border-b border-gray-200 bg-gray-50 flex items-center gap-3">
                    <label class="inline-flex items-center" title="Select all on this page">
                        <input type="checkbox" id="rep-select-all" class="w-3.5 h-3.5 rounded border-gray-300 text-primary-600 focus:ring-primary-500 cursor-pointer">
                    </label>
                    <span class="text-[11px] font-semibold uppercase tracking-wider text-gray-500">
                        Reports
                        <?php if ($currentStatus !== 'all'): ?>· <?= htmlspecialchars(Report::STATUS_LABELS[$currentStatus] ?? $currentStatus) ?><?php endif; ?>
                    </span>
                    <span class="ml-auto text-[11px] text-gray-400"><?= count($reports) ?> on this page</span>
                </div>

                <ul id="rep-list" class="divide-y divide-gray-100 max-h-[calc(100vh-280px)] overflow-y-auto">
                    <?php foreach ($reports as $report): ?>
                    <?php
                        $isActive = (int) $report['id'] === $selectedId;
                        $isPending = $report['status'] === 'pending';
                        $repSubj = Report::subject($report);
                        $search = strtolower(
                            ($repSubj['title']) . ' ' . ($report['username'] ?? '') . ' '
                            . ($report['details'] ?? '') . ' ' . $report['reason'] . ' ' . ($report['ip_address'] ?? '')
                        );
                    ?>
                    <li class="rep-row"
                        data-id="<?= (int)$report['id'] ?>"
                        data-search="<?= htmlspecialchars($search, ENT_QUOTES) ?>">
                        <div class="group relative inbox-row-tap flex items-stretch transition-colors cursor-pointer <?= $isActive ? 'bg-primary-50' : ($isPending ? 'bg-yellow-50/40 hover:bg-yellow-50/70' : 'hover:bg-gray-50') ?>"
                             onclick="repOpen(<?= (int)$report['id'] ?>, event)">
                            <span class="rep-accent absolute left-0 top-0 bottom-0 w-1 <?= $isActive ? 'bg-primary-600' : ($isPending ? 'bg-yellow-400' : 'bg-transparent') ?>"></span>

                            <label class="flex items-center pl-2 pr-2 sm:pl-3 py-2.5 -my-2.5 cursor-pointer" onclick="event.stopPropagation()">
                                <input type="checkbox" class="rep-check w-3.5 h-3.5 rounded border-gray-300 text-primary-600 focus:ring-primary-500 cursor-pointer"
                                       data-id="<?= (int)$report['id'] ?>" onchange="repSelectChanged()">
                            </label>

                            <div class="flex-1 min-w-0 py-2.5 pr-3">
                                <div class="flex items-center justify-between gap-2 mb-0.5">
                                    <div class="flex items-center gap-1.5 min-w-0 flex-wrap">
                                        <span class="rep-status-badge inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium <?= $statusColors[$report['status']] ?? 'bg-gray-100 text-gray-600' ?>">
                                            <?= Report::STATUS_LABELS[$report['status']] ?? $report['status'] ?>
                                        </span>
                                        <span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium <?= $reasonColors[$report['reason']] ?? 'bg-gray-100 text-gray-600' ?>">
                                            <?= Report::REASON_LABELS[$report['reason']] ?? $report['reason'] ?>
                                        </span>
                                    </div>
                                    <span class="text-[10px] text-gray-400 shrink-0 whitespace-nowrap" title="<?= htmlspecialchars(substr($report['created_at'], 0, 16)) ?>">
                                        <?= $relTime($report['created_at']) ?>
                                    </span>
                                </div>
                                <div class="text-sm text-gray-800 truncate font-medium">
                                    <span class="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-bold uppercase tracking-wide <?= $repSubj['type'] === 'album' ? 'bg-fuchsia-100 text-fuchsia-700' : 'bg-slate-100 text-slate-600' ?>"><?= $repSubj['label'] ?></span>
                                    <?= htmlspecialchars($repSubj['title']) ?>
                                </div>
                                <div class="text-[11px] text-gray-400 truncate mt-0.5">
                                    by <?= htmlspecialchars($report['username'] ?? 'Guest') ?>
                                    <?php if (!empty($report['ip_address'])): ?>· <span class="font-mono"><?= htmlspecialchars($report['ip_address']) ?></span><?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>

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

    
    <div id="rep-detail-wrap" class="inbox-detail-pane lg:sticky lg:top-4 min-w-0">
        
        <div class="inbox-detail-back hidden" id="rep-back-bar">
            <button type="button" onclick="repClose()" class="inline-flex items-center justify-center w-9 h-9 rounded-full hover:bg-gray-100 text-gray-700" aria-label="Back to reports">
                <i class="fa-solid fa-arrow-left"></i>
            </button>
            <span class="text-sm font-medium text-gray-700 truncate flex-1" id="rep-back-title">Report</span>
        </div>
        <div id="rep-detail-empty" class="bg-white rounded-lg shadow-sm border border-gray-200 p-16 text-center">
            <i class="fa-solid fa-flag text-6xl text-gray-200 mb-4"></i>
            <p class="text-sm font-medium text-gray-700">Select a report</p>
            <p class="text-xs text-gray-400 mt-1">Click a report on the left to review its details and take action.</p>
        </div>

        <div id="rep-detail-loading" class="hidden bg-white rounded-lg shadow-sm border border-gray-200 p-16 text-center">
            <i class="fa-solid fa-spinner fa-spin text-3xl text-primary-400 mb-3"></i>
            <p class="text-sm text-gray-500">Loading report…</p>
        </div>

        <article id="rep-detail" class="hidden bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
            
            <header class="px-5 py-4 border-b border-gray-200">
                <div class="flex items-center gap-2 flex-wrap mb-2">
                    <span id="rep-d-status" class="inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-medium"></span>
                    <span id="rep-d-reason" class="inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-medium"></span>
                    <span id="rep-d-count" class="text-[11px] text-gray-500"></span>
                </div>
                <h2 id="rep-d-title" class="text-base font-semibold text-gray-900 leading-snug"></h2>
            </header>

            
            <div class="px-5 py-3 border-b border-gray-100 bg-gray-50/60">
                <div class="grid grid-cols-2 gap-x-6 gap-y-2 text-xs">
                    <div>
                        <div class="text-[10px] font-semibold text-gray-400 uppercase tracking-wider mb-0.5">Reporter</div>
                        <div id="rep-d-reporter" class="text-gray-700"></div>
                    </div>
                    <div>
                        <div class="text-[10px] font-semibold text-gray-400 uppercase tracking-wider mb-0.5">IP address</div>
                        <div id="rep-d-ip" class="text-gray-700 font-mono"></div>
                    </div>
                    <div>
                        <div class="text-[10px] font-semibold text-gray-400 uppercase tracking-wider mb-0.5">Date</div>
                        <div id="rep-d-date" class="text-gray-700"></div>
                    </div>
                    <div id="rep-d-email-wrap" class="hidden">
                        <div class="text-[10px] font-semibold text-gray-400 uppercase tracking-wider mb-0.5">Email</div>
                        <div id="rep-d-email" class="text-gray-700"></div>
                    </div>
                </div>
            </div>

            
            <div id="rep-d-details-wrap" class="hidden px-5 py-3 border-b border-gray-100">
                <div class="text-[10px] font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Reporter notes</div>
                <pre id="rep-d-details" class="text-sm text-gray-800 whitespace-pre-wrap font-sans bg-gray-50 px-3 py-2 rounded border border-gray-200 leading-relaxed"></pre>
            </div>

            
            <div id="rep-d-note-wrap" class="hidden px-5 py-3 border-b border-gray-100">
                <div class="text-[10px] font-semibold text-gray-400 uppercase tracking-wider mb-1.5">Admin note</div>
                <pre id="rep-d-note" class="text-sm text-gray-800 whitespace-pre-wrap font-sans bg-yellow-50 px-3 py-2 rounded border border-yellow-200 leading-relaxed"></pre>
            </div>

            
            <div class="px-5 py-3 border-b border-gray-100">
                <div class="text-[10px] font-semibold text-gray-400 uppercase tracking-wider mb-2">Update status</div>
                <div class="flex flex-wrap gap-2 mb-2">
                    <?php foreach (['pending' => 'Pending', 'reviewed' => 'Under review', 'resolved' => 'Resolved', 'dismissed' => 'Dismissed'] as $key => $label): ?>
                    <label class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md border border-gray-300 cursor-pointer hover:bg-gray-50 has-[:checked]:border-primary-500 has-[:checked]:bg-primary-50 has-[:checked]:text-primary-700">
                        <input type="radio" name="rep-d-newstatus" value="<?= $key ?>" class="accent-primary-600 w-3 h-3">
                        <span class="text-xs"><?= $label ?></span>
                    </label>
                    <?php endforeach; ?>
                </div>
                <textarea id="rep-d-newnote" rows="2" placeholder="Admin note (optional)…"
                          class="w-full px-3 py-2 border border-gray-300 rounded-md text-xs resize-y focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none"></textarea>
                <div class="mt-2 flex items-center gap-3">
                    <button type="button" onclick="repUpdateStatus()" id="rep-d-update-btn"
                            class="inline-flex items-center gap-1.5 px-3 py-1.5 bg-primary-600 text-white text-xs font-medium rounded-lg hover:bg-primary-700">
                        <i class="fa-regular fa-circle-check text-[11px]"></i> Update
                    </button>
                    <span id="rep-d-update-msg" class="text-xs hidden"></span>
                </div>
            </div>

            
            <footer class="inbox-detail-actions border-t border-gray-200 bg-gray-50 px-5 py-3 flex flex-wrap items-center justify-between gap-2">
                <div class="flex flex-wrap items-center gap-2">
                    <a id="rep-d-view" href="#" target="_blank"
                       class="inline-flex items-center gap-1.5 px-3 py-2 bg-white text-gray-700 border border-gray-300 text-xs font-medium rounded-lg hover:bg-gray-50">
                        <i class="fa-regular fa-eye text-[11px]"></i> View video
                    </a>
                    <a id="rep-d-edit" href="#"
                       class="inline-flex items-center gap-1.5 px-3 py-2 bg-white text-gray-700 border border-gray-300 text-xs font-medium rounded-lg hover:bg-gray-50">
                        <i class="fa-regular fa-pen-to-square text-[11px]"></i> Edit video
                    </a>
                </div>
                <button type="button" onclick="repDeleteVideo()" id="rep-d-delvideo"
                        class="inline-flex items-center gap-1.5 px-3 py-2 bg-red-600 text-white text-xs font-medium rounded-lg hover:bg-red-700">
                    <i class="fa-regular fa-trash-can text-[11px]"></i> Delete video
                </button>
            </footer>
        </article>
    </div>
</div>

<script>
(function () {
    const csrf = '<?= Router::csrfToken() ?>';
    const preselectId = <?= (int) $selectedId ?>;
    let currentId = 0;

    const STATUS_COLORS = {
        pending:   'bg-yellow-100 text-yellow-800',
        reviewed:  'bg-primary-100 text-primary-800',
        resolved:  'bg-green-100 text-green-800',
        dismissed: 'bg-gray-100 text-gray-500',
    };
    const REASON_COLORS = {
        illegal:   'bg-red-100 text-red-800',
        copyright: 'bg-purple-100 text-purple-800',
        spam:      'bg-orange-100 text-orange-800',
        broken:    'bg-gray-100 text-gray-600',
        underage:  'bg-red-200 text-red-900',
        other:     'bg-gray-100 text-gray-600',
    };

    
    const search = document.getElementById('rep-search');
    if (search) {
        search.addEventListener('input', () => {
            const q = search.value.toLowerCase().trim();
            document.querySelectorAll('#rep-list .rep-row').forEach(row => {
                row.style.display = (!q || row.dataset.search.includes(q)) ? '' : 'none';
            });
        });
    }

    
    window.repSelectChanged = function () {
        const ids = [...document.querySelectorAll('.rep-check:checked')].map(c => c.dataset.id);
        document.getElementById('rep-bulk-count').textContent = ids.length;
        document.getElementById('rep-bulk').classList.toggle('hidden', ids.length === 0);
        const all = document.getElementById('rep-select-all');
        const total = document.querySelectorAll('.rep-check').length;
        if (all) {
            all.checked = ids.length > 0 && ids.length === total;
            all.indeterminate = ids.length > 0 && ids.length < total;
        }
    };
    const selectAllBox = document.getElementById('rep-select-all');
    if (selectAllBox) {
        selectAllBox.addEventListener('change', () => {
            document.querySelectorAll('.rep-check').forEach(c => { c.checked = selectAllBox.checked; });
            repSelectChanged();
        });
    }
    window.repBulkClear = function () {
        document.querySelectorAll('.rep-check').forEach(c => { c.checked = false; });
        repSelectChanged();
    };
    
    async function repPost(url, body) {
        try {
            const res = await fetch(url, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
                body: (body ? body + '&' : '') + '_ajax=1&csrf_token=' + encodeURIComponent(csrf),
            });
            if (res.redirected || res.status === 401 || res.status === 403) return 'auth';
            const data = await res.json().catch(() => null);
            if (!res.ok || !data || data.success !== true) return 'fail';
            return 'ok';
        } catch (e) {
            return 'fail';
        }
    }
    function repSessionExpired() {
        alert('Your session has expired — please sign in again. The page will now reload.');
        location.reload();
    }
    function repRefreshAfterDelete() {
        if (document.querySelectorAll('#rep-list .rep-row').length === 0) location.reload();
    }

    window.repBulkStatus = async function (status) {
        const ids = [...document.querySelectorAll('.rep-check:checked')].map(c => c.dataset.id);
        if (!ids.length) return;
        const results = await Promise.all(ids.map(id => repPost('/admin/reports/' + id + '/status', 'status=' + encodeURIComponent(status))));
        if (results.includes('auth')) { repSessionExpired(); return; }
        ids.forEach((id, i) => { if (results[i] === 'ok') repRowSetStatus(parseInt(id, 10), status); });
        if (results.includes('fail')) { alert('Some reports could not be updated. Reloading to refresh the list.'); location.reload(); return; }
        repBulkClear();
    };
    window.repBulkDelete = async function () {
        const ids = [...document.querySelectorAll('.rep-check:checked')].map(c => c.dataset.id);
        if (!ids.length) return;
        if (!confirm('Delete ' + ids.length + ' report(s)? This will not delete the videos themselves.')) return;
        const results = await Promise.all(ids.map(id => repPost('/admin/reports/' + id + '/delete', '')));
        if (results.includes('auth')) { repSessionExpired(); return; }
        let failed = 0;
        ids.forEach((id, i) => {
            if (results[i] === 'ok') {
                const row = document.querySelector('.rep-row[data-id="' + id + '"]');
                if (row) row.remove();
                if (currentId === parseInt(id, 10)) repClose();
            } else {
                failed++;
            }
        });
        repSelectChanged();
        if (failed > 0) {
            alert(failed + ' report(s) could not be deleted. Reloading to refresh the list.');
            location.reload();
            return;
        }
        repRefreshAfterDelete();
    };

    
    function repRowSetStatus(id, status) {
        const row = document.querySelector('.rep-row[data-id="' + id + '"]');
        if (!row) return;
        const badge = row.querySelector('.rep-status-badge');
        if (badge) {
            badge.className = 'rep-status-badge inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium ' + (STATUS_COLORS[status] || '');
            const labels = {pending: 'Pending', reviewed: 'Under Review', resolved: 'Resolved', dismissed: 'Dismissed'};
            badge.textContent = labels[status] || status;
        }
        const accent = row.querySelector('.rep-accent');
        if (status !== 'pending' && accent && accent.classList.contains('bg-yellow-400')) {
            accent.classList.remove('bg-yellow-400');
            accent.classList.add('bg-transparent');
        }
    }
    function repRowSetActive(id) {
        document.querySelectorAll('.rep-row .group').forEach(card => {
            card.classList.remove('bg-primary-50');
            const a = card.querySelector('.rep-accent');
            if (a && a.classList.contains('bg-primary-600')) {
                a.classList.remove('bg-primary-600');
                a.classList.add('bg-transparent');
            }
        });
        const row = document.querySelector('.rep-row[data-id="' + id + '"]');
        if (row) {
            const card = row.querySelector('.group');
            card.classList.add('bg-primary-50');
            const a = row.querySelector('.rep-accent');
            if (a) { a.classList.remove('bg-transparent','bg-yellow-400'); a.classList.add('bg-primary-600'); }
        }
    }

    
    const shell = document.getElementById('rep-shell');
    const isMobile = () => window.innerWidth < 1024;

    window.repOpen = function (id, evt) {
        if (evt && evt.target && (evt.target.tagName === 'INPUT' || evt.target.tagName === 'LABEL')) return;
        currentId = id;
        repRowSetActive(id);
        document.getElementById('rep-detail-empty').classList.add('hidden');
        document.getElementById('rep-detail').classList.add('hidden');
        document.getElementById('rep-detail-loading').classList.remove('hidden');
        document.getElementById('rep-d-update-msg').classList.add('hidden');
        document.getElementById('rep-d-newnote').value = '';
        document.querySelectorAll('input[name="rep-d-newstatus"]').forEach(r => r.checked = false);

        if (isMobile()) {
            if (shell) shell.dataset.pane = 'detail';
            document.getElementById('rep-back-bar').classList.remove('hidden');
            document.querySelectorAll('.inbox-toolbar, .inbox-bulk').forEach(el => el.classList.add('inbox-mobile-hide'));
            window.scrollTo({ top: 0, behavior: 'instant' });
            if (history.state?.inboxPane !== 'detail') {
                history.pushState({ inboxPane: 'detail', id }, '');
            }
        }

        fetch('/admin/reports/' + id + '/json')
            .then(r => r.json())
            .then(d => {
                document.getElementById('rep-detail-loading').classList.add('hidden');
                if (d.error) { document.getElementById('rep-detail-empty').classList.remove('hidden'); return; }

                const statusEl = document.getElementById('rep-d-status');
                statusEl.className = 'inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-medium ' + (STATUS_COLORS[d.status] || '');
                statusEl.textContent = d.status_label;

                const reasonEl = document.getElementById('rep-d-reason');
                reasonEl.className = 'inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-medium ' + (REASON_COLORS[d.reason] || '');
                reasonEl.textContent = d.reason_label;

                document.getElementById('rep-d-count').textContent = d.report_count > 1 ? '· ' + d.report_count + ' reports for this ' + (d.subject_label || 'item').toLowerCase() : '';
                document.getElementById('rep-d-title').textContent = d.subject_title;

                document.getElementById('rep-d-reporter').textContent = d.username;
                document.getElementById('rep-d-ip').textContent = d.ip_address || '—';
                document.getElementById('rep-d-date').textContent = d.created_at ? d.created_at.substring(0, 16) : '—';

                const emailWrap = document.getElementById('rep-d-email-wrap');
                if (d.reporter_email) { emailWrap.classList.remove('hidden'); document.getElementById('rep-d-email').textContent = d.reporter_email; }
                else { emailWrap.classList.add('hidden'); }

                const detWrap = document.getElementById('rep-d-details-wrap');
                if (d.details) { detWrap.classList.remove('hidden'); document.getElementById('rep-d-details').textContent = d.details; }
                else { detWrap.classList.add('hidden'); }

                const noteWrap = document.getElementById('rep-d-note-wrap');
                if (d.admin_note) { noteWrap.classList.remove('hidden'); document.getElementById('rep-d-note').textContent = d.admin_note; }
                else { noteWrap.classList.add('hidden'); }

                const radio = document.querySelector('input[name="rep-d-newstatus"][value="' + d.status + '"]');
                if (radio) radio.checked = true;

                window._repSubjectType = d.subject_type || 'video';
                var _lbl = d.subject_label || 'Video';
                document.getElementById('rep-d-view').href = d.subject_view_url || '#';
                document.getElementById('rep-d-view').innerHTML = '<i class="fa-regular fa-eye text-[11px]"></i> View ' + _lbl;
                document.getElementById('rep-d-edit').href = d.subject_edit_url || '#';
                document.getElementById('rep-d-edit').innerHTML = '<i class="fa-regular fa-pen-to-square text-[11px]"></i> Edit ' + _lbl;
                var _del = document.getElementById('rep-d-delvideo');
                if (_del) _del.innerHTML = '<i class="fa-regular fa-trash-can text-[11px]"></i> Delete ' + _lbl;

                document.getElementById('rep-detail').classList.remove('hidden');
                document.getElementById('rep-back-title').textContent = d.subject_title || 'Report';

                const u = new URL(window.location);
                u.searchParams.set('id', id);
                history.replaceState({ ...(history.state || {}), id }, '', u);
            })
            .catch(() => {
                document.getElementById('rep-detail-loading').classList.add('hidden');
                document.getElementById('rep-detail-empty').classList.remove('hidden');
            });
    };

    window.repClose = function (skipHistory) {
        currentId = 0;
        document.getElementById('rep-detail').classList.add('hidden');
        document.getElementById('rep-detail-loading').classList.add('hidden');
        document.getElementById('rep-detail-empty').classList.remove('hidden');
        document.querySelectorAll('.rep-row .group').forEach(card => {
            card.classList.remove('bg-primary-50');
            const a = card.querySelector('.rep-accent');
            if (a && a.classList.contains('bg-primary-600')) {
                a.classList.remove('bg-primary-600');
                a.classList.add('bg-transparent');
            }
        });
        if (shell) shell.dataset.pane = 'list';
        document.getElementById('rep-back-bar').classList.add('hidden');
        document.querySelectorAll('.inbox-toolbar, .inbox-bulk').forEach(el => el.classList.remove('inbox-mobile-hide'));
        const u = new URL(window.location); u.searchParams.delete('id');
        if (!skipHistory && history.state?.inboxPane === 'detail') {
            history.back();
        } else {
            history.replaceState({ inboxPane: 'list' }, '', u);
        }
    };

    window.addEventListener('popstate', () => {
        if (currentId && shell?.dataset.pane === 'detail') {
            repClose(true);
        }
    });

    window.repUpdateStatus = async function () {
        const radio = document.querySelector('input[name="rep-d-newstatus"]:checked');
        if (!radio || !currentId) return;
        const btn = document.getElementById('rep-d-update-btn');
        const msg = document.getElementById('rep-d-update-msg');
        btn.disabled = true;
        const oldHtml = btn.innerHTML;
        btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin text-[11px]"></i> Updating…';
        try {
            const res = await fetch('/admin/reports/' + currentId + '/status', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'status=' + encodeURIComponent(radio.value)
                    + '&admin_note=' + encodeURIComponent(document.getElementById('rep-d-newnote').value)
                    + '&_ajax=1&csrf_token=' + encodeURIComponent(csrf),
            });
            const d = await res.json();
            btn.disabled = false; btn.innerHTML = oldHtml;
            msg.classList.remove('hidden');
            if (d.success) {
                msg.className = 'text-xs text-green-600';
                msg.textContent = 'Updated';
                const statusEl = document.getElementById('rep-d-status');
                statusEl.className = 'inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-medium ' + (STATUS_COLORS[d.status] || '');
                statusEl.textContent = d.status_label;
                repRowSetStatus(currentId, d.status);

                const note = document.getElementById('rep-d-newnote').value.trim();
                if (note) {
                    document.getElementById('rep-d-note-wrap').classList.remove('hidden');
                    document.getElementById('rep-d-note').textContent = note;
                    document.getElementById('rep-d-newnote').value = '';
                }
            } else {
                msg.className = 'text-xs text-red-600';
                msg.textContent = d.error || 'Error';
            }
        } catch (e) {
            btn.disabled = false; btn.innerHTML = oldHtml;
            msg.classList.remove('hidden');
            msg.className = 'text-xs text-red-600';
            msg.textContent = 'Network error';
        }
        setTimeout(() => msg.classList.add('hidden'), 3000);
    };

    window.repDeleteVideo = async function () {
        if (!currentId) return;
        var _t = (window._repSubjectType === 'album') ? 'gallery' : 'video';
        if (!confirm('DELETE this ' + _t + '? This will resolve all reports for it. This action cannot be undone.')) return;
        const btn = document.getElementById('rep-d-delvideo');
        btn.disabled = true;
        const oldHtml = btn.innerHTML;
        btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin text-[11px]"></i> Deleting…';
        try {
            const res = await fetch('/admin/reports/' + currentId + '/delete-' + ((window._repSubjectType === 'album') ? 'album' : 'video'), {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'csrf_token=' + encodeURIComponent(csrf),
            });
            const d = await res.json();
            if (d.success) {
                btn.innerHTML = '<i class="fa-regular fa-circle-check text-[11px]"></i> Deleted';
                btn.classList.remove('bg-red-600','hover:bg-red-700');
                btn.classList.add('bg-green-600');
                setTimeout(() => location.reload(), 1200);
            } else {
                btn.disabled = false; btn.innerHTML = oldHtml;
                alert(d.error || 'Error deleting video');
            }
        } catch (e) {
            btn.disabled = false; btn.innerHTML = oldHtml;
            alert('Network error');
        }
    };

    document.addEventListener('keydown', e => {
        if (e.key === 'Escape' && currentId) repClose();
    });

    if (preselectId) repOpen(preselectId);
})();
</script>
