Gemini Vibe Coding: Jukebox

I recently purchased an AsuStor AS6702T and installed Apache HTTP and PHP. I asked Gemini to create a Jukebox frontend to read and play music stored on the server. Features include selective scanning or exclusion of specific folders, album/song queuing, shuffle all, search and optional VU Meters. I will probably replace my instance of Moode Audio running on a Raspberry PI 5.

Save this as your index.html.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NAS Audio Player</title>
<style>
  :root {
    --bg: #12141a;
    --panel: #1b1f29;
    --panel-hover: #252b38;
    --border: #2c3344;
    --text: #e6eaf2;
    --muted: #8b95a8;
    --accent: #4f8cff;
    --accent-hover: #6aa0ff;
  }
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
    background: var(--bg);
    color: var(--text);
    height: 100vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  header {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
    padding: 12px 20px;
    background: var(--panel);
    border-bottom: 1px solid var(--border);
  }
  header h1 { font-size: 1.1rem; font-weight: 600; margin-right: auto; }
  input[type="search"] {
    background: var(--bg);
    border: 1px solid var(--border);
    color: var(--text);
    padding: 7px 12px;
    border-radius: 6px;
    width: 240px;
    outline: none;
  }
  input[type="search"]:focus { border-color: var(--accent); }
  button {
    background: var(--panel-hover);
    color: var(--text);
    border: 1px solid var(--border);
    padding: 7px 12px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 0.85rem;
  }
  button:hover { background: #31394a; }
  button:disabled { opacity: 0.5; cursor: not-allowed; }
  button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
  button.primary:hover { background: var(--accent-hover); }
  button.active { border-color: var(--accent); color: var(--accent); }

  .workspace {
    display: grid;
    grid-template-columns: 1fr 330px;
    flex: 1;
    min-height: 0;
  }
  .library {
    padding: 20px;
    overflow-y: auto;
  }
  .queue-pane {
    background: var(--panel);
    border-left: 1px solid var(--border);
    display: flex;
    flex-direction: column;
    min-height: 0;
  }
  .queue-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 14px 16px;
    border-bottom: 1px solid var(--border);
    font-weight: 600;
    font-size: 0.95rem;
  }
  .queue-list {
    flex: 1;
    overflow-y: auto;
    padding: 8px;
  }
  .queue-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 10px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 0.85rem;
  }
  .queue-item:hover { background: var(--panel-hover); }
  .queue-item.playing { background: rgba(79, 140, 255, 0.18); border-left: 3px solid var(--accent); }
  .queue-item .q-info { flex: 1; min-width: 0; }
  .queue-item .q-title { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: 500; }
  .queue-item .q-sub { font-size: 0.75rem; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .queue-item .q-rm { background: none; border: none; color: var(--muted); padding: 2px 6px; }
  .queue-item .q-rm:hover { color: #ff6b6b; background: none; }

  .album-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(175px, 1fr));
    gap: 16px;
  }
  .album-card {
    background: var(--panel);
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 12px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    transition: transform 0.12s;
  }
  .album-card:hover { background: var(--panel-hover); transform: translateY(-2px); }
  .album-art {
    width: 100%;
    aspect-ratio: 1;
    background: #232836;
    border-radius: 6px;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2.2rem;
    color: var(--muted);
    cursor: pointer;
  }
  .album-art img { width: 100%; height: 100%; object-fit: cover; }
  .album-title { font-weight: 600; font-size: 0.9rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: pointer; }
  .album-artist { font-size: 0.8rem; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .album-actions { display: flex; gap: 6px; margin-top: auto; }
  .album-actions button { flex: 1; padding: 5px; font-size: 0.78rem; }

  .album-detail-header {
    display: flex;
    gap: 20px;
    align-items: flex-end;
    margin-bottom: 20px;
  }
  .album-detail-header .album-art { width: 140px; height: 140px; flex-shrink: 0; }
  .track-table { width: 100%; border-collapse: collapse; font-size: 0.88rem; }
  .track-table th { text-align: left; color: var(--muted); font-weight: 500; padding: 8px 10px; border-bottom: 1px solid var(--border); }
  .track-table td { padding: 9px 10px; border-bottom: 1px solid #1f2430; }
  .track-table tr:hover td { background: var(--panel-hover); }
  .badge {
    font-size: 0.7rem;
    padding: 2px 6px;
    border-radius: 4px;
    background: #2a3142;
    color: var(--muted);
    font-weight: 600;
  }
  .badge.flac { color: #7ce8a5; background: rgba(124, 232, 165, 0.12); }

  .scan-box {
    max-width: 520px;
    margin: 60px auto;
    background: var(--panel);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 24px;
  }
  .scan-header {
    display: flex;
    justify-content: space-between;
    font-size: 0.95rem;
    font-weight: 600;
    margin-bottom: 12px;
  }
  .scan-track {
    width: 100%;
    height: 10px;
    background: var(--bg);
    border-radius: 99px;
    overflow: hidden;
    margin-bottom: 10px;
  }
  .scan-fill {
    height: 100%;
    width: 0%;
    background: var(--accent);
    transition: width 0.12s linear;
  }
  .scan-file {
    font-size: 0.78rem;
    color: var(--muted);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
/* On-Screen Keyboard */
  .osk-panel {
    display: none;
    position: fixed;
    bottom: 88px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1000;
    background: var(--panel);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 12px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.7);
    width: min(680px, 96vw);
    user-select: none;
  }
  .osk-panel.visible { display: block; }
  .osk-row {
    display: flex;
    justify-content: center;
    gap: 6px;
    margin-bottom: 6px;
  }
  .osk-row:last-child { margin-bottom: 0; }
  .osk-key {
    flex: 1;
    min-width: 0;
    height: 44px;
    font-size: 0.95rem;
    font-weight: 500;
    background: var(--panel-hover);
    color: var(--text);
    border: 1px solid var(--border);
    border-radius: 6px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .osk-key:hover { background: #31394a; }
  .osk-key:active { background: var(--accent); color: #fff; }
  .osk-key.wide { flex: 1.6; }
  .osk-key.space { flex: 4.5; }
  .osk-key.accent { background: var(--accent); border-color: var(--accent); color: #fff; }
  
  .folder-panel {
    max-width: 680px;
    margin: 10px auto;
    background: var(--panel);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 20px;
  }
  .folder-mode {
    display: flex;
    gap: 16px;
    margin: 14px 0;
    font-size: 0.9rem;
  }
  .folder-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
    gap: 8px;
    max-height: 50vh;
    overflow-y: auto;
    padding: 10px;
    background: var(--bg);
    border: 1px solid var(--border);
    border-radius: 6px;
    margin-bottom: 16px;
  }
  .folder-item {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 0.85rem;
    cursor: pointer;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  /* Analog VU Meter Dock */
  .vu-dock {
    display: none;
    justify-content: center;
    background: #141112;
    border-top: 1px solid var(--border);
    padding: 10px 16px;
  }
  .vu-dock.visible { display: flex; }
  .vu-bezel {
    background: #060606;
    border: 3px solid #2b2627;
    border-radius: 4px;
    padding: 6px;
    box-shadow: inset 0 0 12px rgba(0, 0, 0, 0.9), 0 4px 14px rgba(0, 0, 0, 0.6);
    display: flex;
    gap: 8px;
    max-width: 100%;
  }
  .vu-bezel canvas {
    display: block;
    width: 270px;
    height: 145px;
    border-radius: 2px;
  }

  footer.player {
    background: var(--panel);
    border-top: 1px solid var(--border);
    padding: 12px 20px;
    display: grid;
    grid-template-columns: 280px 1fr 180px;
    align-items: center;
    gap: 20px;
  }
  .now-playing { display: flex; align-items: center; gap: 12px; min-width: 0; }
  .np-art { width: 48px; height: 48px; border-radius: 6px; background: #232836; overflow: hidden; flex-shrink: 0; display: flex; align-items: center; justify-content: center; }
  .np-art img { width: 100%; height: 100%; object-fit: cover; }
  .np-meta { min-width: 0; }
  .np-title { font-weight: 600; font-size: 0.9rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .np-sub { font-size: 0.78rem; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

  .controls-wrap { display: flex; flex-direction: column; align-items: center; gap: 6px; }
  .controls { display: flex; align-items: center; gap: 10px; }
  .seek-row { display: flex; align-items: center; gap: 10px; width: 100%; max-width: 560px; font-size: 0.75rem; color: var(--muted); }
  input[type="range"] { accent-color: var(--accent); cursor: pointer; }
  #seekBar { flex: 1; }
  .volume-wrap { display: flex; align-items: center; justify-content: flex-end; gap: 8px; }
  #volumeBar { width: 100px; }

  @media (max-width: 860px) {
    .workspace { grid-template-columns: 1fr; }
    .queue-pane { display: none; }
    footer.player { grid-template-columns: 1fr; gap: 10px; }
  }
  @media (max-width: 620px) {
    .vu-bezel canvas { width: 155px; height: 84px; }
  }
</style>
</head>
<body>

<header>
  <h1>NAS Music</h1>
  <button id="btnAlbums" class="active">Albums</button>
  <button id="btnTracks">All Songs</button>
  <input type="search" id="searchInput" placeholder="Search songs, artists, albums...">
  <button id="btnGlobalShuffle" title="Play randomly from the entire library">⇄ Shuffle All</button>
  <button id="btnVu" title="Toggle Analog VU Meters">VU Meters</button>
  <button id="btnFolders" title="Choose folders to include or exclude">Folders</button>
  <button id="btnRescan" title="Rescan NAS directory">Rescan</button>
</header>

<div class="workspace">
  <main class="library" id="libraryView">Loading library...</main>
  <aside class="queue-pane">
    <div class="queue-header">
      <span>Queue (<span id="queueCount">0</span>)</span>
      <button id="btnClearQueue" style="padding:4px 8px;font-size:0.75rem;">Clear</button>
    </div>
    <div class="queue-list" id="queueList"></div>
  </aside>
</div>

<div class="vu-dock" id="vuDock">
  <div class="vu-bezel">
    <canvas id="vuLeft"></canvas>
    <canvas id="vuRight"></canvas>
  </div>
</div>

<footer class="player">
  <div class="now-playing">
    <div class="np-art" id="npArt">♫</div>
    <div class="np-meta">
      <div class="np-title" id="npTitle">Not Playing</div>
      <div class="np-sub" id="npSub">—</div>
    </div>
  </div>

  <div class="controls-wrap">
    <div class="controls">
      <button id="btnShuffle" title="Shuffle Queue">⇄</button>
      <button id="btnPrev" title="Previous">⏮</button>
      <button id="btnPlay" class="primary" style="min-width:46px;">▶</button>
      <button id="btnNext" title="Next">⏭</button>
      <button id="btnRepeat" title="Repeat">↻</button>
    </div>
    <div class="seek-row">
      <span id="curTime">0:00</span>
      <input type="range" id="seekBar" min="0" max="100" value="0" step="0.1">
      <span id="durTime">0:00</span>
    </div>
  </div>

  <div class="volume-wrap">
    <span>🔊</span>
    <input type="range" id="volumeBar" min="0" max="1" step="0.02" value="0.85">
  </div>
</footer>
<div class="osk-panel" id="oskPanel"></div>
<audio id="audio"></audio>

<script>
const STORAGE_KEY = 'nas_music_session_v1';

const state = {
  tracks: [],
  albums: [],
  view: 'albums',      // 'albums' | 'albumDetail' | 'tracks'
  selectedAlbumIdx: -1,
  query: '',
  queue: [],
  queueIndex: -1,
  shuffle: false,
  repeat: false,
  globalShuffle: false
};

const audio = document.getElementById('audio');
audio.volume = 0.85;

const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const artUrl = p => p ? `api.php?action=art&file=${encodeURIComponent(p)}` : null;
const streamUrl = p => `api.php?action=stream&file=${encodeURIComponent(p)}`;
const fmtTime = s => {
  if (!isFinite(s)) return '0:00';
  const m = Math.floor(s / 60), sec = Math.floor(s % 60);
  return `${m}:${sec < 10 ? '0' : ''}${sec}`;
};

async function fetchJson(url, options) {
  const res = await fetch(url, options);
  const text = await res.text();
  if (!text) throw new Error(`Empty response from server (HTTP ${res.status})`);
  try {
    return JSON.parse(text);
  } catch {
    throw new Error(`Invalid JSON (HTTP ${res.status}): ${text.slice(0, 140)}`);
  }
}

// --- Session Persistence ---
function saveSession() {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify({
      queue: state.queue,
      queueIndex: state.queueIndex,
      currentTime: audio.currentTime || 0,
      volume: audio.volume,
      shuffle: state.shuffle,
      repeat: state.repeat,
      globalShuffle: state.globalShuffle
    }));
  } catch (e) {
    // Ignore storage quota errors
  }
}

function restoreSession() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return;
    const saved = JSON.parse(raw);

    if (typeof saved.volume === 'number') {
      audio.volume = saved.volume;
      document.getElementById('volumeBar').value = saved.volume;
    }
    if (saved.shuffle) {
      state.shuffle = true;
      document.getElementById('btnShuffle').classList.add('active');
    }
    if (saved.repeat) {
      state.repeat = true;
      document.getElementById('btnRepeat').classList.add('active');
    }
    if (saved.globalShuffle) {
      state.globalShuffle = true;
      document.getElementById('btnGlobalShuffle').classList.add('active');
    }

    if (Array.isArray(saved.queue) && saved.queue.length) {
      state.queue = saved.queue;
      const idx = (saved.queueIndex >= 0 && saved.queueIndex < saved.queue.length) ? saved.queueIndex : 0;
      state.queueIndex = idx;

      const t = state.queue[idx];
      audio.src = streamUrl(t.file);
      document.getElementById('npTitle').textContent = t.title;
      document.getElementById('npSub').textContent = `${t.artist} — ${t.album} (${t.format})`;
      document.getElementById('npArt').innerHTML = t.art ? `<img src="${artUrl(t.art)}">` : '♫';
      document.getElementById('btnPlay').textContent = '▶';

      if (saved.currentTime > 0) {
        audio.addEventListener('loadedmetadata', () => {
          if (saved.currentTime < audio.duration) {
            audio.currentTime = saved.currentTime;
            document.getElementById('curTime').textContent = fmtTime(saved.currentTime);
            document.getElementById('durTime').textContent = fmtTime(audio.duration);
            document.getElementById('seekBar').value = (saved.currentTime / audio.duration) * 100;
          }
        }, { once: true });
      }
    }
  } catch (e) {
    // Ignore corrupted storage
  }
}

// --- Library & Scanning ---
async function loadLibrary() {
  const el = document.getElementById('libraryView');
  el.innerHTML = 'Loading library...';
  try {
    const data = await fetchJson('api.php?action=library');
    if (data.error) {
      el.innerHTML = `<p style="color:#ff6b6b;">Error: ${esc(data.error)}</p>`;
      return;
    }
    if (data.needs_scan) {
      openFolderConfig();
      return;
    }
    state.tracks = (data.tracks || []).map((t, i) => ({ ...t, _idx: i }));
    buildAlbums();
    renderLibrary();
  } catch (err) {
    el.innerHTML = `<p style="color:#ff6b6b;">Failed to load library: ${esc(err.message)}</p>`;
  }
}

async function openFolderConfig() {
  const el = document.getElementById('libraryView');
  el.innerHTML = 'Loading folders...';
  try {
    const data = await fetchJson('api.php?action=folders');
    if (data.error) {
      el.innerHTML = `<p style="color:#ff6b6b;">Error: ${esc(data.error)}</p>`;
      return;
    }
    const folders = data.folders || [];
    const cfg = data.config || { mode: 'exclude', folders: [] };
    const selectedSet = new Set(cfg.folders);

    el.innerHTML = `
      <div class="folder-panel">
        <h2>Scan Folders</h2>
        <div class="folder-mode">
          <label><input type="radio" name="scanMode" value="include" ${cfg.mode === 'include' ? 'checked' : ''}> Include <strong>only</strong> checked folders</label>
          <label><input type="radio" name="scanMode" value="exclude" ${cfg.mode === 'exclude' ? 'checked' : ''}> Exclude checked folders</label>
        </div>
        <div style="margin-bottom:10px;display:flex;gap:8px;">
          <button onclick="document.querySelectorAll('.folder-cb').forEach(c=>c.checked=true)">Check All</button>
          <button onclick="document.querySelectorAll('.folder-cb').forEach(c=>c.checked=false)">Uncheck All</button>
        </div>
        <div class="folder-grid">
          ${folders.map(f => `
            <label class="folder-item" title="${esc(f)}">
              <input type="checkbox" class="folder-cb" value="${esc(f)}" ${selectedSet.has(f) ? 'checked' : ''}>
              <span>${esc(f)}</span>
            </label>
          `).join('')}
        </div>
        <div style="display:flex;gap:10px;">
          <button class="primary" onclick="saveFolderConfig()">Save & Rescan</button>
          <button onclick="renderLibrary()">Cancel</button>
        </div>
      </div>
    `;
  } catch (err) {
    el.innerHTML = `<p style="color:#ff6b6b;">Failed to load folders: ${esc(err.message)}</p>`;
  }
}

async function saveFolderConfig() {
  const mode = document.querySelector('input[name="scanMode"]:checked')?.value || 'exclude';
  const folders = Array.from(document.querySelectorAll('.folder-cb:checked')).map(cb => cb.value);

  try {
    const data = await fetchJson('api.php?action=save_config', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ mode, folders })
    });
    if (data.error) {
      alert(data.error);
      return;
    }
    startScan();
  } catch (err) {
    alert('Failed to save config: ' + err.message);
  }
}

function startScan() {
  const el = document.getElementById('libraryView');
  const btn = document.getElementById('btnRescan');
  btn.disabled = true;

  el.innerHTML = `
    <div class="scan-box">
      <div class="scan-header">
        <span id="scanLabel">Scanning NAS directory...</span>
        <span id="scanPct">0%</span>
      </div>
      <div class="scan-track"><div class="scan-fill" id="scanFill"></div></div>
      <div class="scan-file" id="scanFile">Preparing...</div>
    </div>
  `;

  const es = new EventSource('api.php?action=scan');

  es.onmessage = e => {
    const msg = JSON.parse(e.data);
    if (msg.status === 'counting') {
      document.getElementById('scanFile').textContent = msg.message;
    } else if (msg.status === 'scanning') {
      const pct = msg.total ? Math.round((msg.current / msg.total) * 100) : 100;
      document.getElementById('scanLabel').textContent = `Scanning (${msg.current} / ${msg.total})`;
      document.getElementById('scanPct').textContent = `${pct}%`;
      document.getElementById('scanFill').style.width = `${pct}%`;
      document.getElementById('scanFile').textContent = msg.file;
    } else if (msg.status === 'error') {
      es.close();
      btn.disabled = false;
      el.innerHTML = `<p style="color:#ff6b6b;">${esc(msg.message)}</p>`;
    } else if (msg.status === 'done') {
      es.close();
      btn.disabled = false;
      loadLibrary();
    }
  };

  es.onerror = () => {
    es.close();
    btn.disabled = false;
    el.innerHTML = `<p style="color:#ff6b6b;">Scan connection interrupted. Click Rescan to try again.</p>`;
  };
}

function buildAlbums() {
  const map = new Map();
  for (const t of state.tracks) {
    const key = t.album;
    if (!map.has(key)) {
      map.set(key, { name: t.album, artist: t.artist, year: t.year, art: t.art, tracks: [] });
    }
    const alb = map.get(key);
    alb.tracks.push(t);
    if (!alb.art && t.art) alb.art = t.art;
  }
  state.albums = Array.from(map.values())
    .sort((a, b) => a.name.localeCompare(b.name))
    .map((a, i) => ({ ...a, _idx: i }));
}

function renderLibrary() {
  const el = document.getElementById('libraryView');
  const q = state.query.toLowerCase();

  if (state.view === 'albums') {
    const list = state.albums.filter(a =>
      !q || a.name.toLowerCase().includes(q) || a.artist.toLowerCase().includes(q)
    );
    if (!list.length) { el.innerHTML = '<p style="color:var(--muted)">No matching albums found.</p>'; return; }

    el.innerHTML = `<div class="album-grid">${list.map(a => `
      <div class="album-card">
        <div class="album-art" onclick="openAlbum(${a._idx})">
          ${a.art ? `<img src="${artUrl(a.art)}" loading="lazy">` : '♫'}
        </div>
        <div class="album-title" title="${esc(a.name)}" onclick="openAlbum(${a._idx})">${esc(a.name)}</div>
        <div class="album-artist" title="${esc(a.artist)}">${esc(a.artist)} • ${a.tracks.length} tracks</div>
        <div class="album-actions">
          <button class="primary" onclick="playAlbum(${a._idx})">Play</button>
          <button onclick="queueAlbum(${a._idx})">+ Queue</button>
        </div>
      </div>
    `).join('')}</div>`;
  }
  else if (state.view === 'albumDetail' && state.albums[state.selectedAlbumIdx]) {
    const a = state.albums[state.selectedAlbumIdx];
    el.innerHTML = `
      <button onclick="setView('albums')" style="margin-bottom:14px;">← Back to Albums</button>
      <div class="album-detail-header">
        <div class="album-art">${a.art ? `<img src="${artUrl(a.art)}">` : '♫'}</div>
        <div>
          <h2 style="margin-bottom:4px;">${esc(a.name)}</h2>
          <p style="color:var(--muted);margin-bottom:12px;">${esc(a.artist)} ${a.year ? '• ' + esc(a.year) : ''} • ${a.tracks.length} tracks</p>
          <button class="primary" onclick="playAlbum(${a._idx})">▶ Play Album</button>
          <button onclick="queueAlbum(${a._idx})">+ Queue Album</button>
        </div>
      </div>
      ${renderTrackTable(a.tracks)}
    `;
  }
  else {
    const list = state.tracks.filter(t =>
      !q || t.title.toLowerCase().includes(q) || t.artist.toLowerCase().includes(q) || t.album.toLowerCase().includes(q)
    );
    el.innerHTML = list.length ? renderTrackTable(list) : '<p style="color:var(--muted)">No matching songs found.</p>';
  }
}

function renderTrackTable(tracks) {
  return `<table class="track-table">
    <thead><tr><th style="width:40px">#</th><th>Title</th><th>Artist</th><th>Album</th><th style="width:65px">Format</th><th style="width:140px"></th></tr></thead>
    <tbody>${tracks.map(t => `
      <tr>
        <td style="color:var(--muted)">${t.track || '—'}</td>
        <td>${esc(t.title)}</td>
        <td style="color:var(--muted)">${esc(t.artist)}</td>
        <td style="color:var(--muted)">${esc(t.album)}</td>
        <td><span class="badge ${t.format === 'FLAC' ? 'flac' : ''}">${esc(t.format)}</span></td>
        <td style="text-align:right;white-space:nowrap;">
          <button onclick="playSingle(${t._idx})">▶</button>
          <button onclick="queueSingle(${t._idx})">+ Queue</button>
        </td>
      </tr>
    `).join('')}</tbody>
  </table>`;
}

// --- Queue, Playback & Global Shuffle ---
function openAlbum(idx) {
  state.selectedAlbumIdx = idx;
  state.view = 'albumDetail';
  renderLibrary();
}

function playAlbum(idx) {
  const a = state.albums[idx];
  if (!a) return;
  state.queue = [...a.tracks];
  playIndex(0);
}

function queueAlbum(idx) {
  const a = state.albums[idx];
  if (!a) return;
  const wasEmpty = state.queue.length === 0;
  state.queue.push(...a.tracks);
  renderQueue();
  if (wasEmpty) playIndex(0);
}

function playSingle(trackIdx) {
  const t = state.tracks[trackIdx];
  if (!t) return;
  const insertAt = state.queueIndex + 1;
  state.queue.splice(insertAt, 0, t);
  playIndex(insertAt);
}

function queueSingle(trackIdx) {
  const t = state.tracks[trackIdx];
  if (!t) return;
  const wasEmpty = state.queue.length === 0;
  state.queue.push(t);
  renderQueue();
  if (wasEmpty) playIndex(0);
}

function playRandomFromLibrary() {
  if (!state.tracks.length) return;
  const curFile = state.queue[state.queueIndex]?.file;
  let pick;
  if (state.tracks.length === 1) {
    pick = state.tracks[0];
  } else {
    do {
      pick = state.tracks[Math.floor(Math.random() * state.tracks.length)];
    } while (pick.file === curFile);
  }
  state.queue.push(pick);
  playIndex(state.queue.length - 1);
}

function playIndex(idx) {
  if (idx < 0 || idx >= state.queue.length) return;
  state.queueIndex = idx;
  const t = state.queue[idx];
  audio.src = streamUrl(t.file);
  audio.play();
  document.getElementById('npTitle').textContent = t.title;
  document.getElementById('npSub').textContent = `${t.artist} — ${t.album} (${t.format})`;
  document.getElementById('npArt').innerHTML = t.art ? `<img src="${artUrl(t.art)}">` : '♫';
  document.getElementById('btnPlay').textContent = '⏸';
  renderQueue();
}

function removeFromQueue(idx, ev) {
  ev.stopPropagation();
  state.queue.splice(idx, 1);
  if (idx < state.queueIndex) state.queueIndex--;
  else if (idx === state.queueIndex) {
    if (state.queue.length) playIndex(Math.min(idx, state.queue.length - 1));
    else { audio.pause(); audio.src = ''; state.queueIndex = -1; }
  }
  renderQueue();
}

function renderQueue() {
  document.getElementById('queueCount').textContent = state.queue.length;
  const el = document.getElementById('queueList');
  if (!state.queue.length) {
    el.innerHTML = '<p style="color:var(--muted);padding:12px;font-size:0.85rem;">Queue is empty.</p>';
  } else {
    el.innerHTML = state.queue.map((t, i) => `
      <div class="queue-item ${i === state.queueIndex ? 'playing' : ''}" onclick="playIndex(${i})">
        <div class="q-info">
          <div class="q-title">${esc(t.title)}</div>
          <div class="q-sub">${esc(t.artist)} • ${esc(t.album)}</div>
        </div>
        <button class="q-rm" onclick="removeFromQueue(${i}, event)" title="Remove">✕</button>
      </div>
    `).join('');
  }
  saveSession();
}

function playNext() {
  if (state.globalShuffle) {
    if (state.queueIndex + 1 < state.queue.length) {
      playIndex(state.queueIndex + 1);
    } else {
      playRandomFromLibrary();
    }
    return;
  }
  if (!state.queue.length) return;
  if (state.shuffle && state.queue.length > 1) {
    let next;
    do { next = Math.floor(Math.random() * state.queue.length); } while (next === state.queueIndex);
    playIndex(next);
  } else if (state.queueIndex + 1 < state.queue.length) {
    playIndex(state.queueIndex + 1);
  } else if (state.repeat) {
    playIndex(0);
  }
}

function playPrev() {
  if (!state.queue.length) return;
  if (audio.currentTime > 3) { audio.currentTime = 0; return; }
  if (state.queueIndex > 0) playIndex(state.queueIndex - 1);
}

function setView(v) {
  state.view = v;
  document.getElementById('btnAlbums').classList.toggle('active', v === 'albums' || v === 'albumDetail');
  document.getElementById('btnTracks').classList.toggle('active', v === 'tracks');
  renderLibrary();
}

// --- Event Listeners ---
document.getElementById('btnAlbums').onclick = () => setView('albums');
document.getElementById('btnTracks').onclick = () => setView('tracks');
document.getElementById('btnFolders').onclick = () => openFolderConfig();
document.getElementById('btnRescan').onclick = () => startScan();
document.getElementById('btnClearQueue').onclick = () => {
  state.queue = []; state.queueIndex = -1; audio.pause(); audio.src = '';
  document.getElementById('btnPlay').textContent = '▶';
  renderQueue();
};
document.getElementById('searchInput').oninput = e => { state.query = e.target.value; renderLibrary(); };

document.getElementById('btnGlobalShuffle').onclick = e => {
  state.globalShuffle = !state.globalShuffle;
  e.target.classList.toggle('active', state.globalShuffle);
  if (state.globalShuffle && state.tracks.length) {
    playRandomFromLibrary();
  }
  saveSession();
};

document.getElementById('btnPlay').onclick = () => {
  if (!audio.src) {
    if (state.queue.length) playIndex(0);
    else if (state.globalShuffle && state.tracks.length) playRandomFromLibrary();
    return;
  }
  if (audio.paused) { audio.play(); document.getElementById('btnPlay').textContent = '⏸'; }
  else { audio.pause(); document.getElementById('btnPlay').textContent = '▶'; }
};
document.getElementById('btnNext').onclick = playNext;
document.getElementById('btnPrev').onclick = playPrev;
document.getElementById('btnShuffle').onclick = e => {
  state.shuffle = !state.shuffle; e.target.classList.toggle('active', state.shuffle); saveSession();
};
document.getElementById('btnRepeat').onclick = e => {
  state.repeat = !state.repeat; e.target.classList.toggle('active', state.repeat); saveSession();
};

let lastTimeSave = 0;
audio.addEventListener('timeupdate', () => {
  if (audio.duration) {
    document.getElementById('seekBar').value = (audio.currentTime / audio.duration) * 100;
    document.getElementById('curTime').textContent = fmtTime(audio.currentTime);
    document.getElementById('durTime').textContent = fmtTime(audio.duration);
  }
  const now = Date.now();
  if (now - lastTimeSave > 5000) {
    lastTimeSave = now;
    saveSession();
  }
});
audio.addEventListener('ended', playNext);
audio.addEventListener('pause', saveSession);
window.addEventListener('beforeunload', saveSession);

document.getElementById('seekBar').oninput = e => {
  if (audio.duration) audio.currentTime = (e.target.value / 100) * audio.duration;
};
document.getElementById('volumeBar').oninput = e => { audio.volume = parseFloat(e.target.value); };
document.getElementById('volumeBar').addEventListener('change', saveSession);

// --- Vintage Analog VU Meters (Web Audio Stereo) ---
const vuDock   = document.getElementById('vuDock');
const btnVu    = document.getElementById('btnVu');
const vuLeftC  = document.getElementById('vuLeft');
const vuRightC = document.getElementById('vuRight');

let vuVisible = false;
let audioCtx = null, analyserL = null, analyserR = null;
let dataL = null, dataR = null;
let needleL = 0, needleR = 0;

function initAudioAnalyser() {
  if (audioCtx) {
    if (audioCtx.state === 'suspended') audioCtx.resume();
    return;
  }
  const Ctx = window.AudioContext || window.webkitAudioContext;
  if (!Ctx) return;
  audioCtx = new Ctx();
  const src = audioCtx.createMediaElementSource(audio);
  const splitter = audioCtx.createChannelSplitter(2);
  analyserL = audioCtx.createAnalyser();
  analyserR = audioCtx.createAnalyser();
  analyserL.fftSize = 512;
  analyserR.fftSize = 512;
  dataL = new Uint8Array(analyserL.fftSize);
  dataR = new Uint8Array(analyserR.fftSize);

  src.connect(splitter);
  splitter.connect(analyserL, 0);
  splitter.connect(analyserR, 1);
  src.connect(audioCtx.destination);
}

audio.addEventListener('play', initAudioAnalyser);

function getChannelLevel(analyser, buf) {
  if (!analyser || audio.paused) return 0;
  analyser.getByteTimeDomainData(buf);
  let sum = 0;
  for (let i = 0; i < buf.length; i++) {
    const v = (buf[i] - 128) / 128;
    sum += v * v;
  }
  const rms = Math.sqrt(sum / buf.length);
  if (rms < 0.001) return 0;
  const db = 20 * Math.log10(rms);
  return Math.max(0, Math.min(1, (db + 42) / 42));
}

function drawVuMeter(canvas, label, level) {
  const dpr = window.devicePixelRatio || 1;
  const w = canvas.clientWidth || 270;
  const h = canvas.clientHeight || 145;
  if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(h * dpr)) {
    canvas.width = Math.round(w * dpr);
    canvas.height = Math.round(h * dpr);
  }
  const ctx = canvas.getContext('2d');
  ctx.save();
  ctx.scale(dpr, dpr);

  const grad = ctx.createRadialGradient(w * 0.5, h * 0.82, w * 0.06, w * 0.5, h * 0.65, w * 0.72);
  grad.addColorStop(0.0, '#ffd426');
  grad.addColorStop(0.55, '#f59211');
  grad.addColorStop(1.0, '#d94508');
  ctx.fillStyle = grad;
  ctx.fillRect(0, 0, w, h);

  ctx.strokeStyle = 'rgba(0,0,0,0.35)';
  ctx.lineWidth = 4;
  ctx.strokeRect(0, 0, w, h);

  const cx = w * 0.5;
  const cy = h * 1.48;
  const rOuter = h * 1.02;
  const rInner = h * 0.84;
  const startA = -Math.PI * 0.74;
  const endA   = -Math.PI * 0.26;
  const zeroA  = startA + (endA - startA) * 0.78;

  ctx.lineWidth = 1.6;
  ctx.strokeStyle = '#181410';
  ctx.beginPath(); ctx.arc(cx, cy, rOuter, startA, zeroA); ctx.stroke();
  ctx.beginPath(); ctx.arc(cx, cy, rInner, startA, zeroA); ctx.stroke();

  ctx.strokeStyle = '#c81c0c';
  ctx.beginPath(); ctx.arc(cx, cy, rOuter, zeroA, endA); ctx.stroke();
  ctx.beginPath(); ctx.arc(cx, cy, rInner, zeroA, endA); ctx.stroke();

  for (let i = 0; i <= 26; i++) {
    const t = i / 26;
    const a = startA + t * (endA - startA);
    const isRed = a >= zeroA - 0.005;
    ctx.strokeStyle = isRed ? '#c81c0c' : '#181410';
    ctx.lineWidth = (i % 5 === 0) ? 1.4 : 0.9;
    const tickLen = (i % 5 === 0) ? 6 : 3.5;

    ctx.beginPath();
    ctx.moveTo(cx + Math.cos(a) * rOuter, cy + Math.sin(a) * rOuter);
    ctx.lineTo(cx + Math.cos(a) * (rOuter + tickLen), cy + Math.sin(a) * (rOuter + tickLen));
    ctx.stroke();

    ctx.beginPath();
    ctx.moveTo(cx + Math.cos(a) * rInner, cy + Math.sin(a) * rInner);
    ctx.lineTo(cx + Math.cos(a) * (rInner + tickLen), cy + Math.sin(a) * (rInner + tickLen));
    ctx.stroke();
  }

  const wattMarks = [
    { t: 0.04, txt: '.01' },
    { t: 0.24, txt: '.1' },
    { t: 0.44, txt: '1' },
    { t: 0.58, txt: '10' },
    { t: 0.74, txt: '100' },
    { t: 0.85, txt: '170W' }
  ];
  ctx.font = `bold ${Math.max(8, Math.round(h * 0.075))}px sans-serif`;
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  for (const m of wattMarks) {
    const a = startA + m.t * (endA - startA);
    ctx.fillStyle = '#181410';
    ctx.save();
    ctx.translate(cx + Math.cos(a) * (rOuter + 14), cy + Math.sin(a) * (rOuter + 14));
    ctx.rotate(a + Math.PI / 2);
    ctx.fillText(m.txt, 0, 0);
    ctx.restore();
  }

  const dbMarks = [
    { t: 0.12, txt: '-40', red: false },
    { t: 0.34, txt: '-30', red: false },
    { t: 0.50, txt: '-20', red: false },
    { t: 0.63, txt: '-10', red: false },
    { t: 0.78, txt: '0',   red: false },
    { t: 0.92, txt: '+5',  red: true }
  ];
  for (const m of dbMarks) {
    const a = startA + m.t * (endA - startA);
    ctx.fillStyle = m.red ? '#c81c0c' : '#181410';
    ctx.save();
    ctx.translate(cx + Math.cos(a) * (rInner + 13), cy + Math.sin(a) * (rInner + 13));
    ctx.rotate(a + Math.PI / 2);
    ctx.fillText(m.txt, 0, 0);
    ctx.restore();
  }

  ctx.fillStyle = '#261a0e';
  ctx.font = `600 ${Math.max(9, Math.round(h * 0.08))}px sans-serif`;
  ctx.fillText(label, cx, h * 0.87);

  const angle = startA + Math.max(0, Math.min(1, level)) * (endA - startA);
  const tipR = rOuter + 10;

  ctx.save();
  ctx.shadowColor = 'rgba(0, 0, 0, 0.45)';
  ctx.shadowBlur = 3;
  ctx.shadowOffsetX = 2;
  ctx.shadowOffsetY = 1;
  ctx.strokeStyle = '#111111';
  ctx.lineWidth = 2.2;
  ctx.lineCap = 'round';
  ctx.beginPath();
  ctx.moveTo(cx, cy);
  ctx.lineTo(cx + Math.cos(angle) * tipR, cy + Math.sin(angle) * tipR);
  ctx.stroke();
  ctx.restore();

  ctx.restore();
}

function animateVu() {
  if (vuVisible) {
    const targetL = getChannelLevel(analyserL, dataL);
    const targetR = getChannelLevel(analyserR, dataR);
    needleL += (targetL - needleL) * (targetL > needleL ? 0.35 : 0.12);
    needleR += (targetR - needleR) * (targetR > needleR ? 0.35 : 0.12);

    drawVuMeter(vuLeftC, 'LEFT', needleL);
    drawVuMeter(vuRightC, 'RIGHT', needleR);
    requestAnimationFrame(animateVu);
  }
}

btnVu.onclick = () => {
  vuVisible = !vuVisible;
  vuDock.classList.toggle('visible', vuVisible);
  btnVu.classList.toggle('active', vuVisible);
  if (vuVisible) {
    if (!audio.paused) initAudioAnalyser();
    requestAnimationFrame(animateVu);
  }
};

// --- Init ---
// --- On-Screen Keyboard ---
const searchInput = document.getElementById('searchInput');
const oskPanel = document.getElementById('oskPanel');

const oskRows = [
  ['1','2','3','4','5','6','7','8','9','0'],
  ['Q','W','E','R','T','Y','U','I','O','P'],
  ['A','S','D','F','G','H','J','K','L'],
  ['Z','X','C','V','B','N','M','⌫'],
  ['Clear','Space','Done']
];

oskPanel.innerHTML = oskRows.map(row => `
  <div class="osk-row">
    ${row.map(key => {
      let cls = 'osk-key';
      if (key === 'Space') cls += ' space';
      else if (key === '⌫' || key === 'Clear') cls += ' wide';
      else if (key === 'Done') cls += ' wide accent';
      return `<button type="button" class="${cls}" data-key="${key}">${key}</button>`;
    }).join('')}
  </div>
`).join('');

// Keep focus in the search box when tapping keys
oskPanel.addEventListener('mousedown', e => e.preventDefault());

oskPanel.addEventListener('click', e => {
  const btn = e.target.closest('.osk-key');
  if (!btn) return;
  const key = btn.dataset.key;

  if (key === 'Done') {
    oskPanel.classList.remove('visible');
    searchInput.blur();
    return;
  }
  if (key === 'Clear') {
    searchInput.value = '';
  } else if (key === '⌫') {
    searchInput.value = searchInput.value.slice(0, -1);
  } else if (key === 'Space') {
    searchInput.value += ' ';
  } else {
    searchInput.value += key.toLowerCase();
  }

  state.query = searchInput.value;
  renderLibrary();
});

searchInput.addEventListener('focus', () => oskPanel.classList.add('visible'));
searchInput.addEventListener('click', () => oskPanel.classList.add('visible'));

document.addEventListener('click', e => {
  if (!oskPanel.contains(e.target) && e.target !== searchInput) {
    oskPanel.classList.remove('visible');
  }
});
restoreSession();
renderQueue();
loadLibrary();
</script>
</body>
</html>

Save this as api.php; note the $MUSIC_DIR variable at the top.

<?php
// === CONFIGURATION ===
$MUSIC_DIR      = '/volume3/Files/Music'; // Absolute path to your NAS music folder
$CACHE_FILE     = __DIR__ . '/library_cache.json';
$CONFIG_FILE    = __DIR__ . '/scan_config.json';
$AUDIO_EXTS     = ['mp3', 'flac'];
$ALWAYS_EXCLUDE = ['#recycle', '@eaDir', '.Trash', '.Trashes', 'System Volume Information'];
// =====================

ini_set('max_execution_time', '0');
ini_set('memory_limit', '512M');

$action = $_GET['action'] ?? '';
$realMusicDir = realpath($MUSIC_DIR);

if (!$realMusicDir || !is_dir($realMusicDir)) {
    http_response_code(500);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['error' => 'MUSIC_DIR does not exist or is not readable by Apache.']);
    exit;
}

switch ($action) {
    case 'library':
        handleLibrary($CACHE_FILE);
        break;
    case 'folders':
        handleFolders($realMusicDir, $CONFIG_FILE, $ALWAYS_EXCLUDE);
        break;
    case 'save_config':
        handleSaveConfig($CONFIG_FILE);
        break;
    case 'scan':
        handleScan($realMusicDir, $CACHE_FILE, $CONFIG_FILE, $AUDIO_EXTS, $ALWAYS_EXCLUDE);
        break;
    case 'stream':
        handleStream($realMusicDir, $_GET['file'] ?? '');
        break;
    case 'art':
        handleArt($realMusicDir, $_GET['file'] ?? '');
        break;
    default:
        http_response_code(400);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['error' => 'Invalid action']);
        break;
}

