<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { RouterLink, useRoute } from 'vue-router'
import { Star } from '@lucide/vue'

import Button from './ui/Button.vue'
import { useAuthStore } from '../stores/auth'
import { usePhases } from '../composables/usePhases'

const route = useRoute()
const authStore = useAuthStore()
const { infoForPhaseKey } = usePhases()
const loginOpen = ref(false)
const loginError = ref('')
const loginForm = reactive({
  twitchUserId: 'jayuhime_demo',
  displayName: 'Jayuhime',
  role: 'viewer' as 'viewer' | 'admin',
})

const navItems = [
  { label: 'Home', to: '/' },
  { label: 'Nominierung', to: '/nominations', requiresAuth: true, phase: 'nomination' },
  { label: 'Voting', to: '/voting', requiresAuth: true, phase: 'voting' },
  { label: 'Clips', to: '/clips', requiresAuth: true, phase: 'nomination' },
  { label: 'Gewinner', to: '/winners' },
  { label: 'Admin', to: '/admin' },
]

const currentLabel = computed(
  () => navItems.find((item) => route.path === item.to || route.path.startsWith(`${item.to}/`))?.label ?? 'Awards',
)

const visibleNavItems = computed(() =>
  navItems.filter((item) => {
    if (item.to === '/admin') return authStore.isAdmin
    // Teilnahme-Seiten erst nach Login zeigen
    if (item.requiresAuth && !authStore.isLoggedIn) return false
    // ... und nur, solange ihre Phase aktiv ist
    if (item.phase && infoForPhaseKey(item.phase).state !== 'active') return false
    return true
  }),
)

async function login(role: 'viewer' | 'admin') {
  loginError.value = ''
  loginForm.role = role

  try {
    await authStore.login(loginForm)
    loginOpen.value = false
  } catch (error) {
    loginError.value = error instanceof Error ? error.message : 'Login fehlgeschlagen.'
  }
}
</script>

<template>
  <div class="min-h-screen overflow-x-hidden bg-[linear-gradient(180deg,#fffdf9_0%,#fff6ee_38%,#fff9f4_100%)] text-slate-800">
    <div class="pointer-events-none absolute inset-x-0 top-0 h-[520px] bg-[radial-gradient(circle_at_top_left,_rgba(237,214,167,0.38),transparent_34%),radial-gradient(circle_at_top_right,_rgba(210,195,255,0.32),transparent_28%)]" />
    <div class="pointer-events-none absolute left-1/2 top-36 h-[560px] w-[560px] -translate-x-1/2 rounded-full border border-white/70 opacity-70 blur-3xl" />

    <div class="relative mx-auto w-full max-w-[1460px] px-4 py-4 sm:px-6 lg:px-10">
      <div class="mb-5 flex items-center justify-between border-b border-black/8 px-2 pb-3 text-[11px] uppercase tracking-[0.34em] text-slate-500">
        <span>VTuber Star Awards 2026</span>
        <span>{{ currentLabel }}</span>
      </div>

      <header
        class="mb-10 flex flex-col gap-6 rounded-[24px] border border-white/70 bg-white/72 px-5 py-5 shadow-[0_18px_55px_rgba(93,63,135,0.08)] backdrop-blur lg:px-7"
      >
        <div class="flex flex-col gap-5 lg:flex-row lg:items-center lg:justify-between">
          <RouterLink to="/" class="flex items-center gap-4 text-slate-800 no-underline">
            <div
              class="grid h-12 w-12 place-items-center rounded-[1.1rem] bg-[linear-gradient(135deg,#f6e3b2,#f5c877)] text-amber-950 shadow-[0_16px_28px_rgba(245,200,119,0.35)]"
            >
              <Star class="h-5 w-5" />
            </div>
            <div>
              <strong class="block text-sm tracking-[0.35em]">VTUBER</strong>
              <span class="block text-[11px] tracking-[0.45em] text-slate-500">STAR AWARDS</span>
            </div>
          </RouterLink>

          <div class="flex flex-wrap items-center gap-3">
            <template v-if="authStore.session">
              <div class="rounded-full border border-violet-100 bg-violet-50/70 px-4 py-2 text-sm text-violet-800">
                {{ authStore.session.displayName }} · {{ authStore.session.role }}
              </div>
              <Button variant="ghost" @click="authStore.logout()">Abmelden</Button>
            </template>
            <template v-else>
              <Button variant="ghost" @click="loginOpen = !loginOpen">Einloggen</Button>
              <Button class="gap-2" @click="login('viewer')">
                <svg class="h-4 w-4 fill-current" viewBox="0 0 16 16"><path d="M2.5 0 0 2.5v11h3.5V16h2l2.5-2.5h3l5-5V0H2.5Zm12 8L12 10.5H8.5L6 13v-2.5H2.5V2h12v6Z"/><path d="M11.5 4h1.5v3.5h-1.5V4Zm-3.5 0h1.5v3.5H8V4Z"/></svg>
                Anmelden mit Twitch
              </Button>
            </template>
          </div>
        </div>

        <div v-if="loginOpen && !authStore.session" class="rounded-[28px] border border-violet-100 bg-white/80 p-5">
          <div class="grid gap-4 md:grid-cols-3">
            <input v-model="loginForm.displayName" type="text" class="rounded-2xl border border-violet-200 px-4 py-3" placeholder="Anzeigename" />
            <input v-model="loginForm.twitchUserId" type="text" class="rounded-2xl border border-violet-200 px-4 py-3" placeholder="Twitch Nutzer-ID" />
            <div class="flex flex-wrap gap-3">
              <Button :disabled="authStore.loading" @click="login('viewer')">
                {{ authStore.loading ? 'Loggt ein ...' : 'Viewer-Login' }}
              </Button>
              <Button variant="secondary" :disabled="authStore.loading" @click="login('admin')">Admin-Login</Button>
            </div>
          </div>
          <p v-if="loginError" class="mt-3 text-sm text-rose-700">{{ loginError }}</p>
        </div>

        <div class="flex flex-col gap-3 border-t border-black/6 pt-3 lg:flex-row lg:items-center lg:justify-between">
          <nav class="flex flex-wrap items-center gap-1 rounded-full border border-violet-100/80 bg-violet-50/50 p-1.5 text-sm font-medium text-slate-500">
            <RouterLink
              v-for="item in visibleNavItems"
              :key="item.to"
              :to="item.to"
              class="rounded-full px-4 py-2 transition"
              :class="route.path === item.to || route.path.startsWith(`${item.to}/`)
                ? 'bg-white text-violet-800 shadow-[0_4px_14px_rgba(124,92,255,0.18)] ring-1 ring-violet-100'
                : 'hover:bg-white/60 hover:text-violet-700'"
            >
              {{ item.label }}
            </RouterLink>
          </nav>

          <div class="flex items-center gap-3 text-xs uppercase tracking-[0.24em] text-slate-500">
            <span class="inline-flex h-2 w-2 rounded-full bg-emerald-500" />
            Community Voting live
          </div>
        </div>
      </header>

      <slot />
    </div>
  </div>
</template>
