<script setup lang="ts">
const auth = useAuth()
const route = useRoute()

// GitHub icon is a "marketing" affordance — only show it on the public landing
// page. Inside the app it just clutters the chrome.
const showGithub = computed(() => route.path === '/')

// Profile dropdown state. Closed by default; opens on click, closes on
// outside click / Escape / route change. Industry-standard pattern: the
// account-scoped actions (Account, Billing, Sign out) tuck under an avatar
// affordance instead of crowding the top-level nav.
const profileOpen = ref(false)
const profileRef = ref<HTMLElement | null>(null)

function initials(name?: string | null) {
  if (!name) return '·'
  return name
    .trim()
    .split(/\s+/)
    .slice(0, 2)
    .map((p) => p[0]?.toUpperCase() || '')
    .join('') || '·'
}

function onDocClick(e: MouseEvent) {
  if (!profileOpen.value) return
  const root = profileRef.value
  if (root && !root.contains(e.target as Node)) profileOpen.value = false
}
function onKeydown(e: KeyboardEvent) {
  if (e.key === 'Escape') profileOpen.value = false
}

if (import.meta.client) {
  onMounted(() => {
    window.addEventListener('click', onDocClick)
    window.addEventListener('keydown', onKeydown)
  })
  onUnmounted(() => {
    window.removeEventListener('click', onDocClick)
    window.removeEventListener('keydown', onKeydown)
  })
}
watch(() => route.fullPath, () => { profileOpen.value = false })

async function signOut() {
  profileOpen.value = false
  await auth.logout()
  navigateTo('/')
}
</script>