function loadConfig(string $configFile): array {
    if (is_file($configFile)) {
        $data = json_decode((string)@file_get_contents($configFile), true);
        if (is_array($data)) {
            return [
                'mode'    => ($data['mode'] ?? 'exclude') === 'include' ? 'include' : 'exclude',
                'folders' => is_array($data['folders'] ?? null) ? array_values($data['folders']) : [],
            ];
        }
    }
    return ['mode' => 'exclude', 'folders' => []];
}

function handleLibrary(string $cacheFile): void {
    header('Content-Type: application/json; charset=utf-8');
    if (!is_file($cacheFile) || filesize($cacheFile) === 0) {
        echo json_encode(['needs_scan' => true]);
        exit;
    }
    readfile($cacheFile);
}

function handleFolders(string $musicDir, string $configFile, array $alwaysExclude): void {
    header('Content-Type: application/json; charset=utf-8');
    try {
        $folders = [];
        foreach (new DirectoryIterator($musicDir) as $item) {
            if ($item->isDot() || !$item->isDir()) continue;
            $name = $item->getFilename();
            if (in_array($name, $alwaysExclude, true)) continue;
            $folders[] = $name;
        }
        natcasesort($folders);
        echo json_encode([
            'folders' => array_values($folders),
            'config'  => loadConfig($configFile),
        ], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
    } catch (Throwable $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Could not read folders: ' . $e->getMessage()]);
    }
}

function handleSaveConfig(string $configFile): void {
    header('Content-Type: application/json; charset=utf-8');
    $input = json_decode((string)file_get_contents('php://input'), true);
    if (!is_array($input)) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid JSON payload']);
        exit;
    }
    $config = [
        'mode'    => ($input['mode'] ?? 'exclude') === 'include' ? 'include' : 'exclude',
        'folders' => is_array($input['folders'] ?? null) ? array_values($input['folders']) : [],
    ];
    $ok = @file_put_contents($configFile, json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    if ($ok === false) {
        http_response_code(500);
        echo json_encode(['error' => 'Could not write scan_config.json (check folder permissions).']);
        exit;
    }
    echo json_encode(['ok' => true, 'config' => $config]);
}

function handleScan(string $musicDir, string $cacheFile, string $configFile, array $exts, array $alwaysExclude): void {
    @ini_set('zlib.output_compression', '0');
    @ini_set('implicit_flush', '1');
    while (ob_get_level() > 0) {
        ob_end_clean();
    }

    header('Content-Type: text/event-stream; charset=utf-8');
    header('Cache-Control: no-cache');
    header('Connection: keep-alive');
    header('X-Accel-Buffering: no');

    $send = function (array $payload): void {
        echo 'data: ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE) . "\n\n";
        @flush();
    };

    $config   = loadConfig($configFile);
    $mode     = $config['mode'];
    $selected = $config['folders'];

    $send(['status' => 'counting', 'message' => 'Counting audio files in selected folders...']);

    $dirIt = new RecursiveDirectoryIterator($musicDir, FilesystemIterator::SKIP_DOTS);
    $filterIt = new RecursiveCallbackFilterIterator(
        $dirIt,
        function (SplFileInfo $current) use ($musicDir, $mode, $selected, $alwaysExclude): bool {
            $name = $current->getFilename();
            if ($current->isDir()) {
                if (in_array($name, $alwaysExclude, true)) return false;
                if (dirname($current->getPathname()) === $musicDir) {
                    if ($mode === 'include' && !empty($selected)) {
                        return in_array($name, $selected, true);
                    }
                    if ($mode === 'exclude' && !empty($selected)) {
                        return !in_array($name, $selected, true);
                    }
                }
            }
            return true;
        }
    );

    $it = new RecursiveIteratorIterator(
        $filterIt,
        RecursiveIteratorIterator::SELF_FIRST,
        RecursiveIteratorIterator::CATCH_GET_CHILD
    );

    $files = [];
    foreach ($it as $fileInfo) {
        if (!$fileInfo->isFile()) continue;
        $ext = strtolower($fileInfo->getExtension());
        if (in_array($ext, $exts, true)) {
            $files[] = [$fileInfo->getRealPath(), $ext, $fileInfo->getFilename()];
        }
    }

    $total = count($files);
    $tracks = [];
    $folderArtCache = [];
    $lastEmit = 0.0;

    foreach ($files as $idx => $entry) {
        [$fullPath, $ext, $filename] = $entry;
        $relPath = ltrim(str_replace('\\', '/', substr($fullPath, strlen($musicDir))), '/');
        $dirPath = dirname($fullPath);

        if (!array_key_exists($dirPath, $folderArtCache)) {
            $folderArtCache[$dirPath] = findFolderArt($dirPath, $musicDir);
        }

        $meta = ($ext === 'flac') ? readFlacMeta($fullPath) : readMp3Meta($fullPath);

        // Prefer embedded art if present; otherwise fall back to cover.jpg / folder.jpg
        $artPath = !empty($meta['has_art']) ? $relPath : $folderArtCache[$dirPath];

        $tracks[] = [
            'file'   => $relPath,
            'format' => strtoupper($ext),
            'title'  => $meta['title'] ?: pathinfo($filename, PATHINFO_FILENAME),
            'artist' => $meta['artist'] ?: 'Unknown Artist',
            'album'  => $meta['album'] ?: basename($dirPath),
            'track'  => (int)preg_replace('/[^0-9].*$/', '', (string)($meta['track'] ?? '0')),
            'year'   => $meta['year'] ?? '',
            'art'    => $artPath,
        ];

        $now = microtime(true);
        if ($now - $lastEmit >= 0.15 || $idx + 1 === $total) {
            $lastEmit = $now;
            $send([
                'status'  => 'scanning',
                'current' => $idx + 1,
                'total'   => $total,
                'file'    => $relPath,
            ]);
        }
    }

    usort($tracks, function (array $a, array $b): int {
        return strcasecmp($a['album'], $b['album'])
            ?: ($a['track'] <=> $b['track'])
            ?: strcasecmp($a['title'], $b['title']);
    });

    $json = json_encode(
        ['tracks' => $tracks, 'scanned_at' => date('c')],
        JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE
    );

    if ($json === false || @file_put_contents($cacheFile, $json) === false) {
        $send(['status' => 'error', 'message' => 'Failed to write library_cache.json (check folder permissions or memory_limit).']);
        exit;
    }

    $send(['status' => 'done', 'total' => $total]);
    exit;
}

// --- Case-insensitive Folder Art Lookup ---
function findFolderArt(string $dirPath, string $musicDir): ?string {
    $candidates = ['cover.jpg', 'cover.jpeg', 'folder.jpg', 'folder.jpeg', 'front.jpg', 'album.jpg', 'cover.png', 'folder.png'];
    $entries = @scandir($dirPath);
    if (!$entries) return null;

    $map = [];
    foreach ($entries as $entry) {
        if ($entry === '.' || $entry === '..') continue;
        $map[strtolower($entry)] = $entry;
    }

    foreach ($candidates as $cand) {
        if (isset($map[$cand])) {
            $real = realpath($dirPath . DIRECTORY_SEPARATOR . $map[$cand]);
            if ($real && is_file($real)) {
                return ltrim(str_replace('\\', '/', substr($real, strlen($musicDir))), '/');
            }
        }
    }
    return null;
}

// --- FLAC Metadata + Embedded Art Detection ---
function readFlacMeta(string $path): array {
    $meta = ['title' => '', 'artist' => '', 'album' => '', 'track' => '', 'year' => '', 'has_art' => false];
    $fp = @fopen($path, 'rb');
    if (!$fp) return $meta;

    if (fread($fp, 4) !== 'fLaC') {
        fclose($fp);
        return $meta;
    }

    $gotComments = false;
    while (!feof($fp)) {
        $hdr = fread($fp, 4);
        if (strlen($hdr) < 4) break;

        $b0     = ord($hdr[0]);
        $isLast = ($b0 & 0x80) !== 0;
        $type   = $b0 & 0x7F;
        $length = (ord($hdr[1]) << 16) | (ord($hdr[2]) << 8) | ord($hdr[3]);

        if ($type === 4 && $length > 0 && $length < 2097152) {
            $data = fread($fp, $length);
            if (strlen($data) >= 8) {
                $vendorLen = unpack('V', substr($data, 0, 4))[1];
                $pos = 4 + $vendorLen;
                if ($pos + 4 <= strlen($data)) {
                    $count = unpack('V', substr($data, $pos, 4))[1];
                    $pos += 4;
                    for ($i = 0; $i < $count && $pos + 4 <= strlen($data); $i++) {
                        $len = unpack('V', substr($data, $pos, 4))[1];
                        $pos += 4;
                        $comment = substr($data, $pos, $len);
                        $pos += $len;
                        $eq = strpos($comment, '=');
                        if ($eq !== false) {
                            $k = strtoupper(substr($comment, 0, $eq));
                            $v = trim(substr($comment, $eq + 1));
                            if ($k === 'TITLE') $meta['title'] = $v;
                            elseif ($k === 'ARTIST' && !$meta['artist']) $meta['artist'] = $v;
                            elseif ($k === 'ALBUM') $meta['album'] = $v;
                            elseif ($k === 'TRACKNUMBER') $meta['track'] = $v;
                            elseif ($k === 'DATE' || $k === 'YEAR') $meta['year'] = substr($v, 0, 4);
                        }
                    }
                }
            }
            $gotComments = true;
        } elseif ($type === 6 && $length > 0) {
            $meta['has_art'] = true;
            fseek($fp, $length, SEEK_CUR);
        } else {
            fseek($fp, $length, SEEK_CUR);
        }

        if ($isLast || ($gotComments && $meta['has_art'])) break;
    }

    fclose($fp);
    return $meta;
}

// --- MP3 Metadata + Embedded Art Detection ---
function readMp3Meta(string $path): array {
    $meta = ['title' => '', 'artist' => '', 'album' => '', 'track' => '', 'year' => '', 'has_art' => false];
    $fp = @fopen($path, 'rb');
    if (!$fp) return $meta;

    $header = fread($fp, 10);
    if (strlen($header) === 10 && substr($header, 0, 3) === 'ID3') {
        $version = ord($header[3]);
        $tagSize = ((ord($header[6]) & 0x7F) << 21)
                 | ((ord($header[7]) & 0x7F) << 14)
                 | ((ord($header[8]) & 0x7F) << 7)
                 | (ord($header[9]) & 0x7F);

        $endPos = 10 + $tagSize;
        $wanted = [
            'TIT2' => 'title',
            'TPE1' => 'artist',
            'TALB' => 'album',
            'TRCK' => 'track',
            'TYER' => 'year',
            'TDRC' => 'year',
        ];

        if ($version === 3 || $version === 4) {
            while (ftell($fp) + 10 <= $endPos && !feof($fp)) {
                $fh = fread($fp, 10);
                if (strlen($fh) < 10 || $fh[0] === "\x00") break;

                $frameId = substr($fh, 0, 4);
                if ($version === 4) {
                    $frameSize = ((ord($fh[4]) & 0x7F) << 21)
                               | ((ord($fh[5]) & 0x7F) << 14)
                               | ((ord($fh[6]) & 0x7F) << 7)
                               | (ord($fh[7]) & 0x7F);
                } else {
                    $frameSize = unpack('N', substr($fh, 4, 4))[1];
                }

                if ($frameSize <= 0 || $frameSize > $tagSize) break;

                if ($frameId === 'APIC') {
                    $meta['has_art'] = true;
                    fseek($fp, $frameSize, SEEK_CUR);
                } elseif (isset($wanted[$frameId])) {
                    $raw = fread($fp, $frameSize);
                    $val = decodeId3Text($raw);
                    $key = $wanted[$frameId];
                    if ($val !== '' && $meta[$key] === '') {
                        $meta[$key] = ($key === 'year') ? substr($val, 0, 4) : $val;
                    }
                } else {
                    fseek($fp, $frameSize, SEEK_CUR);
                }
            }
        }
    }

    if (!$meta['title'] || !$meta['artist']) {
        fseek($fp, -128, SEEK_END);
        $v1 = fread($fp, 128);
        if (strlen($v1) === 128 && substr($v1, 0, 3) === 'TAG') {
            if (!$meta['title'])  $meta['title']  = trim(rtrim(substr($v1, 3, 30), "\0"));
            if (!$meta['artist']) $meta['artist'] = trim(rtrim(substr($v1, 33, 30), "\0"));
            if (!$meta['album'])  $meta['album']  = trim(rtrim(substr($v1, 63, 30), "\0"));
            if (!$meta['year'])   $meta['year']   = trim(rtrim(substr($v1, 93, 4), "\0"));
        }
    }

    fclose($fp);
    return $meta;
}

// --- Extract Embedded Art from FLAC ---
function extractFlacArt(string $path): ?array {
    $fp = @fopen($path, 'rb');
    if (!$fp) return null;

    if (fread($fp, 4) !== 'fLaC') {
        fclose($fp);
        return null;
    }

    while (!feof($fp)) {
        $hdr = fread($fp, 4);
        if (strlen($hdr) < 4) break;

        $b0     = ord($hdr[0]);
        $isLast = ($b0 & 0x80) !== 0;
        $type   = $b0 & 0x7F;
        $length = (ord($hdr[1]) << 16) | (ord($hdr[2]) << 8) | ord($hdr[3]);

        if ($type === 6 && $length > 32 && $length < 15728640) {
            $data = fread($fp, $length);
            fclose($fp);

            $pos = 4; // skip picture type
            if ($pos + 4 > strlen($data)) return null;
            $mimeLen = unpack('N', substr($data, $pos, 4))[1];
            $pos += 4;

            $mime = strtolower(trim(substr($data, $pos, $mimeLen)));
            $pos += $mimeLen;

            if ($pos + 4 > strlen($data)) return null;
            $descLen = unpack('N', substr($data, $pos, 4))[1];
            $pos += 4 + $descLen + 16; // skip description + width/height/depth/colors

            if ($pos + 4 > strlen($data)) return null;
            $imgLen = unpack('N', substr($data, $pos, 4))[1];
            $pos += 4;

            $imgData = substr($data, $pos, $imgLen);
            if ($imgData === '') return null;
            if (!$mime || $mime === 'image/jpg') $mime = 'image/jpeg';

            return ['mime' => $mime, 'data' => $imgData];
        } else {
            fseek($fp, $length, SEEK_CUR);
        }

        if ($isLast) break;
    }

    fclose($fp);
    return null;
}

// --- Extract Embedded Art from MP3 (ID3v2 APIC) ---
function extractMp3Art(string $path): ?array {
    $fp = @fopen($path, 'rb');
    if (!$fp) return null;

    $header = fread($fp, 10);
    if (strlen($header) !== 10 || substr($header, 0, 3) !== 'ID3') {
        fclose($fp);
        return null;
    }

    $version = ord($header[3]);
    $tagSize = ((ord($header[6]) & 0x7F) << 21)
             | ((ord($header[7]) & 0x7F) << 14)
             | ((ord($header[8]) & 0x7F) << 7)
             | (ord($header[9]) & 0x7F);
    $endPos = 10 + $tagSize;

    if ($version === 3 || $version === 4) {
        while (ftell($fp) + 10 <= $endPos && !feof($fp)) {
            $fh = fread($fp, 10);
            if (strlen($fh) < 10 || $fh[0] === "\x00") break;

            $frameId = substr($fh, 0, 4);
            if ($version === 4) {
                $frameSize = ((ord($fh[4]) & 0x7F) << 21)
                           | ((ord($fh[5]) & 0x7F) << 14)
                           | ((ord($fh[6]) & 0x7F) << 7)
                           | (ord($fh[7]) & 0x7F);
            } else {
                $frameSize = unpack('N', substr($fh, 4, 4))[1];
            }

            if ($frameSize <= 0 || $frameSize > $tagSize) break;

            if ($frameId === 'APIC') {
                $raw = fread($fp, $frameSize);
                fclose($fp);

                if (strlen($raw) < 4) return null;
                $enc = ord($raw[0]);
                $mimeEnd = strpos($raw, "\x00", 1);
                if ($mimeEnd === false) return null;

                $mime = strtolower(trim(substr($raw, 1, $mimeEnd - 1)));
                $pos = $mimeEnd + 2; // skip null terminator + picture type byte

                // Skip null-terminated description
                if ($enc === 1 || $enc === 2) {
                    $len = strlen($raw);
                    while ($pos + 1 < $len) {
                        if ($raw[$pos] === "\x00" && $raw[$pos + 1] === "\x00") {
                            $pos += 2;
                            break;
                        }
                        $pos += 2;
                    }
                } else {
                    $descEnd = strpos($raw, "\x00", $pos);
                    if ($descEnd === false) return null;
                    $pos = $descEnd + 1;
                }

                $imgData = substr($raw, $pos);
                if ($imgData === '') return null;
                if (!$mime || $mime === 'jpg' || $mime === 'image/jpg') $mime = 'image/jpeg';
                if ($mime === 'png') $mime = 'image/png';

                return ['mime' => $mime, 'data' => $imgData];
            } else {
                fseek($fp, $frameSize, SEEK_CUR);
            }
        }
    }

    fclose($fp);
    return null;
}

function decodeId3Text(string $raw): string {
    if ($raw === '') return '';
    $enc = ord($raw[0]);
    $str = substr($raw, 1);

    if (function_exists('mb_convert_encoding')) {
        if ($enc === 0) {
            $str = mb_convert_encoding($str, 'UTF-8', 'ISO-8859-1');
        } elseif ($enc === 1) {
            $str = mb_convert_encoding($str, 'UTF-8', 'UTF-16');
        } elseif ($enc === 2) {
            $str = mb_convert_encoding($str, 'UTF-8', 'UTF-16BE');
        }
    }
    return trim(str_replace("\0", '', $str));
}

function resolveSafePath(string $musicDir, string $relPath): ?string {
    $full = realpath($musicDir . DIRECTORY_SEPARATOR . $relPath);
    if (!$full || !is_file($full)) return null;
    if (strpos($full, $musicDir . DIRECTORY_SEPARATOR) !== 0) return null;
    return $full;
}

function handleStream(string $musicDir, string $relPath): void {
    $full = resolveSafePath($musicDir, $relPath);
    if (!$full) { http_response_code(404); exit; }

    $ext   = strtolower(pathinfo($full, PATHINFO_EXTENSION));
    $mime  = ($ext === 'flac') ? 'audio/flac' : 'audio/mpeg';
    $size  = filesize($full);
    $start = 0;
    $end   = $size - 1;

    if (ob_get_level()) ob_end_clean();
    header("Content-Type: $mime");
    header('Accept-Ranges: bytes');

    if (isset($_SERVER['HTTP_RANGE']) && preg_match('/bytes=(\d+)-(\d*)/', $_SERVER['HTTP_RANGE'], $m)) {
        $start = (int)$m[1];
        if ($m[2] !== '') $end = min((int)$m[2], $size - 1);
        if ($start > $end || $start >= $size) {
            http_response_code(416);
            header("Content-Range: bytes */$size");
            exit;
        }
        http_response_code(206);
        header("Content-Range: bytes $start-$end/$size");
    }

    $length = $end - $start + 1;
    header("Content-Length: $length");

    $fp = fopen($full, 'rb');
    fseek($fp, $start);
    $buffer = 65536;
    while (!feof($fp) && $length > 0) {
        $read = min($buffer, $length);
        echo fread($fp, $read);
        flush();
        $length -= $read;
    }
    fclose($fp);
}

function handleArt(string $musicDir, string $relPath): void {
    $full = resolveSafePath($musicDir, $relPath);
    if (!$full) { http_response_code(404); exit; }

    $ext = strtolower(pathinfo($full, PATHINFO_EXTENSION));

    if ($ext === 'mp3' || $ext === 'flac') {
        $art = ($ext === 'flac') ? extractFlacArt($full) : extractMp3Art($full);
        if (!$art) { http_response_code(404); exit; }
        header('Content-Type: ' . $art['mime']);
        header('Cache-Control: public, max-age=86400');
        echo $art['data'];
        exit;
    }

    header('Content-Type: ' . ($ext === 'png' ? 'image/png' : 'image/jpeg'));
    header('Cache-Control: public, max-age=86400');
    readfile($full);
}