text: import React, { useState, useEffect, useRef } from "react";
  import { useParams } from 'react-router-dom';
  import { useSelector } from 'react-redux';
  import AudioControls from "./AudioControls";
  import TrackList from './TrackList'
  import "./AudioStreamer.css";
  
  
  const PlaylistStreamer = ({ tracks, }) => {
      // State
    const [trackIndex, setTrackIndex] = useState(0);
    const [trackProgress, setTrackProgress] = useState(0);
    const [isPlaying, setIsPlaying] = useState(false);
    const [audioSrc, setAudioSrc] = useState();
    const [image, setImage] = useState('');
    const [title, setTitle] = useState('');
    const [artist, setArtist] = useState('');
    const { artistId } = useParams();
    const artistData = useSelector((state) => state.app.artistData);
  
    useEffect(async () => {
      if(artistData){
        setArtist(artistData.first_name);
        setImage(artistData.mp3_playlists[0].image);
        setAudioSrc(artistData.mp3_playlists[0].mp3s[0].Location)
      }
    },[])
  
    useEffect(() => {
        console.log({ trackIndex })
        const { Key, Location } = tracks[trackIndex];
        console.log({ Key });
        console.log({ Location });
        console.log({ tracks })
        setTitle(Key);
        setAudioSrc(Location); 
        console.log({ audioSrc }); 
    },[trackIndex])
  
    // Destructure for conciseness  
  
    // Refs
    const audioRef = useRef(new Audio(audioSrc));
    const intervalRef = useRef();
    const isReady = useRef(false);
  
    // Destructure for conciseness
    const { duration } = audioRef.current;
  
    const currentPercentage = duration
      ? `${(trackProgress / duration) * 100}%`
      : "0%";
    const trackStyling = `
      -webkit-gradient(linear, 0% 0%, 100% 0%, color-stop(${currentPercentage}, #fff), color-stop(${currentPercentage}, #777))
    `;
  
    const startTimer = () => {
      // Clear any timers already running
      clearInterval(intervalRef.current);
  
      intervalRef.current = setInterval(() => {
        if (audioRef.current.ended) {
          toNextTrack();
        } else {
          setTrackProgress(audioRef.current.currentTime);
        }
      }, [1000]);
    };
  
    const onScrub = (value) => {
      // Clear any timers already running
      clearInterval(intervalRef.current);
      audioRef.current.currentTime = value;
      setTrackProgress(audioRef.current.currentTime);
    };
  
    const onScrubEnd = () => {
      // If not already playing, start
      if (!isPlaying) {
        setIsPlaying(true);
      }
      startTimer();
    };
  
    const toPrevTrack = () => {
      if (trackIndex - 1 < 0) {
        setTrackIndex(tracks.length - 1);
      } else {
        setTrackIndex(trackIndex - 1);
      }
    };
  
    const toNextTrack = () => {
      if (trackIndex < tracks.length - 1) {
        setTrackIndex(trackIndex + 1);
      } else {
        setTrackIndex(0);
      }
    };
  
    useEffect(() => {
      if (isPlaying) {
        audioRef.current.play();
        startTimer();
      } else {
        audioRef.current.pause();
      }
    }, [isPlaying]);
  
    // Handles cleanup and setup when changing tracks
    useEffect(() => {
      audioRef.current.pause();
  
      audioRef.current = new Audio(audioSrc);
      setTrackProgress(audioRef.current.currentTime);
  
      if (isReady.current) {
        audioRef.current.play();
        setIsPlaying(true);
        startTimer();
      } else {
        // Set the isReady ref as true for the next pass
        isReady.current = true;
      }
    }, [trackIndex]);
  
    useEffect(() => {
      // Pause and clean up on unmount
      return () => {
        audioRef.current.pause();
        clearInterval(intervalRef.current);
      };
    }, []);
  
    console.log({ audioSrc })
  
    return (
      <div>
      {audioSrc ?
      <div className="audio-player">
        <div className="track-info">
          <img
            className="artwork"
            src={image}
            alt={`track artwork for ${title} by ${artist}`}
          />
          <h2 className="title">{title}</h2>
          <h3 className="artist">{artist}</h3>
          <AudioControls
            isPlaying={isPlaying}
            onPrevClick={toPrevTrack}
            onNextClick={toNextTrack}
            onPlayPauseClick={setIsPlaying}
          />
          <input
            type="range"
            value={trackProgress}
            step="1"
            min="0"
            max={duration ? duration : `${duration}`}
            className="progress"
            onChange={(e) => onScrub(e.target.value)}
            onMouseUp={onScrubEnd}
            onKeyUp={onScrubEnd}
            style={{ background: trackStyling }}
          />
          <TrackList tracks={tracks}/>
        </div>
      </div> : <div>loading audio ... </div>}
      </div>
    );
  }
  
  export default PlaylistStreamer
  