'use client'

import { useState, useRef, useEffect, useCallback } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import {
  Play,
  Pause,
  SkipForward,
  SkipBack,
  Volume2,
  VolumeX,
  X,
} from 'lucide-react'
import type { MediaItem } from '@/lib/types'

// ─── helpers ────────────────────────────────────────────────────────────────

function formatTime(s: number) {
  if (!s || isNaN(s) || !isFinite(s)) return '--:--'
  const m = Math.floor(s / 60)
  const sec = Math.floor(s % 60)
  return `${m}:${sec.toString().padStart(2, '0')}`
}

function WaveformBars({ playing }: { playing: boolean }) {
  return (
    <div className="flex items-end gap-px h-4">
      {[0.55, 1, 0.7, 0.9, 0.5].map((h, i) => (
        <motion.div
          key={i}
          className="w-[3px] bg-amber-400/70 rounded-full"
          animate={
            playing
              ? { height: ['30%', `${h * 100}%`, '45%', `${h * 75}%`, '30%'] }
              : { height: '30%' }
          }
          transition={{ duration: 0.75 + i * 0.13, repeat: Infinity, ease: 'easeInOut', delay: i * 0.11 }}
          style={{ height: '30%' }}
        />
      ))}
    </div>
  )
}

// ─── ambient audio via Web Audio API ────────────────────────────────────────
// A-minor chord: A1 55Hz · A2 110Hz · C3 130.81Hz · E3 164.81Hz · A3 220Hz

function useAmbient() {
  const ctxRef = useRef<AudioContext | null>(null)
  const stopFnsRef = useRef<(() => void)[]>([])
  const [playing, setPlaying] = useState(false)

  const start = useCallback(() => {
    if (ctxRef.current) return
    const ctx = new AudioContext()
    ctxRef.current = ctx

    const master = ctx.createGain()
    master.gain.setValueAtTime(0, ctx.currentTime)
    master.gain.linearRampToValueAtTime(0.11, ctx.currentTime + 6)
    master.connect(ctx.destination)

    // Feedback delay for spaciousness
    const delay = ctx.createDelay(2.0)
    delay.delayTime.value = 1.4
    const fbGain = ctx.createGain()
    fbGain.gain.value = 0.22
    delay.connect(fbGain)
    fbGain.connect(delay)
    fbGain.connect(master)

    const notes = [
      { freq: 55,     gain: 0.55 },
      { freq: 110,    gain: 0.45 },
      { freq: 130.81, gain: 0.38 },
      { freq: 164.81, gain: 0.48 },
      { freq: 220,    gain: 0.30 },
    ]

    notes.forEach(({ freq, gain }, i) => {
      const osc = ctx.createOscillator()
      osc.type = 'sine'
      osc.frequency.value = freq + (i % 2 === 0 ? 0.15 : -0.15) // micro-detune
      const g = ctx.createGain()
      g.gain.value = gain

      // Slow per-note swell LFO
      const lfo = ctx.createOscillator()
      lfo.type = 'sine'
      lfo.frequency.value = 0.06 + i * 0.018
      const lfoG = ctx.createGain()
      lfoG.gain.value = gain * 0.38
      lfo.connect(lfoG)
      lfoG.connect(g.gain)
      lfo.start()

      osc.connect(g)
      g.connect(master)
      g.connect(delay)
      osc.start()

      stopFnsRef.current.push(() => {
        try { osc.stop(); lfo.stop() } catch { /* already stopped */ }
      })
    })

    setPlaying(true)
  }, [])

  const stop = useCallback(() => {
    const ctx = ctxRef.current
    if (!ctx) return
    const master = ctx.destination
    // Fade out gracefully
    const g = ctx.createGain()
    g.gain.setValueAtTime(1, ctx.currentTime)
    g.gain.linearRampToValueAtTime(0, ctx.currentTime + 1.5)
    g.connect(master)
    setTimeout(() => {
      stopFnsRef.current.forEach((fn) => fn())
      stopFnsRef.current = []
      ctx.close()
      ctxRef.current = null
      setPlaying(false)
    }, 1600)
  }, [])

  const toggle = useCallback(() => {
    if (playing) stop()
    else start()
  }, [playing, start, stop])

  return { playing, toggle, start, stop }
}

