"use client"

import { create } from "zustand"
import { Podcast } from "@/app/generated/prisma"

interface AudioPlayerState {
  isPlaying: boolean
  currentPodcast: Podcast | null
  playPodcast: (podcast: Podcast) => void
  pausePodcast: () => void
  togglePlayPause: () => void
}

export const useAudioPlayer = create<AudioPlayerState>((set) => ({
  isPlaying: false,
  currentPodcast: null,
  playPodcast: (podcast) => set({ isPlaying: true, currentPodcast: podcast }),
  pausePodcast: () => set({ isPlaying: false }),
  togglePlayPause: () => set((state) => ({ isPlaying: !state.isPlaying })),
}))


"use client"

import { useAudioPlayer } from "@/hooks/use-audio-player"
import { Play, Pause, SkipBack, SkipForward, Volume2, Calendar } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Slider } from "@/components/ui/slider"
import { useState, useEffect, useRef } from "react"
import { formatPublishedDate } from "@/lib/utils"



export function AudioPlayer() {
  const { isPlaying, currentPodcast, togglePlayPause } = useAudioPlayer()
  const [progress, setProgress] = useState(0)
  const audioRef = useRef<HTMLAudioElement | null>(null)

  const prevPodcastIdRef = useRef<string | null>(null)

  useEffect(() => {
    if (!currentPodcast) {
      prevPodcastIdRef.current = null
      return
    }
    if (prevPodcastIdRef.current !== currentPodcast.id && audioRef.current) {
        audioRef.current.currentTime = 0

    }
    prevPodcastIdRef.current = currentPodcast.id
  }, [currentPodcast])

  useEffect(() => {
    if (!audioRef.current) return
    if (isPlaying) audioRef.current.play().catch(console.error)
    else audioRef.current.pause()
  }, [isPlaying])

  useEffect(() => {
    if (currentPodcast) document.body.classList.add("player-active")
    return () => {
      document.body.classList.remove("player-active")
    }
  }, [currentPodcast])

  useEffect(() => {
    if (currentPodcast?.audioUrl) {
            if (!audioRef.current) {
                audioRef.current = new Audio()
            }

      audioRef.current.src = currentPodcast.audioUrl

            if (isPlaying) {
                audioRef.current.play().catch((err) => {
                    console.error("Error playing audio:", err)
                })
    }
        }

    return () => {
      audioRef.current?.pause()
    }
  }, [currentPodcast, isPlaying])

  useEffect(() => {
    if (!audioRef.current) return
    if (isPlaying) audioRef.current.play().catch((err) => console.error(err))
    else audioRef.current.pause()
  }, [isPlaying])

  useEffect(() => {
    if (!audioRef.current) return
    const update = () => {
      const d = audioRef.current!.duration || 0
      const t = audioRef.current!.currentTime || 0
      setProgress((t / d) * 100)
    }
    audioRef.current.addEventListener("timeupdate", update)
    return () => audioRef.current!.removeEventListener("timeupdate", update)
  }, [currentPodcast])

  if (!currentPodcast) return null

  const handleSeek = (v: number[]) => {
    if (!audioRef.current) return
    const t = (v[0] / 100) * (audioRef.current.duration || 0)
    audioRef.current.currentTime = t
    setProgress(v[0])
  }

  return (
    <div className="fixed bottom-0 left-0 right-0 bg-gradient-to-r from-emerald-950/90 via-black/90 to-blue-950/90 backdrop-blur-md border-t border-emerald-900/50 p-4 z-50">
            <div className="container mx-auto flex items-center justify-between">
                <div className="flex items-center gap-4">
                    <div className="bg-emerald-400 rounded-md p-2">
                        <Volume2 className="h-5 w-5 text-black" />
                    </div>
                    <div>
                        <h4 className="font-medium text-white">{currentPodcast.title}</h4>
                        <div className="flex text-sm text-emerald-400/80">
                            <span className="inline-flex items-center">
                                <Calendar className="h-3 w-3 mr-1" />
                            {formatPublishedDate(currentPodcast.publishedAt)}
                            </span>
                        </div>
                    </div>
                </div>

                <div className="flex flex-col items-center gap-2 flex-1 max-w-md mx-4">
                    <div className="flex items-center gap-4">
                        <Button size="icon" variant="ghost" className="text-white">
                            <SkipBack className="h-4 w-4" />
                        </Button>
                        <Button
                            size="icon"
                            className="rounded-full bg-emerald-400 hover:bg-emerald-500 text-black"
                            onClick={togglePlayPause}
                        >
                            {isPlaying ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />}
                        </Button>
                        <Button size="icon" variant="ghost" className="text-white">
                            <SkipForward className="h-4 w-4" />
                        </Button>
                    </div>
                    <div className="w-full flex items-center gap-2">
                        <span className="text-xs text-white/60">{formatTime(audioRef.current?.currentTime || 0)}</span>
                        <Slider value={[progress]} max={100} step={0.1} className="flex-1" onValueChange={handleSeek} />
                        <span className="text-xs text-white/60">{currentPodcast.duration}</span>
                    </div>
                </div>

                <div className="flex items-center gap-2 w-32">
                    <Volume2 className="h-4 w-4 text-white/60" />
                    <Slider defaultValue={[80]} max={100} step={1} className="flex-1" />
                </div>
            </div>
    </div>
  )
}

function formatTime(seconds: number): string {
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins}:${secs.toString().padStart(2, "0")}`
}
The audio player restarts from the beginning when pressing pause and then play again. keep the state of where the audio is