mira, tengo esto:

import React, { useState, useEffect, useRef } from "react";
import YouTube, { YouTubeProps, YouTubePlayer } from "react-youtube";
import {
  Play,
  Pause,
  SkipBack,
  SkipForward,
  Shuffle,
  Repeat,
  Volume1,
  Volume2,
  VolumeX,
  Maximize2,
  Home,
  Search,
  Library,
  Menu,
  X,
} from "lucide-react";
import { Button } from "./components/ui/button"; // Asegúrate de que la ruta sea correcta
import { Input } from "./components/ui/input"; // Agregado para el campo de búsqueda

// Interfaz para las canciones
interface Song {
  title: string;
  artist: string;
  album: string;
  added: string;
  duration?: number;
  youtubeId?: string;
}

// Lista de canciones con youtubeId
const songs: Song[] = [
  {
    title: "Las Piponas (Remix)",
    artist: "Kris R., Blessed",
    album: "Las Piponas (Remix)",
    added: "hace 2 horas",
    duration: 242,
    youtubeId: "Dftj21lTUIA",
  },
  // Puedes agregar más canciones aquí
];

// Información de la playlist
const playlist = {
  name: "Time Free",
  description: "Relajao",
  owner: "Johan Morales",
  timesSaved: 8,
  songsCount: 1253,
  totalDuration: "72 h 6 min",
  coverImage: "https://i.postimg.cc/y8KhsW1p/imagen-blessd.jpg", // Asegúrate de que esta URL sea correcta
};

// Función para obtener la miniatura de YouTube
const getYouTubeThumbnail = (youtubeId: string): string =>
  `https://img.youtube.com/vi/${youtubeId}/hqdefault.jpg`;

