<template>
  <div class="flex items-center justify-center min-h-screen">
    <div class="text-center max-w-md px-4">
      <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">
        Opening app...
      </h2>
      <p class="text-muted mb-4">
        Attempting to open the mobile app. If it doesn't open automatically, please click the button below.
      </p>

      <UButton
        v-if="appUrl"
        tag="a"
        :href="appUrl"
        color="primary"
        class="mb-3"
      >
        Open in App
      </UButton>

      <UButton
        tag="a"
        :href="webUrl"
        color="neutral"
        variant="outline"
      >
        Continue in Browser
      </UButton>
    </div>
  </div>
</template>

<script setup lang="ts">
/**
 * This page is used as a redirect from magic link emails
 * It attempts to open the app using a custom scheme
 * If that fails, it provides a fallback to continue in browser
 */

const route = useRoute()
const log = useLogger('Magic Link Redirect')

// Get the verification URL from query params
const verificationUrl = route.query.url as string
const webUrl = verificationUrl || '/auth'

// Create the app URL using App Links (HTTPS) instead of custom scheme
// This will be intercepted by Android if the app is installed
const baseUrl = verificationUrl ? new URL(verificationUrl).origin : 'https://harmonic-saas.vercel.app'
const appUrl = verificationUrl
  ? `${baseUrl}/app/open-magic-link?url=${encodeURIComponent(verificationUrl)}`
  : null

onMounted(() => {
  if (!appUrl) {
    // No URL provided, redirect to auth
    window.location.href = webUrl
    return
  }

  log.info('Attempting to open app with App Link:', appUrl)

  // Navigate to the App Link URL
  // If the app is installed, Android will intercept and open it
  // If not, the page will load in browser (we'll create a fallback page)
  setTimeout(() => {
    window.location.href = appUrl
  }, 500)
})
</script>
