/**
 * Deep Link Handler Plugin
 * Checks localStorage for pending deep links from push notifications
 * and navigates to them after the app is fully initialized
 *
 * This plugin only runs when enablePushNotifications is true in saas config
 */
export default defineNuxtPlugin(() => {
  const config = useRuntimeConfig()
  const log = useLogger('DeepLink')

  // Check if push notifications are enabled in saas config
  const saasConfig = config.public.saas as { enablePushNotifications?: boolean } | undefined
  if (!saasConfig?.enablePushNotifications) {
    return
  }

  log.info('Plugin initialized')

  const router = useRouter()

  // Create loading overlay element
  let loadingOverlay: HTMLDivElement | null = null

  const showLoading = () => {
    if (loadingOverlay) return

    loadingOverlay = document.createElement('div')
    loadingOverlay.id = 'deep-link-loading'
    loadingOverlay.innerHTML = `
      <div style="
        position: fixed;
        inset: 0;
        background: rgba(0, 0, 0, 0.7);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 99999;
      ">
        <div style="
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 16px;
          color: white;
        ">
          <div style="
            width: 48px;
            height: 48px;
            border: 4px solid rgba(255,255,255,0.3);
            border-top-color: white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
          "></div>
          <div style="font-size: 14px;">Opening...</div>
        </div>
      </div>
      <style>
        @keyframes spin {
          to { transform: rotate(360deg); }
        }
      </style>
    `
    document.body.appendChild(loadingOverlay)
    log.info('Showing loading overlay')
  }

  const hideLoading = () => {
    if (loadingOverlay) {
      loadingOverlay.remove()
      loadingOverlay = null
      log.info('Hiding loading overlay')
    }
  }

  const checkForDeepLink = () => {
    if (typeof localStorage === 'undefined') return false

    const pendingDeepLink = localStorage.getItem('pendingDeepLink')
    if (pendingDeepLink) {
      log.info('Found deep link:', pendingDeepLink)
      showLoading()
      localStorage.removeItem('pendingDeepLink')

      // Navigate and hide loading after a short delay
      router.push(pendingDeepLink).finally(() => {
        setTimeout(hideLoading, 300)
      })
      return true
    }
    return false
  }

  // Check immediately and at intervals
  // This handles both app launch and when notification is clicked while app is running
  checkForDeepLink()

  // Keep checking periodically for deep links set by Android
  const interval = setInterval(() => {
    checkForDeepLink()
  }, 1000)

  // Also check on visibility change (when app comes back to foreground)
  document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'visible') {
      log.info('App became visible, checking for deep link')
      setTimeout(() => checkForDeepLink(), 100)
    }
  })

  // Clean up after 30 seconds to avoid infinite polling
  setTimeout(() => {
    clearInterval(interval)
    log.info('Stopped periodic checking')
  }, 30000)

  // Safety timeout: hide loading if still showing after 5 seconds
  setTimeout(() => {
    if (loadingOverlay) {
      log.warn('Loading overlay timeout - hiding')
      hideLoading()
    }
  }, 5000)
})
