import { playSound, SFX_BUTTON_DEFAULT } from '../../lib/sounds'
import type { Song } from './types'

type SongCardProps = {
  song: Song
  trackNumber: number
  offset: number
  isActive: boolean
  onClick: () => void
}

function renderDifficultyDots(difficulty: number) {
  return (
    <div className="song-card__difficulty" aria-label={`Difficulty ${difficulty} out of 5`}>
      {Array.from({ length: 5 }).map((_, index) => {
        const filled = index < difficulty
        return (
          <span
            key={index}
            className="song-card__difficulty-dot"
            style={{
              backgroundColor: filled
                ? '#fff'
                : 'rgba(0, 0, 0, 0.35)',
            }}
          />
        )
      })}
    </div>
  )
}

export function SongCard({ song, trackNumber, offset, isActive, onClick }: SongCardProps) {
  const abs = Math.abs(offset)
  const scale = isActive ? 1 : abs === 1 ? 0.83 : 0.67
  const opacity = isActive ? 1 : abs === 1 ? 0.72 : 0.4
  const x = offset * 220
  const z = isActive ? 0 : abs === 1 ? -80 : -170
  const rotateY = offset * -22

  return (
    <button
      type="button"
      className={`song-card${isActive ? ' song-card--active' : ''}`}
      onClick={() => {
        playSound(SFX_BUTTON_DEFAULT)
        onClick()
      }}
      style={{
        backgroundColor: song.color,
        transform: `translateX(${x}px) translateZ(${z}px) rotateY(${rotateY}deg) scale(${scale})`,
        opacity,
        zIndex: 20 - abs,
      }}
      aria-label={`Track ${trackNumber}: ${song.title} by ${song.artist}`}
      tabIndex={-1}
    >
      <img
        className="song-card__banner"
        src={song.bannerUrl}
        alt=""
        draggable={false}
      />
      {song.isCustom && (
        <span className="song-card__custom-badge" title="Stored locally">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
            <polyline points="7 10 12 15 17 10" />
            <line x1="12" y1="15" x2="12" y2="3" />
          </svg>
        </span>
      )}
      <p className="song-card__track font-caption">TRACK {String(trackNumber).padStart(2, '0')}</p>
      <h2 className="song-card__title font-title">{song.title}</h2>
      <p className="song-card__artist">{song.artist}</p>
      <div className="song-card__bottom-row">
        <p className="song-card__bpm">{song.bpm} BPM</p>
        {renderDifficultyDots(song.difficulty)}
      </div>
    </button>
  )
}
