/* ============================================================
   Lyrics view — Spotify-style scrolling timed lyrics
   ============================================================ */

const { useEffect, useRef, useState: useStateL, useMemo: useMemoL, useSyncExternalStore: useSESL } = React;

function useExtractedLyrics(track) {
  return useSESL(
    (fn) => window.MetaStore.subscribe(fn),
    () => window.MetaStore.getTrackLyrics(track),
    () => null,
  );
}

function useExtractedPlainLyrics(track) {
  return useSESL(
    (fn) => window.MetaStore.subscribe(fn),
    () => (track ? (window.MetaStore.get(track.id)?.lyricsPlain || null) : null),
    () => null,
  );
}

function LyricsView({ track, position, onSeek, compact = false, lyricsOverride = null }) {
  const extracted = useExtractedLyrics(track);
  const plain = useExtractedPlainLyrics(track);
  const lyrics = lyricsOverride || extracted || (track ? (window.MUSIC_DB.lyrics[track.id] || null) : null);
  const containerRef = useRef(null);
  const lineRefs = useRef({});

  // find current line index based on position
  const currentIdx = useMemoL(() => {
    if (!lyrics) return -1;
    let idx = -1;
    for (let i = 0; i < lyrics.length; i++) {
      if (lyrics[i].t <= position) idx = i;
      else break;
    }
    return idx;
  }, [lyrics, position]);

  // auto-scroll the current line into view (within the lyrics scroll container)
  useEffect(() => {
    if (currentIdx < 0 || !containerRef.current) return;
    const node = lineRefs.current[currentIdx];
    if (!node) return;
    const ct = containerRef.current;
    // center the line within the container
    const cRect = ct.getBoundingClientRect();
    const nRect = node.getBoundingClientRect();
    const offset = (nRect.top + nRect.height / 2) - (cRect.top + cRect.height / 2);
    ct.scrollTop += offset;
  }, [currentIdx]);

  if (!track) {
    return (
      <div className="lyrics-empty" style={{ display: "grid", placeItems: "center", height: "100%", color: "var(--ink-3)", padding: 40, textAlign: "center" }}>
        <div>
          <div style={{ fontFamily: "var(--f-display)", fontSize: 32, color: "var(--ink-2)", textTransform: "uppercase" }}>Press play</div>
          <div style={{ fontSize: 13, marginTop: 8 }}>Lyrics appear here when a track is loaded</div>
        </div>
      </div>
    );
  }

  if (!lyrics) {
    if (plain) {
      // Unsynced lyrics — show as a static block
      return (
        <div className="lyrics" ref={containerRef}>
          <div style={{ minHeight: "10vh" }} />
          <div style={{ fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--gold)", marginBottom: 12, fontWeight: 700 }}>
            ♪ Unsynced lyrics
          </div>
          {plain.split(/\r?\n/).map((line, i) => (
            <div key={i} className="lyric-line upcoming" style={compact ? { fontSize: 22, padding: "6px 0" } : undefined}>
              {line || <span style={{opacity: 0.4}}>♪</span>}
            </div>
          ))}
          <div style={{ minHeight: "30vh" }} />
        </div>
      );
    }
    return (
      <div className="lyrics" ref={containerRef}>
        <div style={{ minHeight: "30vh" }} />
        <div className="lyric-line" style={{ color: "var(--ink-3)", fontSize: compact ? 20 : 26 }}>
          No lyrics available for this track.
        </div>
        <div className="lyric-line" style={{ color: "var(--ink-4)", fontSize: compact ? 14 : 16, fontFamily: "var(--f-body)", textTransform: "none", fontWeight: 500 }}>
          Lyrics are read from the file's embedded tags (m4a ©lyr, mp3 USLT/SYLT, flac LYRICS).
        </div>
        <div style={{ minHeight: "30vh" }} />
      </div>
    );
  }

  return (
    <div className="lyrics" ref={containerRef}>
      <div style={{ minHeight: "30vh" }} />
      {lyrics.map((l, i) => {
        const cls =
          i === currentIdx ? "current"
          : i < currentIdx ? "past"
          : "upcoming";
        return (
          <div
            key={i}
            ref={(el) => (lineRefs.current[i] = el)}
            className={`lyric-line ${cls} ${l.i ? "instrumental" : ""}`}
            style={compact ? { fontSize: 22, padding: "6px 0" } : undefined}
            onClick={() => onSeek?.(l.t)}
          >
            {l.i ? (
              <>
                <span className="dot" />
                <span className="dot" />
                <span className="dot" />
              </>
            ) : (l.line || <span style={{opacity: 0.4}}>♪</span>)}
          </div>
        );
      })}
      <div style={{ minHeight: "40vh" }} />
    </div>
  );
}

window.LyricsView = LyricsView;
