<template>
  <header class="bg-noctune-teal px-4 py-3 flex items-center justify-between border-b-4 border-black">
    <div class="flex items-center gap-4">
      <router-link to="/home" class="text-black font-bold text-2xl tracking-wider font-mono">NOCTUNE</router-link>
    </div>

    <div class="flex-1 max-w-md mx-8 relative">
      <div class="relative">
        <div class="absolute inset-y-0 left-3 flex items-center pointer-events-none">
          <svg class="w-5 h-5 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
        </div>
        <input type="text" v-model="query" @input="onSearch" @keydown.escape="clearSearch" placeholder="Search music, artist, album..."
          class="w-full bg-noctune-cream py-2 pl-10 pr-4 rounded-full text-sm focus:outline-none focus:ring-2 focus:ring-black" />
      </div>
      <div v-if="searchResults && query" class="absolute top-full mt-2 left-0 right-0 bg-white border-2 border-black rounded-lg shadow-[4px_4px_0px_0px_#000] max-h-96 overflow-y-auto z-50">
        <div v-if="searchResults.tracks?.length" class="p-2">
          <p class="text-xs font-bold text-gray-500 px-2 py-1">TRACKS</p>
          <div v-for="track in searchResults.tracks.slice(0, 5)" :key="track._id" @click="playSearchTrack(track)" class="flex items-center gap-3 px-2 py-2 hover:bg-gray-100 rounded cursor-pointer">
            <div class="w-8 h-8 bg-gray-300 rounded border border-black flex-shrink-0 overflow-hidden">
              <img v-if="track.coverUrl" :src="formatUrl(track.coverUrl)" class="w-full h-full object-cover" />
            </div>
            <div class="min-w-0 flex-1">
              <p class="text-sm font-medium text-black truncate">{{ track.title }}</p>
              <p class="text-xs text-gray-500">{{ track.artist }}</p>
            </div>
          </div>
        </div>
        <div v-if="searchResults.artists?.length" class="p-2 border-t border-gray-200">
          <p class="text-xs font-bold text-gray-500 px-2 py-1">ARTISTS</p>
          <div v-for="artist in searchResults.artists.slice(0, 3)" :key="artist.name" @click="router.push(`/home?artist=${artist.name}`)" class="px-2 py-2 hover:bg-gray-100 rounded cursor-pointer text-sm font-medium text-black">{{ artist.name }}</div>
        </div>
        <div v-if="!searchResults.tracks?.length && !searchResults.artists?.length" class="p-4 text-center text-gray-500 text-sm">No results found</div>
      </div>
    </div>

    <div class="flex items-center gap-4">
      <button @click="toggleLikeRedirect" class="text-black hover:opacity-80">
        <svg class="w-7 h-7" fill="currentColor" viewBox="0 0 24 24">
          <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
        </svg>
      </button>
      <button @click="goToProfile" class="text-black hover:opacity-80">
        <div class="w-8 h-8 rounded-full bg-noctune-dark overflow-hidden border-2 border-black">
          <img v-if="authStore.user?.avatarUrl" :src="formatUrl(authStore.user.avatarUrl)" class="w-full h-full object-cover" />
          <div v-else class="w-full h-full flex items-center justify-center">
            <svg class="w-5 h-5 text-white" fill="currentColor" viewBox="0 0 24 24"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/></svg>
          </div>
        </div>
      </button>
    </div>
  </header>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/authStore.js'
import { usePlayerStore } from '../stores/playerStore.js'
import { useQueueStore } from '../stores/queueStore.js'
import api from '../lib/api.js'
import { formatUrl } from '../lib/utils.js'
import { useAuthGate } from '../composables/useAuthGate.js'

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

const query = ref('')
const searchResults = ref(null)
let searchTimeout = null

function onSearch() {
  clearTimeout(searchTimeout)
  if (!query.value.trim()) {
    searchResults.value = null
    return
  }
  searchTimeout = setTimeout(async () => {
    try {
      const { data } = await api.get(`/search?q=${encodeURIComponent(query.value)}`)
      if (data.success) searchResults.value = data.data
    } catch {
      searchResults.value = null
    }
  }, 300)
}

function clearSearch() {
  query.value = ''
  searchResults.value = null
}

function playSearchTrack(track) {
  clearSearch()
  queueStore.setQueue([track], 0)
  playerStore.setTrack(track)
  playerStore.play()
}

function toggleLikeRedirect() {
  requireAuth({
    redirectTo: '/login',
    onAuthenticated: () => router.push('/library')
  })
}

function goToProfile() {
  requireAuth({
    redirectTo: '/login',
    onAuthenticated: () => router.push('/profile')
  })
}
</script>
