<template>
  <div class="flex items-center justify-center min-h-screen">
    <div class="text-center">
      <UIcon
        name="i-heroicons-arrow-path"
        class="w-12 h-12 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>
    </div>
  </div>
</template>

<script setup lang="ts">
/**
 * This page is loaded after magic link verification
 * It extracts the session cookie and redirects to dashboard
 */

const { t } = useI18n()
const router = useRouter()
const route = useRoute()
const localePath = useLocalePath()
const apiBaseUrl = useApiBaseUrl()
const log = useLogger('Return from Magic Link')

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

  // Check if we're in Capacitor
  const isCapacitor = apiBaseUrl !== null && apiBaseUrl !== undefined && apiBaseUrl !== ''

  // If a token was passed in, store it directly (preferred path)
  const tokenFromQuery = route.query.token as string | undefined
  if (tokenFromQuery) {
    try {
      localStorage.setItem('better-auth-token', tokenFromQuery)
      log.info('Token from query stored, navigating to dashboard')
      // Proactively fetch session (retry to avoid race with DB commit/replication)
      try {
        const { fetchSession, loggedIn } = useAuth()
        for (let attempt = 0; attempt < 3; attempt++) {
          await fetchSession()
          if (loggedIn.value) break
          await new Promise(r => setTimeout(r, 300))
        }
      } catch {
        // Ignore session fetch errors
      }
      await router.push(localePath('/dashboard'))
      return
    } catch (e) {
      log.warn('Failed storing query token', e)
    }
  }

  if (isCapacitor) {
    log.info('Running in Capacitor')
    // Extract cookies and redirect
    log.info('Extracting cookies...')

    try {
      // Extract the session cookie from the backend domain
      log.info('Extracting session cookie...')
      const { CapacitorCookies } = await import('@capacitor/core')
      const cookies = await CapacitorCookies.getCookies({ url: apiBaseUrl })

      const cookieKeys = Object.keys(cookies)
      log.info('Cookies from backend:', cookieKeys)

      const candidateKey = cookieKeys.find(k => k.includes('better') && k.includes('session'))
        || cookieKeys.find(k => k.includes('session'))
      const sessionToken = candidateKey ? cookies[candidateKey] : undefined
      if (sessionToken) {
        log.info('Session token found:', sessionToken.substring(0, 20) + '...')
        localStorage.setItem('better-auth-token', sessionToken)
        log.info('Bearer token stored')
      } else {
        log.warn('No session token found')
        log.warn('Available cookies:', Object.keys(cookies))
      }

      // Wait a moment
      await new Promise(resolve => setTimeout(resolve, 500))

      // Navigate to dashboard
      log.info('Navigating to dashboard...')
      await router.push(localePath('/dashboard'))
    } catch (error) {
      log.error('Error extracting cookie:', error)
      await router.push(localePath('/auth'))
    }
  } else {
    // Not in Capacitor, just redirect normally
    log.info('Not in Capacitor, redirecting to dashboard')
    await router.push(localePath('/dashboard'))
  }
})
</script>
