<script setup lang="ts">
const { user, signOut, initAuth, isLoading } = useAuth()
const showLoginModal = ref(false)

// Initialize auth on component mount
onMounted(() => {
  initAuth()
})

const handleSignOut = async () => {
  try {
    await signOut()
  } catch (error) {
    console.error('Sign out failed:', error)
  }
}
</script>

<template>
  <nav class="sticky top-0 z-30 border-b border-slate-800/60 bg-slate-950/80 backdrop-blur">
    <div class="mx-auto max-w-6xl px-4 py-4 sm:px-6 lg:px-8">
      <div class="flex items-center justify-between gap-6">
        <p class="text-lg font-semibold text-white sm:text-xl">Slipmatz</p>
        <div class="flex items-center gap-3">
          <!-- Show user info and logout when authenticated -->
          <div v-if="user && !isLoading" class="flex items-center gap-3">
            <span class="text-sm text-slate-300">{{ user.email }}</span>
            <button
              type="button"
              @click="handleSignOut"
              class="rounded-full border border-slate-700/80 px-4 py-2 text-sm font-medium text-slate-200 transition hover:border-rose-500 hover:text-rose-300 focus:outline-none focus-visible:ring-2 focus-visible:ring-rose-500 focus-visible:ring-offset-2 focus-visible:ring-offset-slate-950"
            >
              Logout
            </button>
          </div>
          
          <!-- Show login button when not authenticated -->
          <div v-else-if="!isLoading" class="flex items-center gap-3">
            <button
              type="button"
              @click="showLoginModal = true"
              class="rounded-full border border-slate-700/80 px-4 py-2 text-sm font-medium text-slate-200 transition hover:border-slate-500 hover:text-white focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-500 focus-visible:ring-offset-2 focus-visible:ring-offset-slate-950"
            >
              Login
            </button>
          </div>
          
          <!-- Loading state -->
          <div v-else class="flex items-center gap-3">
            <div class="h-8 w-16 animate-pulse rounded bg-slate-700"></div>
          </div>
        </div>
      </div>
    </div>
    
    <LoginModal v-model="showLoginModal" />
  </nav>
</template>