// ─── component ──────────────────────────────────────────────────────────────

export default function MusicPlayer({ tracks }: { tracks: MediaItem[] }) {
  const [current, setCurrent] = useState(0)
  const [playing, setPlaying] = useState(false)
  const [volume, setVolume] = useState(0.4)
  const [muted, setMuted] = useState(false)
  const [progress, setProgress] = useState(0)
  const [duration, setDuration] = useState(0)
  const [elapsed, setElapsed] = useState(0)
  const [miniVisible, setMiniVisible] = useState(false)
  const audioRef = useRef<HTMLAudioElement>(null)
  const ambient = useAmbient()

  const hasTrack = tracks.length > 0
  const track = tracks[current] ?? null

  const trackName = (i: number) =>
    tracks[i]?.original_name?.replace(/\.[^/.]+$/, '') ||
    tracks[i]?.caption ||
    `Titel ${i + 1}`

  useEffect(() => {
    const a = audioRef.current
    if (!a) return
    a.volume = muted ? 0 : volume
  }, [volume, muted])

  useEffect(() => {
    const a = audioRef.current
    if (!a || !track) return
    a.src = `/api/files/${track.filename}`
    a.volume = muted ? 0 : volume
    setDuration(0); setElapsed(0); setProgress(0)
    if (playing) a.play().catch(() => setPlaying(false))
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [current])

  const togglePlay = () => {
    const a = audioRef.current
    if (!a) return
    if (playing) a.pause()
    else a.play().catch(() => setPlaying(false))
  }

  const playTrack = (i: number) => {
    if (i === current) togglePlay()
    else { setCurrent(i); setPlaying(true) }
    setMiniVisible(true)
  }

  const prev = () => setCurrent((c) => (c - 1 + tracks.length) % tracks.length)
  const next = () => setCurrent((c) => (c + 1) % tracks.length)

  const handleTimeUpdate = () => {
    const a = audioRef.current
    if (!a || !a.duration) return
    setProgress((a.currentTime / a.duration) * 100)
    setElapsed(a.currentTime)
  }

  const handleSeek = (e: React.ChangeEvent<HTMLInputElement>) => {
    const a = audioRef.current
    if (!a || !a.duration) return
    const pct = parseFloat(e.target.value)
    a.currentTime = (pct / 100) * a.duration
    setProgress(pct)
  }

  // Decide what the mini-player shows
  const miniLabel = hasTrack ? trackName(current) : 'Stille Begleitung'
  const miniPlaying = hasTrack ? playing : ambient.playing

  return (
    <>
      {hasTrack && (
        <audio
          ref={audioRef}
          src={`/api/files/${track!.filename}`}
          onEnded={next}
          onTimeUpdate={handleTimeUpdate}
          onLoadedMetadata={() => { const a = audioRef.current; if (a) setDuration(a.duration) }}
          onPlay={() => setPlaying(true)}
          onPause={() => setPlaying(false)}
        />
      )}

      {/* ── Inline section ─────────────────────────────────────── */}
      <section
        id="musik"
        className="py-20 px-4"
        style={{ background: 'linear-gradient(to bottom, #0a0706, #060304)' }}
      >
        <div className="max-w-xl mx-auto">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            className="text-center mb-12"
          >
            <p className="text-amber-200/30 text-xs tracking-[0.5em] uppercase font-lora mb-3">
              Begleitung in Tönen
            </p>
            <h2 className="font-cormorant italic text-4xl sm:text-5xl text-amber-100/70 mb-3">
              Musik
            </h2>
            <div className="flex items-center justify-center gap-4">
              <div className="h-px w-12 bg-amber-400/15" />
              <span className="text-amber-400/25">♪</span>
              <div className="h-px w-12 bg-amber-400/15" />
            </div>
          </motion.div>

          {/* ── No uploads: ambient player ── */}
          {!hasTrack && (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ duration: 1 }}
              className="text-center"
            >
              <p className="font-lora text-amber-100/30 text-sm mb-8 leading-relaxed max-w-xs mx-auto">
                Ein sanftes Klangteppich begleitet dich,
                während du durch die Erinnerungen scrollst.
              </p>

              <div className="flex flex-col items-center gap-5">
                <motion.button
                  onClick={() => { ambient.toggle(); setMiniVisible(true) }}
                  whileTap={{ scale: 0.94 }}
                  className="w-16 h-16 rounded-full bg-amber-400/10 hover:bg-amber-400/18 border border-amber-400/20 hover:border-amber-400/40 text-amber-300/70 flex items-center justify-center transition-all duration-200"
                  style={{ boxShadow: ambient.playing ? '0 0 28px rgba(196,160,74,0.14)' : undefined }}
                >
                  {ambient.playing
                    ? <Pause size={22} />
                    : <Play size={22} className="ml-1" />
                  }
                </motion.button>

                {ambient.playing && (
                  <motion.div
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    className="flex items-end gap-1"
                  >
                    <WaveformBars playing={ambient.playing} />
                  </motion.div>
                )}

                <p className="font-cormorant italic text-amber-200/35 text-lg">
                  Stille Begleitung
                </p>
              </div>
            </motion.div>
          )}

          {/* ── With uploads: track list + controls ── */}
          {hasTrack && (
            <>
              <div className="space-y-0.5 mb-8">
                {tracks.map((t, i) => (
                  <motion.button
                    key={t.id}
                    initial={{ opacity: 0, x: -8 }}
                    whileInView={{ opacity: 1, x: 0 }}
                    viewport={{ once: true }}
                    transition={{ delay: i * 0.05 }}
                    onClick={() => playTrack(i)}
                    className={`w-full flex items-center gap-4 px-4 py-3.5 rounded-xl transition-all duration-200 text-left group ${
                      i === current
                        ? 'bg-amber-400/[0.07] border border-amber-400/15'
                        : 'hover:bg-white/[0.03] border border-transparent'
                    }`}
                  >
                    <div className="w-7 flex-shrink-0 flex items-center justify-center">
                      {i === current && playing
                        ? <WaveformBars playing={playing} />
                        : <span className={`font-lora text-xs tabular-nums ${i === current ? 'text-amber-400/60' : 'text-amber-100/20'}`}>
                            {String(i + 1).padStart(2, '0')}
                          </span>
                      }
                    </div>
                    <span className={`font-cormorant italic text-lg flex-1 min-w-0 truncate transition-colors ${
                      i === current ? 'text-amber-200/80' : 'text-amber-100/35 group-hover:text-amber-100/60'
                    }`}>
                      {trackName(i)}
                    </span>
                    <span className="flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
                      {i === current && playing
                        ? <Pause size={13} className="text-amber-400/50" />
                        : <Play size={13} className="text-amber-400/40" />
                      }
                    </span>
                  </motion.button>
                ))}
              </div>

              {/* Controls */}
              <div className="border-t border-amber-400/10 pt-6">
                <p className="text-center font-cormorant italic text-amber-200/50 text-xl mb-5 truncate px-4">
                  {trackName(current)}
                </p>

                <div className="flex items-center gap-3 mb-6">
                  <span className="font-lora text-xs text-amber-100/20 w-9 text-right tabular-nums">{formatTime(elapsed)}</span>
                  <input
                    type="range" min="0" max="100" step="0.1" value={progress}
                    onChange={handleSeek}
                    className="flex-1 cursor-pointer accent-amber-500"
                    style={{ height: '2px' }}
                  />
                  <span className="font-lora text-xs text-amber-100/20 w-9 tabular-nums">{formatTime(duration)}</span>
                </div>

                <div className="flex items-center justify-center gap-8 mb-5">
                  <button onClick={prev} className="text-amber-400/30 hover:text-amber-400/70 transition-colors">
                    <SkipBack size={20} />
                  </button>
                  <motion.button
                    onClick={() => { togglePlay(); setMiniVisible(true) }}
                    whileTap={{ scale: 0.93 }}
                    className="w-14 h-14 rounded-full bg-amber-400/10 hover:bg-amber-400/18 border border-amber-400/20 hover:border-amber-400/40 text-amber-300/80 flex items-center justify-center transition-all duration-200"
                    style={{ boxShadow: playing ? '0 0 24px rgba(196,160,74,0.15)' : undefined }}
                  >
                    {playing ? <Pause size={22} /> : <Play size={22} className="ml-0.5" />}
                  </motion.button>
                  <button onClick={next} className="text-amber-400/30 hover:text-amber-400/70 transition-colors">
                    <SkipForward size={20} />
                  </button>
                </div>

                <div className="flex items-center justify-center gap-3">
                  <button onClick={() => setMuted((m) => !m)} className="text-amber-600/40 hover:text-amber-400/60 transition-colors">
                    {muted ? <VolumeX size={15} /> : <Volume2 size={15} />}
                  </button>
                  <input
                    type="range" min="0" max="1" step="0.01"
                    value={muted ? 0 : volume}
                    onChange={(e) => { setVolume(parseFloat(e.target.value)); setMuted(false) }}
                    className="w-28 accent-amber-600 cursor-pointer"
                    style={{ height: '2px' }}
                  />
                </div>
              </div>
            </>
          )}
        </div>
      </section>

      {/* ── Floating mini-player ─────────────────────────────────── */}
      <AnimatePresence>
        {miniVisible && (
          <motion.div
            initial={{ opacity: 0, y: 16, scale: 0.95 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 16, scale: 0.95 }}
            transition={{ duration: 0.25 }}
            className="fixed bottom-6 right-6 z-50 flex items-center gap-3 bg-stone-950/96 backdrop-blur-md px-4 py-3 rounded-2xl border border-amber-900/25 shadow-2xl"
          >
            <div className="relative flex-shrink-0">
              <div className={`w-8 h-8 rounded-full bg-amber-800/40 flex items-center justify-center ${miniPlaying ? 'ring-1 ring-amber-400/30' : ''}`}>
                {miniPlaying
                  ? <WaveformBars playing />
                  : <Play size={12} className="text-amber-300/70 ml-0.5" />
                }
              </div>
              {miniPlaying && (
                <span className="absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full bg-amber-400 animate-pulse" />
              )}
            </div>

            <button
              onClick={() => document.getElementById('musik')?.scrollIntoView({ behavior: 'smooth' })}
              className="max-w-[130px] text-left"
            >
              <p className="text-amber-200/70 font-cormorant italic text-sm truncate leading-tight">
                {miniLabel}
              </p>
              <p className="text-amber-600/40 text-xs font-lora mt-0.5">
                {hasTrack
                  ? (playing ? `${formatTime(elapsed)} / ${formatTime(duration)}` : 'pausiert')
                  : (ambient.playing ? 'läuft …' : 'pausiert')
                }
              </p>
            </button>

            <button
              onClick={hasTrack ? togglePlay : () => { ambient.toggle() }}
              className="text-amber-400/60 hover:text-amber-300 transition-colors"
            >
              {miniPlaying ? <Pause size={16} /> : <Play size={16} />}
            </button>

            <button
              onClick={() => setMiniVisible(false)}
              className="text-amber-800/60 hover:text-amber-500/80 transition-colors ml-1"
            >
              <X size={13} />
            </button>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  )
}
