import { useEffect } from "react"
import { useNavigate } from "react-router"

import { SignupForm } from "@crema/arcadia-auth-ui"
import { useBrand } from "~/lib/identity"
import { pageTitle } from "~/lib/page-meta"
import { persistFromArcadiaLogin, useSession } from "~/lib/session"
import { AuthBrand, AuthShell } from "~/components/auth/auth-shell"

export const meta = () => pageTitle("Create account")

export default function SignupRoute() {
  const navigate = useNavigate()
  const session = useSession()
  const brand = useBrand()

  useEffect(() => {
    if (session) navigate("/", { replace: true })
  }, [session, navigate])

  return (
    <AuthShell>
      <SignupForm
        brand={<AuthBrand />}
        heading={`Join ${brand.name}`}
        onSignin={() => navigate("/login")}
        onSuccess={async ({ tokens, user, emailVerificationSent }) => {
          if (tokens) {
            persistFromArcadiaLogin(tokens, user)
            navigate("/", { replace: true })
            return
          }
          // No tokens returned — verification email gating. Bounce to login.
          navigate(
            emailVerificationSent
              ? "/login?verify=sent"
              : "/login",
            { replace: true },
          )
        }}
      />
    </AuthShell>
  )
}