const SpotifyClone = () => {
  const [currentSong, setCurrentSong] = useState<Song | null>(null); // Inicializar como null
  const [isPlaying, setIsPlaying] = useState<boolean>(false);
  const [isSidebarOpen, setIsSidebarOpen] = useState<boolean>(true);
  const [isMobile, setIsMobile] = useState<boolean>(window.innerWidth < 1024);

  const playerRef = useRef<YouTubePlayer | null>(null);

  const [currentTime, setCurrentTime] = useState<number>(0);
  const [duration, setDuration] = useState<number>(0);

  const [volume, setVolume] = useState<number>(100);

  useEffect(() => {
    const handleResize = () => {
      if (window.innerWidth < 1024) {
        setIsMobile(true);
        setIsSidebarOpen(false);
      } else {
        setIsMobile(false);
        setIsSidebarOpen(true);
      }
    };

    handleResize();

    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  // Cargar y reproducir el video cuando cambia la canción actual
  useEffect(() => {
    if (playerRef.current && currentSong?.youtubeId) {
      playerRef.current.loadVideoById(currentSong.youtubeId);
      setCurrentTime(0);
      setDuration(0);
      if (isPlaying) {
        playerRef.current.playVideo();
      }
    }
  }, [currentSong]); // Removed isPlaying from dependencies

  // Reproducir o pausar cuando cambia el estado isPlaying
  useEffect(() => {
    if (playerRef.current) {
      if (isPlaying) {
        playerRef.current.playVideo();
      } else {
        playerRef.current.pauseVideo();
      }
    }
  }, [isPlaying]);

  // Actualizar el tiempo actual y la duración
  useEffect(() => {
    let intervalId: NodeJS.Timeout | null = null;

    if (playerRef.current && isPlaying) {
      intervalId = setInterval(() => {
        const current = playerRef.current!.getCurrentTime();
        const dura = playerRef.current!.getDuration();
        setCurrentTime(current);
        setDuration(dura);
      }, 1000);
    }

    return () => {
      if (intervalId) clearInterval(intervalId);
    };
  }, [isPlaying]); // Removed playerRef.current from dependencies

  const handlePlayPause = () => {
    if (isPlaying) {
      playerRef.current?.pauseVideo();
    } else {
      if (currentSong?.youtubeId) {
        playerRef.current?.playVideo();
      }
    }
    setIsPlaying(!isPlaying);
  };

  const handleNextSong = () => {
    if (!currentSong) return; // Asegurar que currentSong no sea null
    const currentIndex = songs.indexOf(currentSong);
    const nextIndex = (currentIndex + 1) % songs.length;
    const nextSong = songs[nextIndex];
    setIsPlaying(false);
    setCurrentSong(nextSong);
    // La reproducción de la siguiente canción se maneja en el useEffect de currentSong
  };

  const handlePreviousSong = () => {
    if (!currentSong) return; // Asegurar que currentSong no sea null
    const currentIndex = songs.indexOf(currentSong);
    const previousIndex = (currentIndex - 1 + songs.length) % songs.length;
    const previousSong = songs[previousIndex];
    setIsPlaying(false);
    setCurrentSong(previousSong);
    // La reproducción de la canción anterior se maneja en el useEffect de currentSong
  };

  const onPlayerReady: YouTubeProps["onReady"] = (event) => {
    playerRef.current = event.target;
    setDuration(event.target.getDuration());

    event.target.setVolume(volume);

    if (isPlaying) {
      event.target.playVideo();
    }
  };

  const onPlayerEnd: YouTubeProps["onEnd"] = () => {
    handleNextSong();
  };

  const onPlayerStateChange: YouTubeProps["onStateChange"] = (event) => {
    if (event.data === window.YT.PlayerState.ENDED) {
      handleNextSong();
    }
  };

  const opts: YouTubeProps["opts"] = {
    height: "0",
    width: "0",
    playerVars: {
      autoplay: 0,
      controls: 0,
      disablekb: 1,
      fs: 0,
      modestbranding: 1,
      rel: 0,
    },
  };

  const formatTime = (seconds: number): string => {
    const minutes = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    const minutesStr = minutes < 10 ? `0${minutes}` : `${minutes}`;
    const secondsStr = secs < 10 ? `0${secs}` : `${secs}`;
    return `${minutesStr}:${secondsStr}`;
  };

  const handleProgressChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newTime = Number(e.target.value);
    if (playerRef.current) {
      playerRef.current.seekTo(newTime, true);
      setCurrentTime(newTime);
    }
  };

  const handleVolumeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newVolume = Number(e.target.value);
    setVolume(newVolume);
    if (playerRef.current) {
      playerRef.current.setVolume(newVolume);
    }
  };

  const toggleMute = () => {
    if (playerRef.current) {
      if (playerRef.current.isMuted()) {
        playerRef.current.unMute();
        setVolume(playerRef.current.getVolume());
      } else {
        playerRef.current.mute();
        setVolume(0);
      }
    }
  };

  return (
    <div className="flex flex-col h-screen text-gray-300 bg-black">
      {/* Renderizar el reproductor solo si hay una canción seleccionada */}
      {currentSong?.youtubeId && (
        <YouTube
          videoId={currentSong.youtubeId}
          opts={opts}
          onReady={onPlayerReady}
          onEnd={onPlayerEnd}
          onStateChange={onPlayerStateChange}
        />
      )}

      {/* Barra de navegación superior */}
      <div className="flex items-center justify-between p-4 bg-gray-900">
        {/* Condicionalmente renderizar el contenido del navbar basado en si es móvil o no */}
        {isMobile ? (
          // Navbar simplificado para móviles: solo el buscador
          <div className="flex-1">
            <Input
              type="text"
              placeholder="¿Qué quieres reproducir?"
              className={`w-full px-4 py-2 text-sm rounded-full focus:outline-none focus:ring-2 ${
                isMobile
                  ? "bg-transparent placeholder-white text-white focus:ring-red-500"
                  : "bg-gray-800 placeholder-gray-400 text-white focus:ring-green-500"
              }`}
            />
          </div>
        ) : (
          // Navbar completo para escritorio
          <>
            {/* Botón de menú */}
            <Button
              variant="ghost"
              size="icon"
              className="text-gray-400 hover:text-white"
              onClick={() => setIsSidebarOpen(!isSidebarOpen)}
              aria-label={isSidebarOpen ? "Cerrar menú" : "Abrir menú"}
            >
              {isSidebarOpen ? (
                <X className="w-5 h-5" />
              ) : (
                <Menu className="w-5 h-5" />
              )}
            </Button>

            {/* Barra de búsqueda */}
            <div className="flex-1 max-w-xl mx-4">
              <Input
                type="text"
                placeholder="¿Qué quieres reproducir?"
                className={`w-full px-4 py-2 text-sm rounded-full focus:outline-none focus:ring-2 ${
                  isMobile
                    ? "bg-transparent placeholder-white text-white focus:ring-red-500"
                    : "bg-gray-800 placeholder-gray-400 text-white focus:ring-green-500"
                }`}
              />
            </div>

            {/* Botones de usuario y perfil */}
            <div className="flex items-center space-x-4">
              <Button
                variant="ghost"
                size="icon"
                className="text-gray-400 hover:text-white"
                aria-label="Usuario"
              >
                <svg
                  width="24"
                  height="24"
                  viewBox="0 0 24 24"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M12 12C15.3137 12 18 9.31371 18 6C18 2.68629 15.3137 0 12 0C8.68629 0 6 2.68629 6 6C6 9.31371 8.68629 12 12 12Z"
                    fill="currentColor"
                  />
                  <path
                    d="M12 14C8.13401 14 0 16.1188 0 19V24H24V19C24 16.1188 15.866 14 12 14Z"
                    fill="currentColor"
                  />
                </svg>
              </Button>
              {/* Reemplazar la div con fondo colorido por una imagen */}
              <img
                src="https://i.postimg.cc/Kjx7YXWv/yo.webp"
                alt="Usuario"
                className="w-8 h-8 rounded-full"
              />
            </div>
          </>
        )}
      </div>

      {/* Barra lateral y contenido principal */}
      <div className="flex flex-1 overflow-hidden">
        {/* Barra lateral */}
        <div
          className={`fixed inset-y-0 left-0 z-50 w-64 p-4 overflow-y-auto bg-gray-900 transform ${
            isSidebarOpen ? "translate-x-0" : "-translate-x-full"
          } transition-transform duration-300 ease-in-out
                      lg:translate-x-0 lg:static lg:inset-auto`}
        >
          <div className="mb-6">
            <Button
              variant="ghost"
              className="w-full justify-start text-gray-400 hover:text-white mb-2"
              aria-label="Inicio"
            >
              <Home className="w-5 h-5 mr-3" />
              Inicio
            </Button>
            <Button
              variant="ghost"
              className="w-full justify-start text-gray-400 hover:text-white mb-2"
              aria-label="Buscar"
            >
              <Search className="w-5 h-5 mr-3" />
              Buscar
            </Button>
            <Button
              variant="ghost"
              className="w-full justify-start text-gray-400 hover:text-white"
              aria-label="Tu biblioteca"
            >
              <Library className="w-5 h-5 mr-3" />
              Tu biblioteca
            </Button>
          </div>
          <div className="pt-4 border-t border-gray-800">
            <h2 className="mb-4 text-sm font-semibold text-gray-400 uppercase">
              Playlists
            </h2>
            <Button
              variant="ghost"
              className="w-full justify-start text-white bg-gray-800 hover:bg-gray-700 mb-2 flex items-center"
              aria-label="Time Free"
            >
              <div className="w-12 h-12 mr-3 bg-gradient-to-br from-purple-700 to-blue-400 rounded-md"></div>
              Time Free
            </Button>
          </div>
        </div>

        {/* Fondo transparente para cerrar la barra lateral en dispositivos móviles */}
        {isSidebarOpen && isMobile && (
          <div
            className="fixed inset-0 bg-black opacity-50 z-40 lg:hidden"
            onClick={() => setIsSidebarOpen(false)}
          ></div>
        )}

        {/* Contenido principal */}
        <div
          className={`flex-1 p-6 overflow-y-auto bg-gradient-to-b from-red-900 to-gray-900 transition-margin duration-300 ease-in-out ${
            isSidebarOpen && !isMobile ? "lg:ml-64" : "lg:ml-0"
          }`}
        >
          {/* Información de la Playlist */}
          <div className="flex flex-col lg:flex-row items-start mb-6">
            <img
              src={playlist.coverImage || "/placeholder.svg"}
              alt="Playlist cover"
              className="w-40 h-40 mr-6 object-cover rounded-md"
            />
            <div className="text-left">
              {/* Condicionalmente renderizar 'Playlist pública' solo si no es móvil */}
              {!isMobile && (
                <p className="text-sm font-medium">Playlist pública</p>
              )}
              <h1 className="text-5xl font-bold mb-2">{playlist.name}</h1>
              <p className="text-sm">{playlist.description}</p>
              <div className="flex items-center mt-2">
                <img
                  src="https://i.postimg.cc/Kjx7YXWv/yo.webp"
                  alt="Propietario"
                  className="w-6 h-6 rounded-full mr-2"
                />
                <div className="flex flex-col">
                  <span className="text-sm">{playlist.owner}</span>
                  <span className="text-sm text-gray-400">
                    {`${playlist.timesSaved} veces guardada • ${playlist.songsCount} canciones, ${playlist.totalDuration}`}
                  </span>
                </div>
              </div>
            </div>
          </div>

          {/* Controles de reproducción */}
          {currentSong && (
            <div className="flex items-center space-x-4 mb-6">
              <Button
                size="lg"
                className="rounded-full bg-green-500 hover:bg-green-400"
                onClick={handlePlayPause}
                aria-label={isPlaying ? "Pausar" : "Reproducir"}
              >
                {isPlaying ? (
                  <Pause fill="black" className="w-6 h-6 text-black" />
                ) : (
                  <Play fill="black" className="w-6 h-6 text-black" />
                )}
              </Button>
              <Button
                variant="outline"
                size="icon"
                className="rounded-full"
                aria-label="Agregar a la cola"
              >
                <svg
                  width="24"
                  height="24"
                  viewBox="0 0 24 24"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M4.5 12.75L19.5 12.75"
                    stroke="currentColor"
                    strokeWidth="1.5"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                  <path
                    d="M12 5.25L12 20.25"
                    stroke="currentColor"
                    strokeWidth="1.5"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
              </Button>
              <Button variant="ghost" size="icon" aria-label="Más opciones">
                •••
              </Button>
            </div>
          )}

          {/* Lista de canciones */}
          <table className="w-full">
            <thead>
              <tr className="text-left text-sm text-gray-400 border-b border-gray-800">
                {!isMobile && <th className="pb-2">#</th>}
                <th className="pb-2">Título</th>
                {!isMobile && <th className="pb-2">Álbum</th>}
                {!isMobile && <th className="pb-2">Fecha en que se agregó</th>}
                {!isMobile && (
                  <th className="pb-2">
                    <svg
                      width="16"
                      height="16"
                      viewBox="0 0 16 16"
                      fill="none"
                      xmlns="http://www.w3.org/2000/svg"
                    >
                      <path
                        d="M8 3.33337V12.6667"
                        stroke="currentColor"
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                      <path
                        d="M3.33331 8H12.6666"
                        stroke="currentColor"
                        strokeWidth="2"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                    </svg>
                  </th>
                )}
              </tr>
            </thead>
            <tbody>
              {songs.map((track, index) => (
                <tr
                  key={index}
                  className="hover:bg-gray-800 cursor-pointer"
                  onClick={() => {
                    if (track.youtubeId) {
                      setCurrentSong(track);
                      setIsPlaying(true); // Establecer isPlaying directamente en true
                    }
                  }}
                >
                  {!isMobile && <td className="py-2">{index + 1}</td>}
                  <td className="py-2">
                    <div className="flex items-center">
                      <img
                        src={
                          track.youtubeId
                            ? getYouTubeThumbnail(track.youtubeId)
                            : "/placeholder.svg"
                        }
                        alt="Video thumbnail"
                        className="w-10 h-10 mr-4 object-cover rounded-md"
                      />
                      <div>
                        <p className="font-medium">{track.title}</p>
                        <p className="text-sm text-gray-400">{track.artist}</p>
                      </div>
                    </div>
                  </td>
                  {!isMobile && (
                    <td className="py-2 text-sm text-gray-400">
                      {track.album}
                    </td>
                  )}
                  {!isMobile && (
                    <td className="py-2 text-sm text-gray-400">
                      {track.added}
                    </td>
                  )}
                  {!isMobile && (
                    <td className="py-2 text-sm text-gray-400">
                      {track.duration ? formatTime(track.duration) : "--:--"}
                    </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Now Playing Bar (solo para dispositivos móviles, solo si hay una canción seleccionada) */}
      {isMobile && currentSong && (
        <div className="bg-gray-900 p-2 fixed bottom-0 left-0 right-0 z-50">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-2 flex-grow">
              <img
                src={
                  currentSong.youtubeId
                    ? getYouTubeThumbnail(currentSong.youtubeId)
                    : "/placeholder.svg"
                }
                alt="Now playing cover"
                className="w-12 h-12 rounded"
              />
              <div>
                <p className="font-medium">{currentSong.title}</p>
                <p className="text-sm text-gray-400">{currentSong.artist}</p>
              </div>
            </div>
            <div className="flex items-center space-x-4">
              <Button
                variant="ghost"
                size="icon"
                className="text-white"
                onClick={handlePlayPause}
                aria-label={isPlaying ? "Pausar" : "Reproducir"}
              >
                {isPlaying ? (
                  <Pause className="h-6 w-6" fill="currentColor" />
                ) : (
                  <Play className="h-6 w-6" fill="currentColor" />
                )}
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* Barra de reproducción (solo para pantallas grandes, solo si hay una canción seleccionada) */}
      {!isMobile && currentSong && (
        <div
          className={`flex flex-col lg:flex-row items-center justify-between p-4 bg-gray-900 border-t border-gray-800 fixed bottom-0 left-0 right-0 ${
            !isMobile ? "lg:ml-64" : "lg:ml-0"
          } transition-margin duration-300 ease-in-out`}
        >
          {/* Información de la canción actual */}
          <div className="flex items-center mb-4 lg:mb-0 w-full lg:w-1/3 justify-center lg:justify-start">
            <img
              src={
                currentSong.youtubeId
                  ? getYouTubeThumbnail(currentSong.youtubeId)
                  : "/placeholder.svg"
              }
              alt="Album cover"
              className="w-10 h-10 mr-4 object-cover rounded-md"
            />
            <div>
              <p className="font-medium">{currentSong.title}</p>
              <p className="text-sm text-gray-400">{currentSong.artist}</p>
            </div>
          </div>

          {/* Controles de reproducción y progreso */}
          <div className="flex flex-col items-center w-full lg:w-1/3">
            <div className="flex items-center space-x-4 mb-2">
              <Button
                variant="ghost"
                size="icon"
                className="text-gray-400 hover:text-white"
                aria-label="Shuffle"
              >
                <Shuffle className="w-5 h-5" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="text-gray-400 hover:text-white"
                onClick={handlePreviousSong}
                aria-label="Anterior"
              >
                <SkipBack className="w-5 h-5" />
              </Button>
              <Button
                size="icon"
                className={`rounded-full bg-white hover:bg-gray-200`}
                onClick={handlePlayPause}
                aria-label={isPlaying ? "Pausar" : "Reproducir"}
              >
                {isPlaying ? (
                  <Pause className="w-6 h-6 text-black" />
                ) : (
                  <Play className="w-6 h-6 text-black" />
                )}
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="text-gray-400 hover:text-white"
                onClick={handleNextSong}
                aria-label="Siguiente"
              >
                <SkipForward className="w-5 h-5" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="text-gray-400 hover:text-white"
                aria-label="Repetir"
              >
                <Repeat className="w-5 h-5" />
              </Button>
            </div>
            <div className="flex items-center w-full space-x-2">
              <span className="text-xs text-gray-400">
                {formatTime(currentTime)}
              </span>
              <input
                type="range"
                min={0}
                max={duration}
                value={currentTime}
                onChange={handleProgressChange}
                className="flex-1 h-1 bg-gray-600 rounded-full cursor-pointer appearance-none focus:outline-none"
              />
              <span className="text-xs text-gray-400">
                {formatTime(duration)}
              </span>
            </div>
          </div>

          {/* Controles de volumen y pantalla completa */}
          <div className="flex items-center justify-end w-full lg:w-1/3 mt-4 lg:mt-0">
            <Button
              variant="ghost"
              size="icon"
              className="text-gray-400 hover:text-white mr-2"
              onClick={toggleMute}
              aria-label={volume === 0 ? "Desmutear" : "Mute"}
            >
              {volume === 0 ? (
                <VolumeX className="w-5 h-5" />
              ) : volume <= 50 ? (
                <Volume1 className="w-5 h-5" />
              ) : (
                <Volume2 className="w-5 h-5" />
              )}
            </Button>
            <input
              type="range"
              min={0}
              max={100}
              value={volume}
              onChange={handleVolumeChange}
              className="w-24 h-1 bg-gray-600 rounded-full cursor-pointer appearance-none focus:outline-none"
            />
            <Button
              variant="ghost"
              size="icon"
              className="text-gray-400 hover:text-white ml-2"
              aria-label="Pantalla completa"
            >
              <Maximize2 className="w-5 h-5" />
            </Button>
          </div>
        </div>
      )}
    </div>
  );
};

export default SpotifyClone;

pero necesito optimizar el codigo y que sa mas facil de mantener, puedes ayudarme?