<template>
  <div class="p-8">
    <div class="flex items-start gap-8 mb-12">
      <div class="flex-1">
        <h1 class="text-5xl font-black text-black leading-tight mb-2">MUSIC<br/>THAT HITS</h1>
        <div class="inline-block bg-noctune-orange px-4 py-2 mb-4 border-b-4 border-black">
          <span class="text-4xl font-black text-black">DIFFERENT.</span>
        </div>
        <p class="text-gray-600 mb-6">You Vibe. Your sound. Only on Noctune.</p>
        <div class="flex gap-4">
          <button @click="playFirstTrack" class="bg-noctune-yellow border-2 border-black px-6 py-3 font-bold hover:bg-yellow-400 transition-colors rounded-lg">PLAY NOW</button>
          <button class="bg-gray-200 border-2 border-black px-6 py-3 font-bold hover:bg-gray-300 transition-colors rounded-lg">EXPLORE</button>
        </div>
      </div>
      <div class="w-80 h-80 rounded-2xl overflow-hidden border-4 border-black flex-shrink-0">
        <img src="https://images.unsplash.com/photo-1470225620780-dba8ba36b745?w=400&h=400&fit=crop" alt="Music illustration" class="w-full h-full object-cover" />
      </div>
    </div>

    <section>
      <h2 class="text-2xl font-black text-black mb-6 flex items-center">
        TRENDING NOW
        <svg class="w-5 h-5 ml-2" fill="currentColor" viewBox="0 0 24 24"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/></svg>
      </h2>
      <div v-if="loading" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
        <div v-for="i in 4" :key="i" class="animate-pulse rounded-2xl border-2 border-black overflow-hidden">
          <div class="aspect-square bg-gray-300" />
          <div class="p-3 space-y-2">
            <div class="h-3 bg-gray-300 rounded w-3/4" />
            <div class="h-2 bg-gray-300 rounded w-1/2" />
          </div>
        </div>
      </div>
      <div v-else-if="tracks.length === 0" class="text-center py-20 bg-white rounded-2xl border-2 border-black">
        <svg class="w-24 h-24 mx-auto text-gray-300 mb-4" fill="currentColor" viewBox="0 0 24 24"><path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55C7.79 13 6 14.79 6 17s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"/></svg>
        <p class="text-gray-500 mb-2 text-lg">No tracks yet</p>
        <p class="text-gray-400 text-sm mb-4">Be the first to upload music!</p>
        <router-link to="/admin/tracks" class="inline-block bg-noctune-orange border-2 border-black px-6 py-3 font-bold rounded-lg hover:bg-orange-500 transition-colors">UPLOAD TRACK</router-link>
      </div>
      <div v-else class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
        <div v-for="track in tracks" :key="track._id"
          @click="playTrack(track)"
          class="bg-white rounded-2xl overflow-hidden hover:scale-[1.02] transition-transform cursor-pointer group"
          :class="isCurrentTrack(track) ? 'border-4 border-noctune-teal' : 'border-2 border-black'"
        >
          <div class="aspect-square bg-gray-300 relative overflow-hidden">
            <img v-if="track.coverUrl" :src="formatUrl(track.coverUrl)" class="w-full h-full object-cover" />
            <div class="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors flex items-center justify-center">
              <div class="w-12 h-12 rounded-full flex items-center justify-center border-2 border-black opacity-0 group-hover:opacity-100 transition-opacity"
                :class="isCurrentTrack(track) && playerStore.isPlaying ? 'bg-white' : 'bg-noctune-yellow'">
                <svg v-if="isCurrentTrack(track) && playerStore.isPlaying" class="w-6 h-6 text-black" fill="currentColor" viewBox="0 0 24 24"><path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/></svg>
                <svg v-else class="w-6 h-6 ml-1 text-black" fill="currentColor" viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>
              </div>
            </div>
          </div>
          <div class="p-3">
            <div class="flex items-center justify-between">
              <div class="flex-1 min-w-0">
                <p class="text-sm font-bold text-black truncate">{{ track.title }}</p>
                <p class="text-xs text-gray-500 truncate">{{ track.artist }}</p>
              </div>
              <button @click.stop="toggleLike(track)" class="ml-2 flex-shrink-0">
                <svg class="w-5 h-5" :class="isLiked(track) ? '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>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { usePlayerStore } from '../stores/playerStore.js'
import { useQueueStore } from '../stores/queueStore.js'
import { useAuthStore } from '../stores/authStore.js'
import api from '../lib/api.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 tracks = ref([])
const loading = ref(true)

function isCurrentTrack(track) {
  return playerStore.currentTrack?._id === track._id
}

function isLiked(track) {
  return authStore.likedTrackIds?.has(track._id)
}

function playTrack(track) {
  if (isCurrentTrack(track)) {
    playerStore.togglePlay()
    return
  }
  const idx = tracks.value.findIndex((t) => t._id === track._id)
  queueStore.setQueue(tracks.value, idx)
  playerStore.setTrack(track)
  playerStore.play()
}

function playFirstTrack() {
  if (tracks.value.length) playTrack(tracks.value[0])
}

function toggleLike(track) {
  requireAuth({
    redirectTo: '/login',
    onAuthenticated: () => authStore.toggleLike(track._id)
  })
}

onMounted(async () => {
  try {
    const { data } = await api.get('/tracks')
    if (data.success) tracks.value = data.data
  } catch {
    // ignore
  } finally {
    loading.value = false
  }
})
</script>
