import React, { useState } from 'react';

function SongCard({ song }) {
  const [playing, setPlaying] = useState(false);

  if (!song?.path) return null;

  const fileName = encodeURIComponent(song.path.split("\\").pop().split("/").pop());
  const audioSrc = `http://localhost:8000/songs/${fileName}`;

  return (
    <div className="rounded-lg shadow-md p-4 bg-white dark:bg-gray-800 flex flex-col items-center text-center">
      <img
        src={song.cover || '/default-cover.jpg'}
        alt={song.title}
        className="w-24 h-24 object-cover rounded"
      />
      <h3 className="mt-2 text-sm font-semibold text-gray-800 dark:text-white">
        {song.title || fileName.replace(".mp3", "")}
      </h3>
      <p className="text-xs text-gray-500 dark:text-gray-300">
        {song.artist || "Unknown"}
      </p>

      <button
        onClick={() => setPlaying(!playing)}
        className="mt-2 px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600"
      >
        {playing ? "Pause" : "Play"}
      </button>

      {playing && (
        <audio controls autoPlay className="mt-2 w-full">
          <source src={audioSrc} type="audio/mpeg" />
          Your browser does not support the audio element.
        </audio>
      )}
    </div>
  );
}

export default SongCard;
