<template>
  <div class="flex items-center justify-center min-h-screen">
    <div class="text-center">
      <UIcon
        name="i-heroicons-arrow-path"
        class="w-10 h-10 animate-spin mx-auto mb-4 text-primary"
      />
      <h2 class="text-xl font-semibold mb-2">
        {{ t('auth.magicLink.verifying') }}
      </h2>
      <p class="text-muted">
        {{ t('auth.magicLink.pleaseWait') }}
      </p>
      <p class="text-xs text-muted mt-4">
        If you're not redirected automatically,
        <a
          :href="returnUrl"
          class="text-primary underline"
        >click here</a>.
      </p>
    </div>
  </div>
</template>

<script setup lang="ts">
/**
 * This page is reached after Better Auth verifies the magic link
 * in Capacitor, we navigate the WebView to the backend for verification
 * After verification, the backend redirects here
 * This page extracts the session cookie and redirects back to the app
 */

const { t } = useI18n()
const router = useRouter()
const log = useLogger('Magic Link Callback')

// Always redirect to the return page
// In Capacitor, bounce back to the app's local origin so we can read cookies via CapacitorCookies
// In browser, stay on current origin
const returnUrl = computed(() => {
  if (typeof window !== 'undefined') {
    try {
      // Lazy import to avoid SSR issues
      // eslint-disable-next-line @typescript-eslint/no-require-imports
      const { Capacitor } = require('@capacitor/core') as typeof import('@capacitor/core')
      const isNative = Capacitor?.isNativePlatform?.() || false
      if (isNative) {
        const platform = Capacitor.getPlatform()
        const localOrigin = platform === 'ios' ? 'capacitor://localhost' : 'https://localhost'
        return `${localOrigin}/app/return-from-magic-link`
      }
    } catch {
      // Ignore Capacitor import errors
    }
    return `${window.location.origin}/app/return-from-magic-link`
  }
  return '/app/return-from-magic-link'
})

onMounted(async () => {
  log.info('Page mounted')
  log.info('Current location:', window.location.href)

  try {
    // Attempt to export the session token from the same-origin (Vercel) cookie
    const res = await fetch('/api/auth/export-token', { credentials: 'include' })
    if (res.ok) {
      const data = await res.json() as { token?: string }
      if (data?.token) {
        log.info('Exported session token, redirecting to app with token')
        // Compute local origin for Capacitor (Android/iOS) or fallback to current origin
        let localOrigin = typeof window !== 'undefined' ? window.location.origin : ''
        try {
          // eslint-disable-next-line @typescript-eslint/no-require-imports
          const { Capacitor } = require('@capacitor/core') as typeof import('@capacitor/core')
          if (Capacitor?.isNativePlatform?.()) {
            const platform = Capacitor.getPlatform()
            localOrigin = platform === 'ios' ? 'capacitor://localhost' : 'https://localhost'
          }
        } catch {
          // Ignore Capacitor import errors
        }

        const target = `${localOrigin}/app/return-from-magic-link?token=${encodeURIComponent(data.token)}`
        window.location.replace(target)
        return
      }
    }
  } catch (e) {
    log.warn('Failed to export session token', e)
  }

  log.info('Fallback redirect to:', returnUrl.value)
  await router.replace(returnUrl.value)
})
</script>
