<template>
  <div class="min-h-full flex items-center justify-center py-16 px-4 sm:px-6 lg:px-8 bg-gray-50">
    <div class="max-w-md w-full space-y-8">
      <div class="text-center">
        <h2 class="text-3xl font-display font-bold text-gray-900">
          Mitglieder-Login
        </h2>
        <p class="mt-2 text-sm text-gray-600">
          Melden Sie sich an, um auf den Mitgliederbereich zuzugreifen
        </p>
      </div>

      <div class="bg-white rounded-xl shadow-lg p-8">
        <form
          class="space-y-6"
          @submit.prevent="handleLogin"
        >
          <!-- Email -->
          <div>
            <label
              for="email"
              class="block text-sm font-medium text-gray-700 mb-2"
            >
              E-Mail-Adresse
            </label>
            <input
              id="email"
              v-model="formData.email"
              type="email"
              required
              autocomplete="email"
              class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-600 focus:border-transparent transition-all"
              :class="{ 'border-red-500': errorMessage }"
              placeholder="ihre-email@example.com"
            >
          </div>

          <!-- Password -->
          <div>
            <label
              for="password"
              class="block text-sm font-medium text-gray-700 mb-2"
            >
              Passwort
            </label>
            <input
              id="password"
              v-model="formData.password"
              type="password"
              required
              autocomplete="current-password"
              class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-600 focus:border-transparent transition-all"
              :class="{ 'border-red-500': errorMessage }"
              placeholder="••••••••"
            >
          </div>

          <!-- Error Message -->
          <div
            v-if="errorMessage"
            class="bg-red-50 border border-red-200 rounded-lg p-4"
          >
            <p class="text-sm text-red-800 flex items-center">
              <AlertCircle
                :size="18"
                class="mr-2"
              />
              {{ errorMessage }}
            </p>
          </div>

          <!-- Success Message -->
          <div
            v-if="successMessage"
            class="bg-green-50 border border-green-200 rounded-lg p-4"
          >
            <p class="text-sm text-green-800 flex items-center">
              <Check
                :size="18"
                class="mr-2"
              />
              {{ successMessage }}
            </p>
          </div>

          <!-- Submit Button -->
          <button
            type="submit"
            :disabled="isLoading || passkeyLoading"
            class="w-full px-6 py-3 bg-primary-600 hover:bg-primary-700 disabled:bg-gray-400 text-white font-semibold rounded-lg transition-colors flex items-center justify-center"
          >
            <Loader2
              v-if="isLoading"
              :size="20"
              class="mr-2 animate-spin"
            />
            <span>{{ isLoading ? 'Anmeldung läuft...' : 'Anmelden' }}</span>
          </button>

          <button
            type="button"
            :disabled="isLoading || passkeyLoading || !isPasskeySupported"
            class="w-full px-6 py-3 border border-gray-300 bg-white hover:bg-gray-50 disabled:bg-gray-100 disabled:text-gray-400 text-gray-800 font-semibold rounded-lg transition-colors flex items-center justify-center"
            @click="handlePasskeyLogin"
          >
            <Loader2
              v-if="passkeyLoading"
              :size="20"
              class="mr-2 animate-spin"
            />
            <Lock
              v-else
              :size="18"
              class="mr-2"
            />
            <span>{{ passkeyLoading ? 'Passkey-Anmeldung läuft...' : 'Mit Passkey anmelden' }}</span>
          </button>

          <p class="text-xs text-gray-500 text-center">
            Falls kein lokaler Passkey verfügbar ist: Smartphone oder USB-Sicherheitsschlüssel verwenden.
          </p>

          <p
            v-if="!isPasskeySupported"
            class="text-xs text-gray-500 text-center"
          >
            {{ passkeySupportReason || 'Passkeys sind in diesem Browser aktuell nicht verfügbar.' }}
          </p>

          <!-- Forgot Password Link -->
          <div class="text-center">
            <NuxtLink
              to="/passwort-vergessen"
              class="text-sm text-primary-600 hover:text-primary-700 font-medium"
            >
              Passwort vergessen?
            </NuxtLink>
          </div>
        </form>
      </div>

      <!-- Info Box -->
      <div class="bg-primary-50 border border-primary-100 rounded-lg p-4">
        <p class="text-sm text-primary-800 text-center">
          <Lock
            :size="16"
            class="inline mr-1"
          />
          Nur für Vereinsmitglieder. Kein Zugang? Kontaktieren Sie den Vorstand.
        </p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { AlertCircle, Check, Loader2, Lock } from 'lucide-vue-next'

const router = useRouter()
const authStore = useAuthStore()

const formData = ref({
  email: '',
  password: ''
})

const isLoading = ref(false)
const passkeyLoading = ref(false)
const errorMessage = ref('')
const successMessage = ref('')
const isPasskeySupported = ref(false)
const passkeySupportReason = ref('')

onMounted(() => {
  const hasPublicKeyCredential = typeof window !== 'undefined' && typeof window.PublicKeyCredential !== 'undefined'
  const secureContext = typeof window !== 'undefined' && !!window.isSecureContext

  isPasskeySupported.value = !!(hasPublicKeyCredential && secureContext)

  if (!secureContext) {
    passkeySupportReason.value = 'Passkeys benötigen HTTPS (oder localhost).'
  } else if (!hasPublicKeyCredential) {
    passkeySupportReason.value = 'Dieser Browser unterstützt WebAuthn/Passkeys nicht.'
  } else {
    passkeySupportReason.value = ''
  }
})

const handleLogin = async () => {
  isLoading.value = true
  errorMessage.value = ''
  successMessage.value = ''

  try {
    const response = await authStore.login(formData.value.email, formData.value.password)

    if (response.success) {
      successMessage.value = 'Anmeldung erfolgreich! Sie werden weitergeleitet...'
      
      // Redirect based on role
      setTimeout(() => {
        const roles = response.user.roles || (response.user.role ? [response.user.role] : [])
        if (roles.includes('trainer')) {
          router.push('/cms/kontaktanfragen')
        } else if (roles.includes('admin') || roles.includes('vorstand') || roles.includes('newsletter')) {
          router.push('/cms')
        } else {
          router.push('/mitgliederbereich')
        }
      }, 1000)
    }
  } catch (error) {
    errorMessage.value = error.data?.message || 'Anmeldung fehlgeschlagen. Bitte prüfen Sie Ihre Zugangsdaten.'
  } finally {
    isLoading.value = false
  }
}

const handlePasskeyLogin = async () => {
  passkeyLoading.value = true
  errorMessage.value = ''
  successMessage.value = ''

  try {
    const response = await authStore.passkeyLogin(formData.value.email)

    if (response.success) {
      successMessage.value = 'Passkey-Anmeldung erfolgreich! Sie werden weitergeleitet...'

      setTimeout(() => {
        const roles = response.user.roles || (response.user.role ? [response.user.role] : [])
        if (roles.includes('trainer')) {
          router.push('/cms/kontaktanfragen')
        } else if (roles.includes('admin') || roles.includes('vorstand') || roles.includes('newsletter')) {
          router.push('/cms')
        } else {
          router.push('/mitgliederbereich')
        }
      }, 1000)
    }
  } catch (error) {
    const message = error?.data?.message || error?.message || 'Passkey-Anmeldung fehlgeschlagen.'
    errorMessage.value = message
  } finally {
    passkeyLoading.value = false
  }
}

definePageMeta({
  layout: 'default'
})

useHead({
  title: 'Login - Harheimer TC',
})
</script>

