import { useEffect, useMemo, useRef } from 'react';
import { usePlaybackStore } from '../store/usePlaybackStore';
import { parseLrc, activeLineIndex } from '../lib/lyrics';

interface SyncedLyricsProps {
  /** Raw LRC string from track_lyrics.synced_lyrics (may be null/unparseable). */
  synced: unknown;
  /** Plain lyrics fallback when there are no timestamped lines. */
  plain: string | null;
}

/**
 * Karaoke-style lyrics. When time-synced lyrics are available it highlights the
 * line for the current playback position, dims the rest, smoothly auto-scrolls
 * to keep the active line centered, and lets you click any line to seek there.
 * Falls back to plain scrollable text when no sync data exists.
 */
export function SyncedLyrics({ synced, plain }: SyncedLyricsProps) {
  const position = usePlaybackStore((s) => s.position);
  const setPosition = usePlaybackStore((s) => s.setPosition);

  const lines = useMemo(() => parseLrc(synced), [synced]);
  const active = activeLineIndex(lines, position);

  const activeRef = useRef<HTMLButtonElement>(null);

  // Keep the active line centered as it changes.
  useEffect(() => {
    activeRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }, [active]);

  if (lines.length === 0) {
    if (!plain) {
      return (
        <p className="px-6 py-10 text-center text-sm text-muted italic">No lyrics available.</p>
      );
    }
    return (
      <pre className="whitespace-pre-wrap px-6 py-6 text-center font-sans text-base leading-loose text-muted">
        {plain}
      </pre>
    );
  }

  return (
    <div className="px-5 py-[45%] space-y-5">
      {lines.map((line, i) => {
        const isActive = i === active;
        const isPast = i < active;
        // Lines near the active one stay a bit more legible than far ones.
        const distance = Math.abs(i - active);
        const upcomingOpacity = distance <= 2 ? 'opacity-70' : 'opacity-40';
        return (
          <button
            key={`${line.time}-${i}`}
            ref={isActive ? activeRef : undefined}
            onClick={() => setPosition(line.time)}
            className={`block w-full text-left text-2xl font-extrabold leading-tight tracking-tight transition-all duration-500 ease-out hover:text-text ${
              isActive
                ? 'text-accent scale-[1.03] origin-left [text-shadow:0_0_24px_var(--accent)]'
                : isPast
                  ? 'text-muted/30'
                  : `text-muted ${upcomingOpacity}`
            }`}
          >
            {line.text || '♪'}
          </button>
        );
      })}
    </div>
  );
}
