<template>
  <div v-if="playerStore.currentTrack" class="fixed bottom-0 left-0 right-0 bg-noctune-dark border-t-4 border-black z-50">
    <div class="flex items-center px-4 py-2 max-w-screen-2xl mx-auto">
      <div class="flex items-center gap-3 w-80">
        <div class="w-12 h-12 bg-black rounded-lg overflow-hidden flex-shrink-0 border border-white/20">
          <img v-if="playerStore.currentTrack.coverUrl" :src="coverSrc" alt="" class="w-full h-full object-cover" />
          <div v-else class="w-full h-full flex items-center justify-center">
            <svg class="w-8 h-6 text-white/60" viewBox="0 0 50 30"><rect x="2" y="10" width="3" height="10" fill="currentColor"/><rect x="8" y="5" width="3" height="20" fill="currentColor"/><rect x="14" y="8" width="3" height="14" fill="currentColor"/><rect x="20" y="3" width="3" height="24" fill="currentColor"/><rect x="26" y="7" width="3" height="16" fill="currentColor"/><rect x="32" y="5" width="3" height="20" fill="currentColor"/><rect x="38" y="9" width="3" height="12" fill="currentColor"/><rect x="44" y="11" width="3" height="8" fill="currentColor"/></svg>
          </div>
        </div>
        <div class="min-w-0">
          <p class="text-sm font-bold text-white truncate">{{ playerStore.currentTrack.title }}</p>
          <p class="text-xs text-gray-400 truncate">{{ playerStore.currentTrack.artist }}</p>
        </div>
      </div>

      <div class="flex-1 flex flex-col items-center">
        <div class="flex items-center gap-4 mb-1">
          <button @click="queueStore.toggleShuffle()" :class="['text-sm transition-colors', queueStore.shuffle ? 'text-noctune-teal' : 'text-gray-400 hover:text-white']">
            <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M10.59 9.17L5.41 4 4 5.41l5.17 5.17 1.42-1.41zM14.5 4l2.04 2.04L4 18.59 5.41 20 17.96 7.46 20 9.5V4h-5.5zm.33 9.41l-1.41 1.41 3.13 3.13L14.5 20H20v-5.5l-2.04 2.04-3.13-3.13z"/></svg>
          </button>
          <button @click="playPrev()" class="text-gray-400 hover:text-white transition-colors">
            <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24"><path d="M6 6h2v12H6zm3.5 6l8.5 6V6z"/></svg>
          </button>
          <button @click="playerStore.togglePlay()" class="w-10 h-10 bg-white rounded-full flex items-center justify-center hover:scale-105 transition-transform">
            <svg v-if="playerStore.isPlaying" class="w-5 h-5 text-black" fill="currentColor" viewBox="0 0 24 24"><path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/></svg>
            <svg v-else class="w-5 h-5 text-black ml-0.5" fill="currentColor" viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>
          </button>
          <button @click="playNext()" class="text-gray-400 hover:text-white transition-colors">
            <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24"><path d="M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"/></svg>
          </button>
          <button @click="queueStore.cycleRepeat()" :class="['text-sm transition-colors', queueStore.repeat !== 'off' ? 'text-noctune-teal' : 'text-gray-400 hover:text-white', queueStore.repeat === 'one' ? 'relative' : '']">
            <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z"/></svg>
            <span v-if="queueStore.repeat === 'one'" class="absolute -top-2 -right-2 text-[9px] font-bold">1</span>
          </button>
        </div>
        <div class="flex items-center gap-3 w-full max-w-lg">
          <span class="text-xs text-gray-400 w-10 text-right">{{ playerStore.formattedProgress }}</span>
          <div class="relative flex-1" @mousemove="onSeekHover" @mouseleave="seekTooltipVal = null">
            <div v-if="seekTooltipVal !== null" class="absolute -top-6 left-1/2 -translate-x-1/2 bg-black text-white text-xs px-2 py-1 rounded whitespace-nowrap z-10"
              :style="{ left: `${(seekTooltipVal / (playerStore.duration || 1)) * 100}%` }">
              {{ formatSeekTime(seekTooltipVal) }}
            </div>
            <input type="range" :value="playerStore.progress" @input="onSeek" min="0" :max="playerStore.duration || 1" step="0.1" class="w-full h-1 bg-gray-600 rounded-full appearance-none cursor-pointer range-player" />
          </div>
          <span class="text-xs text-gray-400 w-10">{{ playerStore.formattedDuration }}</span>
        </div>
      </div>

      <div class="w-80 flex items-center justify-end gap-3">
        <button @click="toggleLike" class="transition-colors">
          <svg class="w-5 h-5" :class="isLiked ? 'fill-red-400 text-red-400' : 'text-gray-400 hover:text-red-400'" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"/></svg>
        </button>
        <div class="flex items-center gap-2">
          <svg class="w-4 h-4 text-gray-400" fill="currentColor" viewBox="0 0 24 24"><path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02z"/></svg>
          <input type="range" :value="playerStore.volume" @input="onVolume" min="0" max="100" class="w-20 h-1 bg-gray-600 rounded-full appearance-none cursor-pointer range-vol" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { usePlayerStore } from '../stores/playerStore.js'
import { useQueueStore } from '../stores/queueStore.js'
import { useAuthStore } from '../stores/authStore.js'
import { formatUrl } from '../lib/utils.js'
import { useAuthGate } from '../composables/useAuthGate.js'

const playerStore = usePlayerStore()
const queueStore = useQueueStore()
const authStore = useAuthStore()
const { requireAuth } = useAuthGate()

const isLiked = ref(false)
const seekTooltipVal = ref(null)

function formatSeekTime(seconds) {
  const m = Math.floor(seconds / 60)
  const s = Math.floor(seconds % 60)
  return `${m}:${s.toString().padStart(2, '0')}`
}

function onSeekHover(e) {
  const rect = e.currentTarget.getBoundingClientRect()
  const pct = (e.clientX - rect.left) / rect.width
  seekTooltipVal.value = pct * playerStore.duration
}

function onTrackEnd() {
  const next = queueStore.nextTrack()
  if (next) {
    playerStore.setTrack(next)
    playerStore.play()
  }
}

onMounted(() => {
  playerStore.onEnd(onTrackEnd)
})

const coverSrc = computed(() => formatUrl(playerStore.currentTrack?.coverUrl))

function onSeek(e) {
  playerStore.seek(parseFloat(e.target.value))
}

function onVolume(e) {
  playerStore.setVolume(parseInt(e.target.value))
}

function playNext() {
  const next = queueStore.nextTrack()
  if (next) {
    playerStore.setTrack(next)
    playerStore.play()
  }
}

function playPrev() {
  const prev = queueStore.prevTrack()
  if (prev) {
    playerStore.setTrack(prev)
    playerStore.play()
  }
}

function toggleLike() {
  if (!playerStore.currentTrack) return
  const id = playerStore.currentTrack._id || playerStore.currentTrack.id
  requireAuth({
    redirectTo: '/login',
    onAuthenticated: () => authStore.toggleLike(id)
  })
}

// Sync isLiked ref reactively from authStore
watch(() => playerStore.currentTrack?._id, (id) => {
  isLiked.value = id ? authStore.likedTrackIds.has(id) : false
}, { immediate: true })

watch(() => authStore.user?.likedTracks?.length, () => {
  const id = playerStore.currentTrack?._id
  if (id) isLiked.value = authStore.likedTrackIds.has(id)
})
</script>

<style scoped>
.range-player::-webkit-slider-thumb,
.range-vol::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: white;
  cursor: pointer;
}
</style>