<template>
  <div class="min-h-screen bg-zinc-950 text-zinc-100 antialiased">
    <header class="border-b border-zinc-900">
      <div class="mx-auto flex max-w-6xl items-center justify-between px-6 py-4">
        <!-- Logo doubles as the "home" affordance. Signed-in users land
             on their events list; visitors get the marketing landing. -->
        <NuxtLink
          :to="auth.isAuthenticated.value ? '/dashboard' : '/'"
          class="flex items-center gap-2 text-lg font-semibold"
        >
          <span class="inline-block h-2.5 w-2.5 rounded-full bg-brand-500"></span>
          GuestGuard
        </NuxtLink>
        <nav class="flex items-center gap-2 text-sm text-zinc-400">
          <a
            v-if="showGithub"
            href="https://github.com/alchemistkay/guestguard"
            target="_blank"
            rel="noopener"
            class="rounded-md p-2 transition hover:bg-zinc-900 hover:text-zinc-100"
            title="View on GitHub"
            aria-label="View on GitHub"
          >
            <svg viewBox="0 0 24 24" class="h-5 w-5" fill="currentColor" aria-hidden="true">
              <path d="M12 0C5.374 0 0 5.373 0 12c0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23A11.509 11.509 0 0112 5.803c1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576C20.566 21.797 24 17.3 24 12c0-6.627-5.373-12-12-12z"/>
            </svg>
          </a>

          <ClientOnly>
            <template v-if="auth.isAuthenticated.value">
              <!-- Logo is the "home → events" affordance; the only top-level
                   nav element for signed-in users is the profile dropdown. -->

              <!-- Profile dropdown — Account / Billing / Sign out -->
              <div ref="profileRef" class="relative">
                <button
                  type="button"
                  class="flex items-center gap-2 rounded-md px-2 py-1.5 transition hover:bg-zinc-900 hover:text-zinc-100"
                  :aria-expanded="profileOpen"
                  aria-haspopup="menu"
                  aria-label="Account menu"
                  @click="profileOpen = !profileOpen"
                >
                  <span class="flex h-7 w-7 items-center justify-center rounded-full bg-brand-500/15 text-xs font-semibold text-brand-300">
                    {{ initials(auth.user.value?.name) }}
                  </span>
                  <svg
                    class="h-3 w-3 text-zinc-500 transition-transform"
                    :class="profileOpen ? 'rotate-180' : ''"
                    viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"
                  >
                    <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                  </svg>
                </button>

                <Transition
                  enter-active-class="transition duration-150 ease-out"
                  enter-from-class="-translate-y-1 opacity-0"
                  enter-to-class="translate-y-0 opacity-100"
                  leave-active-class="transition duration-100 ease-in"
                  leave-from-class="translate-y-0 opacity-100"
                  leave-to-class="-translate-y-1 opacity-0"
                >
                  <div
                    v-if="profileOpen"
                    role="menu"
                    class="absolute right-0 top-full z-30 mt-2 w-60 overflow-hidden rounded-lg border border-zinc-800 bg-zinc-950 shadow-2xl"
                  >
                    <div class="border-b border-zinc-900 px-3 py-3">
                      <p class="truncate text-sm font-medium text-zinc-100">
                        {{ auth.user.value?.name || 'Account' }}
                      </p>
                      <p class="truncate text-xs text-zinc-500">{{ auth.user.value?.email }}</p>
                    </div>
                    <NuxtLink
                      to="/dashboard/account"
                      role="menuitem"
                      class="flex items-center gap-2 px-3 py-2 text-sm text-zinc-200 transition hover:bg-zinc-900"
                    >
                      <svg class="h-4 w-4 text-zinc-500" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                        <path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd" />
                      </svg>
                      Account
                    </NuxtLink>
                    <NuxtLink
                      to="/dashboard/billing"
                      role="menuitem"
                      class="flex items-center gap-2 px-3 py-2 text-sm text-zinc-200 transition hover:bg-zinc-900"
                    >
                      <svg class="h-4 w-4 text-zinc-500" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                        <path d="M4 4a2 2 0 00-2 2v1h16V6a2 2 0 00-2-2H4zM18 9H2v5a2 2 0 002 2h12a2 2 0 002-2V9zM4 13a1 1 0 011-1h1a1 1 0 110 2H5a1 1 0 01-1-1zm5-1a1 1 0 100 2h1a1 1 0 100-2H9z" />
                      </svg>
                      Billing &amp; plan
                    </NuxtLink>
                    <button
                      type="button"
                      role="menuitem"
                      class="flex w-full items-center gap-2 border-t border-zinc-900 px-3 py-2 text-left text-sm text-zinc-200 transition hover:bg-zinc-900"
                      @click="signOut"
                    >
                      <svg class="h-4 w-4 text-zinc-500" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                        <path fill-rule="evenodd" d="M3 3a1 1 0 011-1h6a1 1 0 110 2H5v12h5a1 1 0 110 2H4a1 1 0 01-1-1V3zm12.293 4.293a1 1 0 011.414 0l3 3a1 1 0 010 1.414l-3 3a1 1 0 01-1.414-1.414L16.586 12H9a1 1 0 110-2h7.586l-1.293-1.293a1 1 0 010-1.414z" clip-rule="evenodd" />
                      </svg>
                      Sign out
                    </button>
                  </div>
                </Transition>
              </div>
            </template>
            <template v-else>
              <NuxtLink to="/login" class="px-3 py-1.5 transition hover:text-zinc-100">Sign in</NuxtLink>
              <NuxtLink to="/signup" class="btn-primary !px-3 !py-1.5 text-xs">Get started</NuxtLink>
            </template>
          </ClientOnly>
        </nav>
      </div>
    </header>

    <main class="mx-auto max-w-6xl px-6 py-8">
      <NuxtPage />
    </main>

    <!-- Global "plan limit reached" prompt — surfaces whenever any API
         call returns 402. Lives at app-root so every page benefits
         without per-page wiring. -->
    <UpgradeModal />

    <!-- Privacy / terms onboarding gate. Auto-shows when the signed-in
         user hasn't accepted the current policies yet. No-op otherwise. -->
    <TermsGateModal />

    <footer class="mt-16 border-t border-zinc-900">
      <div class="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3 px-6 py-6 text-xs text-zinc-500">
        <span>© 2025 GuestGuard — Hassle-free RSVPs for every occasion.</span>
        <span class="flex items-center gap-4">
          <NuxtLink to="/privacy" class="hover:text-zinc-300">Privacy</NuxtLink>
          <NuxtLink to="/terms" class="hover:text-zinc-300">Terms</NuxtLink>
        </span>
      </div>
    </footer>
  </div>
</template>
