<script setup lang="ts">
import type { AuthProvider } from '#auth'

definePageMeta({
  auth: false
})

const route = useRoute()
const { getCsrfToken, getProviders } = useAuth()

const csrfToken = ref('')
const provider = ref<AuthProvider | undefined>(undefined)
const error = ref('')
const loading = ref(true)

const callbackUrl = computed(() => (route.query.callbackUrl as string) || '/')

onMounted(async () => {
  try {
    const [providersData, tokenData] = await Promise.all([
      getProviders(),
      getCsrfToken()
    ])
    const token = tokenData || ''
    csrfToken.value = token
    provider.value = (providersData as Record<string, AuthProvider>)?.zitadel
  } catch (e: any) {
    error.value = e?.message || 'Failed to load authentication'
  } finally {
    loading.value = false
  }
})
</script>

<template>
  <div class="min-h-screen flex items-center justify-center" style="background: var(--page-bg);">
    <div class="w-full max-w-md p-8 rounded-xl border" style="background: var(--surface); border-color: var(--card-border);">
      <div class="text-center mb-8">
        <h1 class="text-2xl font-semibold" style="color: var(--text-primary);">
          Welcome to Segur-OS
        </h1>
        <p class="mt-2 text-sm" style="color: var(--text-muted);">
          Sign in to access your insurance management dashboard
        </p>
      </div>

      <template v-if="error">
        <div class="text-sm text-red-500 mb-4">{{ error }}</div>
      </template>

      <template v-else-if="provider">
        <form :action="provider.signinUrl" method="POST" class="space-y-4">
          <input type="hidden" name="csrfToken" :value="csrfToken" />
          <input type="hidden" name="callbackUrl" :value="callbackUrl" />
          <input type="hidden" name="provider" value="zitadel" />

          <button
            type="submit"
            class="w-full flex items-center justify-center gap-3 px-4 py-3 rounded-lg font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            style="background: var(--brand); color: white;"
          >
            <UIcon name="i-heroicons-lock-closed" class="h-5 w-5" />
            <span>Sign in with CorredorConect ID</span>
          </button>
        </form>
      </template>

      <template v-else-if="loading">
        <button
          type="button"
          disabled
          class="w-full flex items-center justify-center gap-3 px-4 py-3 rounded-lg font-medium"
          style="background: var(--brand); color: white; opacity: 0.5;"
        >
          <UIcon name="i-heroicons-arrow-path" class="h-5 w-5 animate-spin" />
          <span>Loading...</span>
        </button>
      </template>

      <div class="mt-6 text-center text-xs" style="color: var(--text-muted);">
        <p>Secure authentication powered by CorredorConect ID</p>
      </div>
    </div>
  </div>
</template>