/* ============================================================
   Player components — bar, full-screen, queue panel, quality menu
   ============================================================ */

const { useEffect: useEffectP, useState: useStateP, useRef: useRefP, useMemo: useMemoP, useSyncExternalStore: useSESP } = React;

// Subscribe to MetaStore for live quality info
function useTrackQuality(track) {
  return useSESP(
    (fn) => window.MetaStore.subscribe(fn),
    () => window.MetaStore.getQuality(track),
    () => ({ tier: "hifi", label: "HiFi", detail: "" })
  );
}

// helper
function fmtTime(s) {
  if (!s || s < 0) s = 0;
  const m = Math.floor(s / 60);
  const sec = Math.floor(s % 60);
  return `${m}:${sec.toString().padStart(2, "0")}`;
}

// =============================================================
// Now-playing bar (persistent bottom)
// =============================================================
function PlayerBar({ ctx }) {
  const t = ctx.current;
  const album = ctx.albumOf(t);
  const Ic = window.Icons;
  const quality = useTrackQuality(t);
  const [volOpen, setVolOpen] = useStateP(false);
  const volRef = useRefP(null);

  useEffectP(() => {
    if (!volOpen) return;
    function onDoc(e) {
      if (volRef.current && !volRef.current.contains(e.target)) setVolOpen(false);
    }
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [volOpen]);

  function seek(e) {
    if (!t) return;
    const rect = e.currentTarget.getBoundingClientRect();
    const ratio = (e.clientX - rect.left) / rect.width;
    ctx.seek(t.d * Math.max(0, Math.min(1, ratio)));
  }

  return (
    <div className="player" data-screen-label="Player Bar">
      <div className="player-left">
        {t ?
        <>
            <div className="player-cover" onClick={ctx.toggleFullscreen}>
              <Cover album={album} text={false} />
            </div>
            <div className="player-track">
              <div className="player-track-name">{t.title}</div>
              <div className="player-track-artist">{t.artist}</div>
              {album &&
            <div className="player-track-album">
                  <Ic.Disc size={11} />
                  <span>{album.title}</span>
                </div>
            }
            </div>
            <button
            className={"btn-icon " + (ctx.isLiked(t.id) ? "active" : "")}
            onClick={() => ctx.toggleLike(t.id)}
            title="Add to favorites">
            
              <Ic.Heart size={18} fill={ctx.isLiked(t.id) ? "currentColor" : "none"} />
            </button>
          </> :

        <div style={{ color: "var(--ink-4)", fontSize: 13, padding: "0 8px" }}>
            Nothing playing — choose a track
          </div>
        }
      </div>

      <div className="player-center">
        <div className="player-controls">
          <button
            className={ctx.shuffle ? "active" : ""}
            onClick={() => ctx.setShuffle(!ctx.shuffle)}
            title="Shuffle">
            
            <Ic.Shuffle size={16} />
          </button>
          <button onClick={ctx.prev} title="Previous">
            <Ic.Prev size={18} />
          </button>
          <button className="play-big" onClick={ctx.togglePlay} title={ctx.playing ? "Pause" : "Play"}>
            {ctx.playing ? <Ic.Pause size={16} /> : <Ic.Play size={16} />}
          </button>
          <button onClick={ctx.next} title="Next">
            <Ic.Next size={18} />
          </button>
          <button
            className={ctx.repeat !== "off" ? "active" : ""}
            onClick={ctx.cycleRepeat}
            title={`Repeat: ${ctx.repeat}`}>
            
            <Ic.Repeat size={16} />
          </button>
        </div>
        <div className="player-progress">
          <span>{fmtTime(ctx.position)}</span>
          <div className="progress-bar" onClick={seek}>
            <div className="progress-fill" style={{ width: t ? `${ctx.position / t.d * 100}%` : "0%" }} />
          </div>
          <span>{fmtTime(t?.d || 0)}</span>
        </div>
      </div>

      <div className="player-right">
        {t && (
          <button
            className="btn-icon"
            onClick={() => ctx.openShare({ kind: "track", id: t.id, label: `${t.title} — ${t.artist}` })}
            title="Share track">
            <Ic.Share size={16} />
          </button>
        )}
        <button
          className={"btn-icon " + (ctx.queueOpen ? "active" : "")}
          onClick={() => ctx.setQueueOpen(!ctx.queueOpen)}
          title="Queue">

          <Ic.Queue size={18} />
        </button>
        <div className="volume-control" ref={volRef}>
          <button
            className={"btn-icon " + (volOpen ? "active" : "")}
            onClick={() => setVolOpen((v) => !v)}
            title="Volume">
            
            {ctx.volume === 0 ? <Ic.VolumeOff size={18} /> : <Ic.Volume size={18} />}
          </button>
          {volOpen &&
          <div className="volume-popover" data-comment-anchor="f19d7b7261-div-136-13">
              <div className="vol-slider-wrap">
                <input
                  type="range" min="0" max="100" value={ctx.volume}
                  onChange={(e) => ctx.setVolume(+e.target.value)}
                  autoFocus data-comment-anchor="cf005e308d-input-137-15" />
              </div>
              <div className="vol-num">{ctx.volume}</div>
            </div>
          }
        </div>
        <button
          className={"quality-pill " + (quality.tier === "master" ? "master" : "")}
          onClick={() => ctx.setQualityMenu(true)}
          title={"Now playing: " + (quality.detail || quality.label)}>
          
          {quality.label}
        </button>
      </div>
    </div>);

}

// =============================================================
// Full-screen now-playing
// =============================================================
function FullPlayer({ ctx, isMobile }) {
  if (!ctx.fullscreen) return null;
  if (isMobile) return <MobileFullPlayer ctx={ctx} />;
  return <DesktopFullPlayer ctx={ctx} />;
}

function DesktopFullPlayer({ ctx }) {
  const t = ctx.current;
  const album = ctx.albumOf(t);
  const Ic = window.Icons;
  const [showLyrics, setShowLyrics] = useStateP(true);
  const quality = useTrackQuality(t);
  const [volOpen, setVolOpen] = useStateP(false);
  const volRef = useRefP(null);
  useEffectP(() => {
    if (!volOpen) return;
    function onDoc(e) {
      if (volRef.current && !volRef.current.contains(e.target)) setVolOpen(false);
    }
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [volOpen]);
  const hasLyrics = useMemoP(() => {
    if (!t) return false;
    return !!(window.MetaStore.getTrackLyrics(t) || window.MUSIC_DB.lyrics[t.id]);
  }, [t?.id, ctx.extractedMeta]);

  if (!t) return null;

  function seek(e) {
    const rect = e.currentTarget.getBoundingClientRect();
    const ratio = (e.clientX - rect.left) / rect.width;
    ctx.seek(t.d * Math.max(0, Math.min(1, ratio)));
  }

  const tint = album?.cover?.c1 || "#ff3d9a";
  const tint2 = album?.cover?.c2 || "#f5c14b";
  const artistInitial = (t.artist || "?").trim().charAt(0).toUpperCase();
  const trackIdx = (album?.tracks.findIndex((x) => x.id === t.id) ?? 0) + 1;

  return (
    <div className={"dfp " + (showLyrics && hasLyrics ? "with-lyrics" : "") + (ctx.queueOpen ? " with-queue" : "")} style={{
      "--pink-glow": tint + "60",
      "--gold-glow": tint2 + "55"
    }}>
      <div className="dfp-bg" />

      {/* Top bar */}
      <div className="dfp-topbar">
        <div className="dfp-artist-chip" title={t.artist}>
          <div className="avatar" style={{ background: `linear-gradient(135deg, ${tint}, ${tint2})` }}>
            {artistInitial}
          </div>
          <span>{t.artist}</span>
        </div>
        <div className="dfp-pills">
          <button
            className={"dfp-pill " + (showLyrics && hasLyrics ? "on" : "")}
            onClick={() => setShowLyrics((s) => !s)}
            disabled={!hasLyrics}
            title={hasLyrics ? "Toggle lyrics" : "No lyrics for this track"}>
            
            Lyrics
          </button>
          <button className="dfp-icon" onClick={ctx.toggleFullscreen} title="Close">
            <Ic.Compress size={16} />
          </button>
        </div>
      </div>

      {ctx.queueOpen && (
        <div className="dfp-queue">
          <QueuePanel ctx={ctx} />
        </div>
      )}

      {/* Main content area */}
      <div className="dfp-main">
        <div className="dfp-cover-wrap">
          <div className="dfp-cover">
            <Cover album={album} text={false} />
          </div>
        </div>
        {showLyrics && hasLyrics &&
        <div className="dfp-lyrics-wrap">
            <LyricsView
            track={t}
            position={ctx.position}
            onSeek={ctx.seek}
            lyricsOverride={ctx.trackMeta?.(t)?.lyrics || null} />
          
          </div>
        }
      </div>

      {/* Bottom strip */}
      <div className="dfp-bottom">
        <div className="dfp-track-info">
          <div className="dfp-track-title">{t.title}</div>
          <div className="dfp-track-artist">{t.artist}</div>
          <div className="dfp-track-album">
            <Ic.Disc size={11} />
            <span>{album?.title}</span>
            {album?.isSingle ? null : <span style={{ color: "var(--ink-4)" }}> · {trackIdx} / {album?.tracks.length}</span>}
          </div>
        </div>

        <div className="dfp-controls">
          <div className="dfp-control-row">
            <button
              className={"dfp-ctl " + (ctx.shuffle ? "active" : "")}
              onClick={() => ctx.setShuffle(!ctx.shuffle)}
              title="Shuffle">
              
              <Ic.Shuffle size={18} />
            </button>
            <button className="dfp-ctl" onClick={ctx.prev} title="Previous">
              <Ic.Prev size={22} />
            </button>
            <button className="dfp-ctl-play" onClick={ctx.togglePlay} title={ctx.playing ? "Pause" : "Play"}>
              {ctx.playing ? <Ic.Pause size={20} /> : <Ic.Play size={20} />}
            </button>
            <button className="dfp-ctl" onClick={ctx.next} title="Next">
              <Ic.Next size={22} />
            </button>
            <button
              className={"dfp-ctl " + (ctx.repeat !== "off" ? "active" : "")}
              onClick={ctx.cycleRepeat}
              title={`Repeat: ${ctx.repeat}`}>
              
              <Ic.Repeat size={18} />
            </button>
          </div>
          <div className="dfp-progress">
            <span className="dfp-time">{fmtTime(ctx.position)}</span>
            <div className="progress-bar" onClick={seek}>
              <div className="progress-fill" style={{ width: `${ctx.position / t.d * 100}%` }} />
            </div>
            <span className="dfp-time">{fmtTime(t.d)}</span>
          </div>
        </div>

        <div className="dfp-actions">
          <button
            className={"dfp-icon " + (ctx.isLiked(t.id) ? "active" : "")}
            onClick={() => ctx.toggleLike(t.id)}
            title="Favorite">

            <Ic.Heart size={18} fill={ctx.isLiked(t.id) ? "currentColor" : "none"} />
          </button>
          <button
            className="dfp-icon"
            onClick={() => ctx.openShare({ kind: "track", id: t.id, label: `${t.title} — ${t.artist}` })}
            title="Share track">
            <Ic.Share size={16} />
          </button>
          <button
            className={"dfp-icon " + (ctx.queueOpen ? "active" : "")}
            onClick={() => ctx.setQueueOpen(!ctx.queueOpen)}
            title="Show queue">

            <Ic.Queue size={18} />
          </button>
          <div className="dfp-volume volume-control" ref={volRef}>
            <button
              className={"dfp-icon " + (volOpen ? "active" : "")}
              onClick={() => setVolOpen((v) => !v)}
              title="Volume">
              {ctx.volume === 0 ? <Ic.VolumeOff size={16} /> : <Ic.Volume size={16} />}
            </button>
            {volOpen &&
              <div className="volume-popover">
                <div className="vol-slider-wrap">
                  <input
                    type="range" min="0" max="100" value={ctx.volume}
                    onChange={(e) => ctx.setVolume(+e.target.value)}
                    autoFocus />
                </div>
                <div className="vol-num">{ctx.volume}</div>
              </div>
            }
          </div>
          <button
            className={"dfp-quality " + (quality.tier === "master" ? "master" : "")}
            onClick={() => ctx.setQualityMenu(true)}
            title={quality.detail || "Audio quality"}>
            
            {quality.label}
          </button>
        </div>
      </div>
    </div>);

}

// =============================================================
// Queue panel
// =============================================================
function QueuePanel({ ctx }) {
  const Ic = window.Icons;
  const upNext = ctx.queue.slice(ctx.queueIdx + 1);
  const playing = ctx.current;
  const playingAlbum = ctx.albumOf(playing);

  return (
    <div className="queue" data-screen-label="Queue">
      <div className="queue-head">
        <h3>Queue</h3>
        <button className="btn-icon" onClick={() => ctx.setQueueOpen(false)} title="Close">
          <Ic.X size={18} />
        </button>
      </div>

      {playing &&
      <>
          <div className="queue-section-label">Now Playing</div>
          <div className="queue-item current">
            <div className="mini-cover">
              <Cover album={playingAlbum} text={false} />
            </div>
            <div className="info">
              <div className="t">{playing.title}</div>
              <div className="a">{playing.artist}</div>
            </div>
            <div style={{ display: "flex", gap: 2, alignItems: "flex-end", height: 16 }}>
              <span style={{ width: 2, height: "60%", background: "var(--pink)", animation: "bars 0.9s ease-in-out infinite" }} />
              <span style={{ width: 2, height: "100%", background: "var(--pink)", animation: "bars 0.9s ease-in-out infinite 0.2s" }} />
              <span style={{ width: 2, height: "40%", background: "var(--pink)", animation: "bars 0.9s ease-in-out infinite 0.4s" }} />
            </div>
          </div>
        </>
      }

      <div className="queue-section-label">
        Up Next {upNext.length > 0 && <span style={{ color: "var(--ink-3)", fontWeight: 600, letterSpacing: 0, textTransform: "none" }}>· {upNext.length}</span>}
      </div>
      {upNext.length === 0 &&
      <div style={{ color: "var(--ink-4)", fontSize: 12, padding: "8px 12px" }}>
          Nothing queued. Add a song to the queue, or start an album.
        </div>
      }
      {upNext.map((t, i) => {
        const album = ctx.albumOf(t);
        return (
          <div className="queue-item" key={i} onClick={() => ctx.jumpQueue(ctx.queueIdx + 1 + i)}>
            <div className="mini-cover">
              <Cover album={album} text={false} />
            </div>
            <div className="info">
              <div className="t">{t.title}</div>
              <div className="a">{t.artist}</div>
            </div>
            <div style={{ fontSize: 11, color: "var(--ink-4)", fontVariantNumeric: "tabular-nums" }}>
              {fmtTime(t.d)}
            </div>
          </div>);

      })}
    </div>);

}

// =============================================================
// Quality menu
// =============================================================
function QualityMenu({ ctx }) {
  if (!ctx.qualityMenu) return null;
  const Ic = window.Icons;
  const options = [
  { id: "high", name: "High", desc: "AAC · 320 kbps · everyday listening", bitrate: "320 kbps" },
  { id: "master", name: "Master", desc: "FLAC 24-bit · studio master", bitrate: "Up to 9216 kbps", master: true }];


  return (
    <div className="qmenu-backdrop" onClick={() => ctx.setQualityMenu(false)}>
      <div className="qmenu" onClick={(e) => e.stopPropagation()}>
        <h3>Audio Quality</h3>
        <p className="sub">Higher quality uses more bandwidth.</p>
        <div className="qmenu-options">
          {options.map((o) =>
          <button
            key={o.id}
            className={`qmenu-opt ${o.master ? "master" : ""} ${ctx.quality === o.id ? "active" : ""}`}
            onClick={() => {ctx.setQuality(o.id);ctx.setQualityMenu(false);}}>
            
              <div className="left">
                <div className="name">
                  {o.name}
                  {o.master &&
                <span style={{ marginLeft: 8, fontSize: 9, letterSpacing: "0.18em", color: "var(--pink)" }}>★ MAX</span>
                }
                </div>
                <div className="desc">{o.desc}</div>
              </div>
              <div className="right">
                {o.bitrate}
                {ctx.quality === o.id &&
              <div style={{ marginTop: 4, color: o.master ? "var(--pink)" : "var(--gold)" }}>
                    <Ic.Check size={16} />
                  </div>
              }
              </div>
            </button>
          )}
        </div>
      </div>
    </div>);

}

// =============================================================
// MobileFullPlayer — Apple Music–style, single column
// =============================================================
function MobileFullPlayer({ ctx }) {
  const t = ctx.current;
  const album = ctx.albumOf(t);
  const Ic = window.Icons;
  const [view, setView] = useStateP("cover"); // 'cover' | 'lyrics' | 'queue'
  const quality = useTrackQuality(t);

  if (!t) return null;

  function seek(e) {
    const rect = e.currentTarget.getBoundingClientRect();
    const ratio = (e.clientX - rect.left) / rect.width;
    ctx.seek(t.d * Math.max(0, Math.min(1, ratio)));
  }

  const tint = album?.cover?.c1 || "#ff3d9a";
  const tint2 = album?.cover?.c2 || "#f5c14b";

  return (
    <div className="mfp" style={{
      "--pink-glow": tint + "60",
      "--gold-glow": tint2 + "55"
    }}>
      {/* Drag handle row */}
      <div className="mfp-handle-row">
        <button className="mfp-handle-btn" onClick={ctx.toggleFullscreen} aria-label="Close">
          <svg width="22" height="6" viewBox="0 0 22 6" fill="none">
            <rect x="0" y="2" width="22" height="3" rx="1.5" fill="currentColor" />
          </svg>
        </button>
      </div>

      <div className="mfp-eyebrow">
        <div className="mfp-eyebrow-label">{album?.isSingle ? "Playing Single" : "Playing From Album"}</div>
        <div className="mfp-eyebrow-title">{album?.title}</div>
      </div>

      {/* Main content — swaps between cover, lyrics, queue */}
      <div className="mfp-content">
        {view === "cover" &&
        <div className={"mfp-cover " + (ctx.playing ? "playing" : "paused")}>
            <Cover album={album} text={false} />
          </div>
        }
        {view === "lyrics" &&
        <div className="mfp-lyrics">
            <LyricsView track={t} position={ctx.position} onSeek={ctx.seek} compact />
          </div>
        }
        {view === "queue" &&
        <div className="mfp-queue-content">
            <h4 className="mfp-section-h">Up Next</h4>
            {ctx.queue.slice(ctx.queueIdx + 1).map((qt, i) => {
            const qa = ctx.albumOf(qt);
            return (
              <div className="mfp-queue-item" key={i}
              onClick={() => ctx.jumpQueue(ctx.queueIdx + 1 + i)}>
                  <div className="mini-cover"><Cover album={qa} text={false} /></div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="mfp-q-t">{qt.title}</div>
                    <div className="mfp-q-a">{qt.artist}</div>
                  </div>
                  <span style={{ fontSize: 11, color: "var(--ink-4)" }}>{fmtTime(qt.d)}</span>
                </div>);

          })}
            {ctx.queue.slice(ctx.queueIdx + 1).length === 0 &&
          <div style={{ color: "var(--ink-4)", fontSize: 12, padding: "20px 4px" }}>
                Nothing queued.
              </div>
          }
          </div>
        }
      </div>

      {/* Title + heart */}
      <div className="mfp-title-row">
        <div className="mfp-title-meta">
          <div className="mfp-title">{t.title}</div>
          <div className="mfp-artist">{t.artist}</div>
        </div>
        <button
          className={"mfp-heart " + (ctx.isLiked(t.id) ? "on" : "")}
          onClick={() => ctx.toggleLike(t.id)}
          aria-label="Favorite">
          
          <Ic.Heart size={22} fill={ctx.isLiked(t.id) ? "currentColor" : "none"} />
        </button>
      </div>

      {/* Progress */}
      <div className="mfp-progress">
        <div className="progress-bar" onClick={seek}>
          <div className="progress-fill" style={{ width: `${ctx.position / t.d * 100}%` }} />
        </div>
        <div className="mfp-times">
          <span>{fmtTime(ctx.position)}</span>
          <span>−{fmtTime(Math.max(0, t.d - ctx.position))}</span>
        </div>
      </div>

      {/* Transport controls */}
      <div className="mfp-controls">
        <button className="mfp-ctl-side" onClick={ctx.prev} aria-label="Previous">
          <Ic.Prev size={28} />
        </button>
        <button className="mfp-ctl-main" onClick={ctx.togglePlay} aria-label={ctx.playing ? "Pause" : "Play"}>
          {ctx.playing ? <Ic.Pause size={32} /> : <Ic.Play size={32} />}
        </button>
        <button className="mfp-ctl-side" onClick={ctx.next} aria-label="Next">
          <Ic.Next size={28} />
        </button>
      </div>

      {/* Volume */}
      <div className="mfp-volume">
        <Ic.Volume size={14} style={{ color: "var(--ink-4)" }} />
        <input
          type="range" min="0" max="100" value={ctx.volume}
          onChange={(e) => ctx.setVolume(+e.target.value)}
          className="slider" />
        
        <Ic.Volume size={18} style={{ color: "var(--ink-4)" }} />
      </div>

      {/* Bottom action row */}
      <div className="mfp-actions">
        <button
          className={"mfp-action " + (view === "lyrics" ? "on" : "")}
          onClick={() => setView(view === "lyrics" ? "cover" : "lyrics")}>
          
          <Ic.Mic size={18} />
          <span>Lyrics</span>
        </button>
        <button
          className={"mfp-action " + (view === "queue" ? "on" : "")}
          onClick={() => setView(view === "queue" ? "cover" : "queue")}>
          
          <Ic.Queue size={18} />
          <span>Queue</span>
        </button>
        <button
          className={"mfp-action " + (quality.tier === "master" ? "master" : "")}
          onClick={() => ctx.setQualityMenu(true)}>
          
          <span className="mfp-q-pill">
            {quality.label}
          </span>
        </button>
      </div>
    </div>);

}

Object.assign(window, { PlayerBar, FullPlayer, MobileFullPlayer, QueuePanel, QualityMenu, fmtTime });