import React, { useRef, useEffect } from 'react'

function Player({ song, isPlaying, onTogglePlay }) {
  if (!song) return null

  const audioRef = useRef(null)

  // 当播放状态变化时，控制音频播放
  useEffect(() => {
    if (audioRef.current) {
      if (isPlaying) {
        audioRef.current.play().catch(err => {
          console.error('播放失败:', err)
          onTogglePlay() // 播放失败时重置状态
        })
      } else {
        audioRef.current.pause()
      }
    }
  }, [isPlaying, onTogglePlay])

  // 当歌曲变化时，重置播放
  useEffect(() => {
    if (audioRef.current) {
      audioRef.current.currentTime = 0
      if (isPlaying) {
        audioRef.current.play().catch(err => {
          console.error('播放失败:', err)
          onTogglePlay() // 播放失败时重置状态
        })
      }
    }
  }, [song, isPlaying, onTogglePlay])

  return (
    <div className="player">
      <div className="now-playing">
        <img 
          src={`https://picsum.photos/200/200?random=${song.id}`} 
          alt={song.title} 
        />
        <div className="now-playing-info">
          <h4>{song.title}</h4>
          <p>{song.artist}</p>
        </div>
      </div>
      
      <div className="playback-controls">
        <button className="btn btn-secondary">⏮</button>
        <button className="play-btn" onClick={onTogglePlay}>
          {isPlaying ? '⏸' : '▶'}
        </button>
        <button className="btn btn-secondary">⏭</button>
      </div>
      
      <div className="player-actions">
        <button className="btn btn-secondary">❤️</button>
        <button className="btn btn-secondary">📋</button>
      </div>
      
      {/* 音频播放器元素 */}
      <audio 
        ref={audioRef} 
        src={song.audioUrl || 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3'} 
        preload="auto"
      />
    </div>
  )
}

export default Player