<script setup lang="ts">
const { signInMagicLink } = useAuth()

const { t } = useI18n()
const localePath = useLocalePath()
const toast = useToast()

// Detect mobile
const apiBaseUrl = useApiBaseUrl()
const isCapacitor = computed(() => apiBaseUrl !== null && apiBaseUrl !== undefined && apiBaseUrl !== '')
const isMobile = computed(() => {
  if (isCapacitor.value) return true
  if (typeof window !== 'undefined') {
    return window.innerWidth < 768
  }
  return false
})

const email = ref('')
const loading = ref(false)
const emailSent = ref(false)

async function handleSubmit() {
  if (loading.value || !email.value) return

  loading.value = true
  try {
    await signInMagicLink({
      email: email.value,
      callbackURL: '/dashboard'
    })

    emailSent.value = true
    toast.add({
      title: t('auth.magicLink.emailSent'),
      description: t('auth.magicLink.checkInbox'),
      color: 'success'
    })
  } catch (error) {
    toast.add({
      title: t('auth.magicLink.error'),
      description: (error as Error).message || t('auth.magicLink.errorDescription'),
      color: 'error'
    })
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <NuxtLayout>
    <UContainer>
      <UPageBody>
        <AuthCard :title="t('auth.magicLink.title')">
          <template v-if="!emailSent">
            <!-- Mobile-optimized header -->
            <UAlert
              v-if="isMobile"
              :icon="useSolarIcon('shield-check')"
              color="success"
              variant="soft"
              :title="t('auth.magicLink.secure')"
              :description="t('auth.magicLink.secureDescription')"
              class="mb-6"
            />

            <p class="text-muted mb-4">
              {{ t('auth.magicLink.description') }}
            </p>
            <p class="text-muted text-xs mb-6">
              {{ t('auth.magicLink.description2') }}
            </p>

            <form
              class="flex flex-col gap-4"
              @submit.prevent="handleSubmit"
            >
              <UFormField
                :label="t('auth.email')"
                required
              >
                <UInput
                  v-model="email"
                  type="email"
                  :placeholder="t('auth.email')"
                  class="w-full"
                  :icon="useSolarIcon('letter')"
                  autofocus
                />
              </UFormField>

              <UButton
                type="submit"
                color="primary"
                :loading="loading"
                :disabled="!email || loading"
                block
                :icon="useSolarIcon('link')"
              >
                {{ t('auth.magicLink.sendLink') }}
              </UButton>

              <div class="text-center mt-4">
                <ULink
                  :to="localePath('/auth')"
                  class="text-sm text-muted hover:text-primary"
                >
                  {{ t('auth.magicLink.backToLogin') }}
                </ULink>
              </div>
            </form>
          </template>

          <template v-else>
            <div class="text-center py-6">
              <UIcon
                :name="useSolarIcon('inbox-in')"
                class="h-16 w-16 mx-auto mb-6 text-success"
              />
              <h2 class="text-2xl font-semibold mb-4">
                {{ t('auth.magicLink.emailSent') }}
              </h2>
              <p class="text-base mb-6">
                {{ t('auth.magicLink.checkInboxDescription', { email: email }) }}
              </p>

              <!-- Mobile-specific instructions -->
              <UAlert
                v-if="isMobile"
                :icon="useSolarIcon('smartphone')"
                color="info"
                variant="soft"
                :title="t('auth.magicLink.mobileInstructions')"
                :description="t('auth.magicLink.mobileInstructionsDescription')"
                class="mb-6 text-left"
              />

              <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 mb-6">
                <p class="text-sm text-muted mb-2">
                  <strong>{{ t('auth.magicLink.whatToDoNext') }}</strong>
                </p>
                <ol class="text-sm text-muted text-left space-y-2 ml-4 list-decimal">
                  <li>{{ t('auth.magicLink.step1') }}</li>
                  <li>{{ t('auth.magicLink.step2') }}</li>
                  <li>{{ t('auth.magicLink.step3') }}</li>
                </ol>
              </div>

              <p class="text-sm text-muted mb-6">
                {{ t('auth.magicLink.linkExpires') }}
              </p>

              <div class="flex flex-col gap-3">
                <UButton
                  color="primary"
                  :icon="useSolarIcon('refresh')"
                  @click="emailSent = false"
                >
                  {{ t('auth.magicLink.sendAnother') }}
                </UButton>
                <UButton
                  :to="localePath('/auth')"
                  color="neutral"
                  variant="outline"
                >
                  {{ t('auth.magicLink.backToLogin') }}
                </UButton>
              </div>
            </div>
          </template>
        </AuthCard>
      </UPageBody>
    </UContainer>
  </NuxtLayout>
</template>
