"use client"

import { useEffect, Suspense } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { applySessionToStore } from "@/lib/auth/session-sync"

function AuthCompleteInner() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const returnTo = searchParams.get("returnTo") ?? "/mail/inbox"
  const accountNotice = searchParams.get("accountNotice")

  useEffect(() => {
    let cancelled = false

    async function finish() {
      try {
        const res = await fetch("/api/auth/session", { credentials: "include" })
        const data = (await res.json()) as {
          authenticated?: boolean
          accessToken?: string
          refreshToken?: string | null
          expiresAt?: number
          user?: { sub: string; email: string; name: string } | null
        }
        if (applySessionToStore(data) && !cancelled) {
          if (accountNotice === "same") {
            sessionStorage.setItem("ulti_account_notice", "same")
          }
          router.replace(returnTo.startsWith("/") ? returnTo : "/mail/inbox")
          return
        }
      } catch {
        // fall through
      }
      if (!cancelled) {
        router.replace("/login?error=session_failed")
      }
    }

    void finish()
    return () => {
      cancelled = true
    }
  }, [accountNotice, returnTo, router])

  return null
}

export default function AuthCompletePage() {
  return (
    <Suspense fallback={null}>
      <AuthCompleteInner />
    </Suspense>
  )
}
