<template>
  <div v-if="show" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50" @click.self="$emit('close')">
    <div class="bg-white rounded-2xl border-4 border-black p-6 w-full max-w-md mx-4 shadow-[8px_8px_0px_0px_#000]">
      <div class="flex items-center justify-between mb-4">
        <h2 class="text-xl font-black text-black">SAVE TO PLAYLIST</h2>
        <button @click="$emit('close')" class="text-gray-500 hover:text-black text-2xl leading-none">&times;</button>
      </div>

      <p v-if="error" class="text-red-500 text-sm mb-3 font-medium">{{ error }}</p>

      <div v-if="loading" class="space-y-3">
        <div v-for="i in 3" :key="i" class="h-14 bg-gray-200 animate-pulse rounded-lg border-2 border-black" />
      </div>

      <div v-else-if="playlists.length === 0" class="text-center py-8">
        <svg class="w-16 h-16 mx-auto text-gray-300 mb-3" fill="currentColor" viewBox="0 0 24 24"><path d="M3 10h11v2H3v-2zm0-4h11v2H3V6zm0 8h7v2H3v-2zm13-1v8l6-4-6-4z"/></svg>
        <p class="text-gray-500 mb-2">No playlists yet</p>
        <button @click="openCreatePlaylist" class="bg-noctune-yellow border-2 border-black px-4 py-2 font-bold rounded-lg text-sm hover:bg-yellow-400 transition-colors cursor-pointer">
          CREATE PLAYLIST
        </button>
      </div>

      <div v-else class="max-h-80 overflow-y-auto space-y-2">
        <div v-for="pl in playlists" :key="pl._id"
          @click="addToPlaylist(pl)"
          class="flex items-center gap-3 px-4 py-3 rounded-lg border-2 border-black cursor-pointer hover:bg-noctune-teal/10 transition-colors"
          :class="savingId === pl._id ? 'opacity-50 pointer-events-none' : ''"
        >
          <div class="w-12 h-12 rounded-lg overflow-hidden bg-gray-300 border border-black flex-shrink-0">
            <img v-if="pl.coverUrl" :src="formatUrl(pl.coverUrl)" class="w-full h-full object-cover" />
            <div v-else class="w-full h-full flex items-center justify-center bg-gradient-to-br from-noctune-teal/20 to-noctune-yellow/20">
              <svg class="w-6 h-5 text-gray-400" fill="currentColor" viewBox="0 0 24 24"><path d="M3 10h11v2H3v-2zm0-4h11v2H3V6zm0 8h7v2H3v-2zm13-1v8l6-4-6-4z"/></svg>
            </div>
          </div>
          <div class="flex-1 min-w-0">
            <p class="font-bold text-sm text-black truncate">{{ pl.name }}</p>
            <p class="text-xs text-gray-500">{{ pl.tracks?.length || 0 }} songs</p>
          </div>
          <svg v-if="savingId === pl._id" class="w-5 h-5 animate-spin text-noctune-teal" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/></svg>
          <svg v-else class="w-5 h-5 text-gray-400" fill="currentColor" viewBox="0 0 24 24"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/></svg>
        </div>
      </div>
    </div>

    <CreatePlaylistModal :show="showCreateModal" @close="showCreateModal = false" @created="onPlaylistCreated" />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useAuthStore } from '../stores/authStore.js'
import { useUiStore } from '../stores/uiStore.js'
import api from '../lib/api.js'
import { formatUrl } from '../lib/utils.js'
import CreatePlaylistModal from './CreatePlaylistModal.vue'

const props = defineProps({
  show: Boolean,
  trackId: { type: String, default: null },
})

const emit = defineEmits(['close'])

const authStore = useAuthStore()
const uiStore = useUiStore()

const playlists = ref([])
const loading = ref(false)
const savingId = ref(null)
const error = ref('')
const showCreateModal = ref(false)

function openCreatePlaylist() {
  showCreateModal.value = true
}

function onPlaylistCreated(pl) {
  showCreateModal.value = false
  playlists.value.unshift(pl)
}

async function addToPlaylist(pl) {
  if (!props.trackId) return
  savingId.value = pl._id
  error.value = ''
  try {
    const { data } = await api.post(`/playlists/${pl._id}/tracks`, { trackId: props.trackId })
    if (data.success) {
      uiStore.showToast(`Saved to "${pl.name}"`, 'success')
      emit('close')
    }
  } catch (err) {
    const msg = err.response?.data?.message || ''
    if (msg.includes('already') || msg.includes('duplicate')) {
      uiStore.showToast(`Already in "${pl.name}"`, 'info')
      emit('close')
    } else {
      error.value = msg || 'Failed to save track'
    }
  } finally {
    savingId.value = null
  }
}

async function fetchPlaylists() {
  if (!authStore.isLoggedIn) return
  loading.value = true
  try {
    const { data } = await api.get('/playlists')
    if (data.success) playlists.value = data.data
  } catch {
    // ignore
  } finally {
    loading.value = false
  }
}

watch(() => props.show, (val) => {
  if (val) fetchPlaylists()
})
</script>
