'use client'

import { useEffect, Suspense } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { useStore } from '@/lib/store'
import { Loader2 } from 'lucide-react'

function OAuthCallbackContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { checkAuth } = useStore()

  useEffect(() => {
    const sanitizeRedirect = (value: string | null): string => {
      const fallback = '/terminal/hunt'
      if (!value) return fallback
      const v = value.trim()
      if (!v.startsWith('/')) return fallback
      if (v.startsWith('//')) return fallback
      if (v.includes('://')) return fallback
      if (v.includes('\\')) return fallback
      return v
    }

    const addWelcomeFlag = (path: string): string => {
      try {
        const u = new URL(path, window.location.origin)
        u.searchParams.set('welcome', 'true')
        return `${u.pathname}${u.search}${u.hash}`
      } catch {
        return path
      }
    }

    const redirect = sanitizeRedirect(searchParams.get('redirect'))
    const isNew = searchParams.get('new') === 'true'
    const error = searchParams.get('error')

    if (error) {
      router.push(`/login?error=${encodeURIComponent(error)}`)
      return
    }

    // Auth cookie is set by backend during OAuth callback; just refresh auth state.
    checkAuth().finally(() => {
      router.push(isNew ? addWelcomeFlag(redirect) : redirect)
    })
  }, [searchParams, router, checkAuth])

  return (
    <div className="min-h-screen bg-background flex items-center justify-center">
      <div className="text-center">
        <div className="relative mb-6">
          <Loader2 className="w-12 h-12 text-accent animate-spin mx-auto" />
          <div className="absolute inset-0 bg-accent/20 blur-xl rounded-full" />
        </div>
        <h2 className="text-xl font-display text-foreground mb-2">Signing you in...</h2>
        <p className="text-sm text-foreground-muted">Please wait while we complete authentication</p>
      </div>
    </div>
  )
}

export default function OAuthCallbackPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen flex items-center justify-center bg-background">
        <Loader2 className="w-6 h-6 animate-spin text-accent" />
      </div>
    }>
      <OAuthCallbackContent />
    </Suspense>
  )
}

