const app = document.getElementById('app');
const toastEl = document.getElementById('toast');
const searchInput = document.getElementById('search-input');
const body = document.body;
let toastTimer = null;
let currentUser = null;
let currentRoute = 'home';
let autoplayMode = localStorage.getItem('vidhive_autoplay') || 'off';
function setAutoplayMode(m) { autoplayMode = m; localStorage.setItem('vidhive_autoplay', m); }
let autoplayIntent = false;
const THEME_ORDER = ['dark', 'light', 'classic'];
const THEME_ICONS = { dark: 'π', light: 'βοΈ', classic: 'π₯' };
const themeBtn = document.getElementById('theme-toggle');
function applyTheme(t) {
document.documentElement.setAttribute('data-theme', t);
if (themeBtn) {
themeBtn.textContent = THEME_ICONS[t] || 'π';
const next = THEME_ORDER[(THEME_ORDER.indexOf(t) + 1) % THEME_ORDER.length];
themeBtn.title = `Theme: ${t} β click for ${next}`;
}
}
function initTheme() {
const stored = localStorage.getItem('vidhive_theme');
const prefersLight = window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches;
applyTheme(stored || (prefersLight ? 'light' : 'dark'));
}
if (themeBtn) themeBtn.addEventListener('click', () => {
const current = document.documentElement.getAttribute('data-theme') || 'dark';
const next = THEME_ORDER[(THEME_ORDER.indexOf(current) + 1) % THEME_ORDER.length];
localStorage.setItem('vidhive_theme', next);
applyTheme(next);
});
initTheme();
const state = {
q: '',
channel: null,
sort: 'newest',
offset: 0,
limit: 24,
total: 0,
};
function esc(s) {
return String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
}
function fmtDur(sec) {
if (!sec || !isFinite(sec)) return '0:00';
sec = Math.floor(sec);
const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60), s = sec % 60;
if (h > 0) return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
return `${m}:${String(s).padStart(2, '0')}`;
}
function fmtTime(sec) {
sec = Math.floor(sec || 0);
const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60);
if (h > 0) return `${h}h ${m}m`;
if (m > 0) return `${m} min`;
return `${sec}s`;
}
function fmtDate(ts) {
if (!ts) return '';
const d = new Date(ts * 1000);
const diff = (Date.now() - d.getTime()) / 1000;
if (diff < 60) return 'just now';
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
if (diff < 2592000) return `${Math.floor(diff / 86400)}d ago`;
return d.toLocaleDateString();
}
function fmtViews(n) {
if (!n) return '0 views';
if (n < 1000) return `${n} views`;
if (n < 1e6) return `${(n / 1000).toFixed(1).replace(/\.0$/, '')}k views`;
return `${(n / 1e6).toFixed(1)}M views`;
}
async function api(path, opts) {
const res = await fetch(path, opts);
if (res.status === 401) {
showLoginScreen();
throw new Error('Unauthorized');
}
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try { const j = await res.json(); if (j && j.error) msg = j.error; } catch {}
throw new Error(msg);
}
return res.json();
}
function toast(msg) {
toastEl.textContent = msg;
toastEl.classList.add('show');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toastEl.classList.remove('show'), 2600);
}
async function getMe() {
const r = await fetch('/api/auth/me');
if (!r.ok) return null;
try { const j = await r.json(); return j.user || null; } catch { return null; }
}
function showLoginScreen() {
currentUser = null;
body.classList.add('logged-out');
document.getElementById('app-header').style.display = 'none';
app.innerHTML = `
`;
let authMode = 'login';
const titleEl = document.getElementById('login-title');
const subEl = document.getElementById('login-sub');
const submitEl = document.getElementById('login-submit');
const errEl = document.getElementById('login-error');
const setMode = (mode) => {
authMode = mode;
document.getElementById('mode-login').classList.toggle('active', mode === 'login');
document.getElementById('mode-register').classList.toggle('active', mode === 'register');
if (mode === 'login') {
titleEl.textContent = 'Welcome back'; subEl.textContent = 'Sign in to your account'; submitEl.textContent = 'Log in';
document.getElementById('login-password').autocomplete = 'current-password';
} else {
titleEl.textContent = 'Create account'; subEl.textContent = 'Pick a username and password (min 6 characters)'; submitEl.textContent = 'Create account';
document.getElementById('login-password').autocomplete = 'new-password';
}
errEl.textContent = '';
};
document.getElementById('mode-login').addEventListener('click', () => setMode('login'));
document.getElementById('mode-register').addEventListener('click', () => setMode('register'));
document.getElementById('login-form').addEventListener('submit', async (e) => {
e.preventDefault();
const username = document.getElementById('login-username').value.trim();
const password = document.getElementById('login-password').value;
errEl.textContent = '';
submitEl.disabled = true;
try {
const res = await fetch(`/api/auth/${authMode === 'login' ? 'login' : 'register'}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) { errEl.textContent = data.error || 'Something went wrong'; submitEl.disabled = false; return; }
currentUser = data.user;
if (location.hash !== '#/') { location.hash = '#/'; return; }
render();
} catch (err) {
errEl.textContent = 'Network error β is the server running?';
submitEl.disabled = false;
}
});
}
async function showApp(user) {
currentUser = user;
body.classList.remove('logged-out');
document.getElementById('app-header').style.display = '';
const initial = esc((user.username || '?').charAt(0).toUpperCase());
document.getElementById('user-area').innerHTML = `
${initial}
${esc(user.username)}
`;
document.getElementById('logout-btn').addEventListener('click', async () => {
try { await fetch('/api/auth/logout', { method: 'POST' }); } catch {}
currentUser = null;
render();
});
const status = await api('/api/status').catch(() => null);
if (status && status.lastRescanAt) {
document.getElementById('rescan-btn').title = `Rescan video folder (last: ${fmtDate(Math.floor(new Date(status.lastRescanAt).getTime() / 1000))})`;
}
}
function cardHtml(v) {
const dur = fmtDur(v.duration);
const progress = v.watched_position > 0 && v.duration > 0 ? Math.min(1, v.watched_position / v.duration) : 0;
const done = v.watch_completed || (progress >= 0.9);
return `
${dur}
${progress > 0 ? `
` : ''}
${esc(v.title)}
${esc(v.channel)} Β· ${fmtViews(v.views)}
`;
}
async function loadGrid() {
let url, noun;
if (currentRoute === 'favorites') {
url = `/api/favorites?limit=${state.limit}&offset=${state.offset}`;
noun = 'videos';
} else {
const q = state.q ? `&q=${encodeURIComponent(state.q)}` : '';
const ch = state.channel ? `&channel=${encodeURIComponent(state.channel)}` : '';
url = `/api/videos?limit=${state.limit}&offset=${state.offset}&sort=${encodeURIComponent(state.sort)}${q}${ch}`;
noun = state.q ? 'results' : 'videos';
}
try {
const data = await api(url);
state.total = data.total;
const grid = document.getElementById('video-grid');
const empty = document.getElementById('empty-msg');
if (state.offset === 0) {
if (data.videos.length === 0) {
grid.innerHTML = '';
empty.style.display = 'block';
} else {
empty.style.display = 'none';
grid.innerHTML = data.videos.map(cardHtml).join('');
}
} else {
data.videos.forEach(v => grid.insertAdjacentHTML('beforeend', cardHtml(v)));
}
const loadMoreBtn = document.getElementById('load-more');
if (loadMoreBtn) {
loadMoreBtn.style.display = state.offset + data.videos.length < state.total ? 'block' : 'none';
}
const countEl = document.getElementById('result-count');
if (countEl) countEl.textContent = `${state.total} ${noun}`;
} catch (err) {
if (err.message !== 'Unauthorized') toast('Failed to load videos: ' + err.message);
}
}
function wireGridControls() {
const sortSelect = document.getElementById('sort-select');
if (sortSelect) {
sortSelect.value = state.sort;
sortSelect.addEventListener('change', () => { state.sort = sortSelect.value; state.offset = 0; loadGrid(); });
}
const loadMoreBtn = document.getElementById('load-more');
if (loadMoreBtn) {
loadMoreBtn.addEventListener('click', () => { state.offset += state.limit; loadGrid(); });
}
}
async function renderHome() {
currentRoute = 'home';
const channels = await api('/api/channels').catch(() => []);
const historyItems = await api('/api/history?limit=8').catch(() => []);
const continueWatching = historyItems.filter(h => !h.completed && h.position > 0 && (h.duration || h.watch_duration) > 0 && h.position < (h.duration || h.watch_duration) * 0.95).slice(0, 8);
app.innerHTML = `
${continueWatching.length ? `
Continue watching
${continueWatching.map(v => {
const dur = v.duration || v.watch_duration || 0;
const p = dur > 0 ? Math.min(1, v.position / dur) : 0;
return `
${fmtDur(v.duration)}
${esc(v.title)}
${fmtDate(v.watched_at)} Β· ${Math.round(p * 100)}% watched
`;
}).join('')}
` : ''}
${state.q ? 'Search results' : 'All videos'}
${channels.map(c => ``).join('')}
π¬
${state.q ? 'No videos match your search.' : 'No videos found. Drop video files into the video folder and click β³ to rescan.'}
`;
wireGridControls();
document.getElementById('channel-chips').addEventListener('click', (e) => {
const btn = e.target.closest('.chip');
if (!btn) return;
state.channel = btn.dataset.channel || null;
state.offset = 0;
renderHome();
});
await loadGrid();
}
async function renderChannel(name) {
currentRoute = 'channel';
const channels = await api('/api/channels').catch(() => []);
const channel = channels.find(c => c.name === name);
const stats = await api(`/api/channel/${encodeURIComponent(name)}/stats`).catch(() => null);
searchInput.value = '';
app.innerHTML = `
${esc(name)}
${stats ? `
${stats.videos} videos
${fmtTime(stats.totalSeconds)} total
${fmtTime(stats.watchedSeconds)} watched by you
${stats.completedCount} completed
` : ''}
πΊ
No videos in this channel yet.
`;
state.channel = name;
state.q = '';
state.offset = 0;
wireGridControls();
await loadGrid();
}
async function renderFavorites() {
currentRoute = 'favorites';
searchInput.value = '';
app.innerHTML = `
Favorites
β
No favorites yet. Click the star on any video to add it here.
`;
state.offset = 0;
wireGridControls();
await loadGrid();
}
async function renderHistory() {
currentRoute = 'history';
const items = await api('/api/history?limit=50').catch(() => []);
app.innerHTML = `
Watch history ${items.length} videos
${items.length ? items.map(v => {
const p = v.duration > 0 ? Math.min(1, v.position / v.duration) : 0;
return `
${esc(v.title)}
${esc(v.channel)} Β· ${fmtDate(v.watched_at)}
${v.completed ? 'β Watched' : fmtDur(v.position) + ' / ' + fmtDur(v.duration || 0)}
`;
}).join('') : `π
Nothing watched yet. Play something and it will show up here.
`}`;
}
async function renderPlaylists() {
currentRoute = 'playlists';
searchInput.value = '';
const playlists = await api('/api/playlists').catch(() => []);
app.innerHTML = `
Playlists ${playlists.length}
${playlists.map(p => `
${esc(p.name)}
${p.count} video${p.count === 1 ? '' : 's'} Β· ${fmtDate(p.created_at)}
`).join('') || `
π
No playlists yet. Create one above, then add videos from the watch page.
`}
`;
document.getElementById('new-playlist-form').addEventListener('submit', async (e) => {
e.preventDefault();
const name = document.getElementById('new-playlist-name').value.trim();
if (!name) return;
try {
await api('/api/playlists', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }) });
toast(`Created "${name}"`);
renderPlaylists();
} catch (err) { toast(err.message); }
});
app.querySelectorAll('[data-delete-playlist]').forEach(btn => btn.addEventListener('click', async (e) => {
e.stopPropagation();
if (!confirm('Delete this playlist? Videos are not deleted.')) return;
try {
await api(`/api/playlists/${btn.dataset.deletePlaylist}`, { method: 'DELETE' });
renderPlaylists();
} catch (err) { toast(err.message); }
}));
}
async function renderPlaylistDetail(id) {
currentRoute = 'playlists';
const data = await api(`/api/playlists/${id}`).catch(() => null);
if (!data) {
app.innerHTML = ``;
return;
}
const { playlist, videos } = data;
app.innerHTML = `
β All playlists
${esc(playlist.name)} ${videos.length} videos
${videos.length ? videos.map((v, i) => `
${i + 1}
${esc(v.title)}
${fmtDur(v.duration)} Β· ${fmtViews(v.views)}
`).join('') : `π
This playlist is empty. Add videos from the watch page.
`}`;
const ids = videos.map(v => v.id);
app.querySelectorAll('.pl-row').forEach(row => {
const rowId = parseInt(row.dataset.id, 10);
const upBtn = row.querySelector('[data-move="up"]');
const downBtn = row.querySelector('[data-move="down"]');
const removeBtn = row.querySelector('[data-remove]');
const idx = ids.indexOf(rowId);
const move = (dir) => {
const j = idx + dir;
if (j < 0 || j >= ids.length) return;
[ids[idx], ids[j]] = [ids[j], ids[idx]];
api(`/api/playlists/${id}/reorder`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_ids: ids }) })
.then(() => renderPlaylistDetail(id))
.catch(err => toast(err.message));
};
if (upBtn) upBtn.addEventListener('click', () => move(-1));
if (downBtn) downBtn.addEventListener('click', () => move(1));
if (removeBtn) removeBtn.addEventListener('click', async () => {
try {
await api(`/api/playlists/${id}/items/${rowId}`, { method: 'DELETE' });
renderPlaylistDetail(id);
} catch (err) { toast(err.message); }
});
});
}
async function renderStats() {
currentRoute = 'stats';
searchInput.value = '';
const s = await api('/api/stats').catch(() => null);
if (!s) {
app.innerHTML = `π
Unable to load stats.
`;
return;
}
const maxSec = Math.max(1, ...s.daily.map(d => d.seconds));
const days = [];
for (let i = 13; i >= 0; i--) {
const d = new Date(Date.now() - i * 86400000);
days.push({ key: d.toISOString().slice(0, 10), label: d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }), seconds: 0 });
}
const byDay = {};
s.daily.forEach(d => { byDay[d.day] = d.seconds; });
days.forEach(d => { d.seconds = byDay[d.key] || 0; });
const maxSecAll = Math.max(1, ...s.topChannels.map(c => c.seconds));
const maxVideosSec = Math.max(1, ...s.topVideos.map(v => v.seconds));
app.innerHTML = `
Watch stats
${fmtTime(s.totalSeconds)}
Total watch time
${fmtTime(s.thisMonthSeconds)}
This month
${s.startedCount}
Videos started
${s.completedCount}
Completed
Last 14 days
${days.map(d => `
`).join('')}
Top channels
${s.topChannels.length ? s.topChannels.map((c, i) => `
${i + 1}
${esc(c.channel)}
${c.videos} videos
${fmtTime(c.seconds)}
`).join('') : '
No watch time yet.
'}
`;
}
let playerCleanup = null;
async function renderWatch(id) {
currentRoute = 'watch';
const shouldAutoplay = autoplayIntent;
autoplayIntent = false;
const data = await api(`/api/video/${id}`).catch(() => null);
if (!data) {
app.innerHTML = `π«
Video not found or no longer in the library.
`;
return;
}
const v = data.video;
const history = data.history;
const fav = !!data.favorite;
app.innerHTML = `
β Back to library
${esc(v.title)}
`;
try { api('/api/view', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: v.id }) }); } catch {}
const player = document.getElementById('player');
const wrap = document.getElementById('player-wrap');
let resumeAt = 0;
if (history && history.position > 5 && !history.completed && v.duration > 0 && history.position < v.duration * 0.95) {
resumeAt = history.position;
}
let lastSave = -1;
const saveProgress = (force = false) => {
if (!player.duration || !isFinite(player.duration)) return;
const pos = player.currentTime;
if (!force && Math.abs(pos - lastSave) < 1 && lastSave >= 0) return;
lastSave = pos;
api('/api/progress', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: v.id, position: pos, duration: player.duration }) }).catch(() => {});
};
const onLoaded = () => {
if (resumeAt > 0 && !player.dataset.resumed) {
player.currentTime = resumeAt;
player.dataset.resumed = '1';
}
if (shouldAutoplay) {
player.play().catch(() => {});
}
};
player.addEventListener('loadedmetadata', onLoaded);
const interval = setInterval(saveProgress, 10000);
const onPause = () => saveProgress(true);
const startNext = async () => {
if (autoplayMode === 'off') return;
try {
const r = await api(`/api/videos/${v.id}/next?mode=${autoplayMode}`);
if (!r.video) return;
autoplayIntent = true;
location.hash = `#/watch/${r.video.id}`;
} catch {}
};
const onEnded = () => {
saveProgress(true);
api('/api/progress', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: v.id, position: player.duration, duration: player.duration }) }).catch(() => {});
startNext();
};
const onError = () => {
wrap.innerHTML = 'β Unable to play this video. The file may be missing or unsupported.
';
};
player.addEventListener('pause', onPause);
player.addEventListener('ended', onEnded);
player.addEventListener('error', onError);
document.getElementById('autoplay-seg').addEventListener('click', (e) => {
const btn = e.target.closest('button[data-mode]');
if (!btn) return;
setAutoplayMode(btn.dataset.mode);
document.querySelectorAll('#autoplay-seg button').forEach(b => b.classList.toggle('active', b === btn));
});
const favBtn = document.getElementById('fav-btn');
favBtn.addEventListener('click', async () => {
try {
const r = await api('/api/favorite', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: v.id }) });
favBtn.textContent = r.favorite ? 'β
Favorited' : 'β Add to favorites';
toast(r.favorite ? 'Added to favorites' : 'Removed from favorites');
} catch (err) { if (err.message !== 'Unauthorized') toast('Error: ' + err.message); }
});
const panel = document.getElementById('playlist-panel');
const playlistBtn = document.getElementById('playlist-btn');
playlistBtn.addEventListener('click', async () => {
if (panel.style.display === 'none') {
panel.style.display = 'block';
await renderPlaylistPanel(panel, v.id);
} else {
panel.style.display = 'none';
}
});
playerCleanup = () => {
clearInterval(interval);
player.removeEventListener('loadedmetadata', onLoaded);
player.removeEventListener('pause', onPause);
player.removeEventListener('ended', onEnded);
player.removeEventListener('error', onError);
};
const related = await api(`/api/videos?channel=${encodeURIComponent(v.channel)}&sort=newest&limit=6`).catch(() => ({ videos: [] }));
const list = document.getElementById('related-list');
if (list) {
const others = related.videos.filter(x => x.id !== v.id).slice(0, 6);
list.innerHTML = others.length ? others.map(x => `
${esc(x.title)}
${fmtDur(x.duration)} Β· ${fmtViews(x.views)}
`).join('') : 'No other videos in this channel.
';
}
}
async function renderPlaylistPanel(panel, videoId) {
panel.innerHTML = 'Loading playlistsβ¦
';
const playlists = await api('/api/playlists').catch(() => []);
const details = await Promise.all(playlists.map(async p => {
try {
const d = await api(`/api/playlists/${p.id}`);
return { ...p, videos: d.videos };
} catch { return { ...p, videos: [] }; }
}));
panel.innerHTML = `
${details.length ? details.map(p => `
${esc(p.name)} (${p.videos.length})
${p.videos.some(x => x.id === videoId) ? 'β In playlist' : ''}
`).join('') : '
No playlists yet β create one below.
'}
`;
panel.querySelectorAll('.pl-item').forEach(item => {
item.addEventListener('click', async () => {
const pid = parseInt(item.dataset.playlistId, 10);
const isMember = item.querySelector('.check').textContent.trim() !== '';
try {
if (isMember) {
await api(`/api/playlists/${pid}/items/${videoId}`, { method: 'DELETE' });
} else {
await api(`/api/playlists/${pid}/items`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: videoId }) });
}
await renderPlaylistPanel(panel, videoId);
} catch (err) { toast(err.message); }
});
});
panel.querySelector('#panel-new-playlist').addEventListener('submit', async (e) => {
e.preventDefault();
const name = document.getElementById('panel-new-name').value.trim();
if (!name) return;
try {
const r = await api('/api/playlists', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }) });
await api(`/api/playlists/${r.id}/items`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: videoId }) });
await renderPlaylistPanel(panel, videoId);
} catch (err) { toast(err.message); }
});
}
async function render() {
const hash = location.hash.slice(2);
if (playerCleanup) { playerCleanup(); playerCleanup = null; }
const user = await getMe();
if (!user) { showLoginScreen(); return; }
showApp(user);
document.querySelectorAll('nav a[data-nav]').forEach(a => a.classList.toggle('active',
(hash === '' || hash === '/') && a.dataset.nav === 'home' ||
hash.startsWith('/playlists') && a.dataset.nav === 'playlists' ||
hash.startsWith('/favorites') && a.dataset.nav === 'favorites' ||
hash.startsWith('/history') && a.dataset.nav === 'history' ||
hash.startsWith('/stats') && a.dataset.nav === 'stats'));
const parts = hash.split('/').filter(Boolean);
if (parts[0] === 'channel' && parts[1]) {
await renderChannel(decodeURIComponent(parts.slice(1).join('/')));
} else if (parts[0] === 'watch' && parts[1]) {
await renderWatch(parseInt(parts[1], 10));
} else if (parts[0] === 'playlists' && parts[1]) {
await renderPlaylistDetail(parseInt(parts[1], 10));
} else if (parts[0] === 'playlists') {
await renderPlaylists();
} else if (parts[0] === 'favorites') {
state.q = ''; searchInput.value = '';
await renderFavorites();
} else if (parts[0] === 'history') {
await renderHistory();
} else if (parts[0] === 'stats') {
await renderStats();
} else {
currentRoute = 'home';
state.channel = null;
await renderHome();
}
}
app.addEventListener('click', (e) => {
const favBtn = e.target.closest('.fav-btn');
if (favBtn) {
e.preventDefault();
e.stopPropagation();
toggleFavoriteButton(favBtn);
return;
}
const link = e.target.closest('[data-href]');
if (link) {
e.preventDefault();
location.hash = link.dataset.href;
}
});
async function toggleFavoriteButton(btn) {
const id = parseInt(btn.dataset.videoId, 10);
try {
const r = await api('/api/favorite', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: id }) });
btn.classList.toggle('off', !r.favorite);
btn.textContent = r.favorite ? 'β
' : 'β';
toast(r.favorite ? 'Added to favorites' : 'Removed from favorites');
} catch (err) { if (err.message !== 'Unauthorized') toast('Error: ' + err.message); }
}
let searchTimer = null;
searchInput.addEventListener('input', () => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
state.q = searchInput.value.trim();
state.offset = 0;
if (location.hash !== '#/') {
location.hash = '#/';
} else {
renderHome();
}
}, 250);
});
document.getElementById('rescan-btn').addEventListener('click', async () => {
const btn = document.getElementById('rescan-btn');
btn.disabled = true; btn.textContent = 'β¦';
try {
const r = await api('/api/rescan', { method: 'POST' });
toast(`Rescan done β ${r.added} added, ${r.updated} updated, ${r.removed} removed`);
render();
} catch (err) { if (err.message !== 'Unauthorized') toast('Rescan failed: ' + err.message); }
finally { btn.disabled = false; btn.textContent = 'β³'; }
});
window.addEventListener('hashchange', render);
render();