import { useEffect, useState } from 'react'
import { API_ROOT } from '../furumiApi'
import type { QueueItem } from './QueueList'

function Cover({ src }: { src: string }) {
  const [errored, setErrored] = useState(false)

  useEffect(() => {
    setErrored(false)
  }, [src])

  if (errored) return <>&#127925;</>
  return <img src={src} alt="" onError={() => setErrored(true)} />
}

export function NowPlaying({ track }: { track: QueueItem | null }) {
  if (!track) {
    return (
      <div className="np-info">
        <div className="np-cover" id="npCover">
          &#127925;
        </div>
        <div className="np-text">
          <div className="np-title" id="npTitle">
            Nothing playing
          </div>
          <div className="np-artist" id="npArtist">
            &mdash;
          </div>
        </div>
      </div>
    )
  }

  const coverUrl = `${API_ROOT}/tracks/${track.slug}/cover`

  return (
    <div className="np-info">
      <div className="np-cover" id="npCover">
        <Cover src={coverUrl} />
      </div>
      <div className="np-text">
        <div className="np-title" id="npTitle">
          {track.title}
        </div>
        <div className="np-artist" id="npArtist">
          {track.artist || '—'}
        </div>
      </div>
    </div>
  )
}

