<script setup lang="ts">
definePageMeta({ middleware: ['auth'] })

interface EventSummary {
  id: string
  name: string
  slug: string
  event_date: string
  status: string
  venue: string
  max_capacity: number
}

interface EventsResponse {
  events: EventSummary[]
}

const auth = useAuth()

const events = ref<EventSummary[]>([])
const loadingEvents = ref(false)
const loadError = ref<string | null>(null)

async function loadEvents() {
  if (!auth.user.value) return
  loadingEvents.value = true
  loadError.value = null
  try {
    // host is derived server-side from the session — no query param needed.
    const res = await useApi<EventsResponse>('/events')
    events.value = res.events
  } catch (e: any) {
    loadError.value = e?.data?.error || e?.message || 'Failed to load events'
  } finally {
    loadingEvents.value = false
  }
}

watch(() => auth.user.value, loadEvents, { immediate: true })

function fmtDate(iso: string) {
  try { return new Date(iso).toLocaleString() } catch { return iso }
}
</script>

<template>
  <section>
    <ClientOnly>
      <div v-if="!auth.bootstrapped.value || !auth.user.value" class="text-sm text-zinc-500">
        Loading dashboard…
      </div>

      <div v-else>
        <div class="mb-6 flex items-center justify-between">
          <div>
            <h1 class="text-2xl font-semibold">Your events</h1>
            <p class="text-sm text-zinc-400">Signed in as {{ auth.user.value.name }} ({{ auth.user.value.email }})</p>
          </div>
          <NuxtLink to="/dashboard/events/new" class="btn-primary">New event</NuxtLink>
        </div>

        <div v-if="loadingEvents" class="text-sm text-zinc-500">Loading…</div>
        <div v-else-if="loadError" class="card text-sm text-red-400">{{ loadError }}</div>
        <div v-else-if="events.length === 0" class="card text-sm text-zinc-400">
          No events yet. Create one to get started.
        </div>
        <div v-else class="grid gap-4 md:grid-cols-2">
          <NuxtLink
            v-for="ev in events"
            :key="ev.id"
            :to="`/dashboard/events/${ev.id}`"
            class="card transition hover:border-brand-700 hover:bg-zinc-900/80"
          >
            <div class="mb-1 flex items-center justify-between">
              <h2 class="font-semibold text-zinc-50">{{ ev.name }}</h2>
              <span class="text-xs uppercase tracking-wide text-zinc-500">{{ ev.status }}</span>
            </div>
            <p class="text-sm text-zinc-400">{{ ev.venue || '—' }}</p>
            <p class="mt-2 text-xs text-zinc-500">{{ fmtDate(ev.event_date) }}</p>
          </NuxtLink>
        </div>
      </div>

      <template #fallback>
        <div class="text-sm text-zinc-500">Loading dashboard…</div>
      </template>
    </ClientOnly>
  </section>
</template>
