"use client"; import { useEffect, useState } from "react"; import { useRouter, useSearchParams } from "next/navigation"; import { Alert, AlertDescription } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import { useMutation } from "@tanstack/react-query"; import { CheckCircle, Loader2, XCircle } from "lucide-react"; import { useTRPC } from "@karakeep/shared-react/trpc"; import { isMobileAppRedirect, validateRedirectUrl, } from "@karakeep/shared/utils/redirectUrl"; export default function VerifyEmailPage() { const api = useTRPC(); const searchParams = useSearchParams(); const router = useRouter(); const [status, setStatus] = useState<"loading" | "success" | "error">( "loading", ); const [message, setMessage] = useState(""); const token = searchParams.get("token"); const email = searchParams.get("email"); const redirectUrl = validateRedirectUrl(searchParams.get("redirectUrl")) ?? "/"; const verifyEmailMutation = useMutation( api.users.verifyEmail.mutationOptions({ onSuccess: () => { setStatus("success"); if (isMobileAppRedirect(redirectUrl)) { setMessage( "Your email has been successfully verified! Redirecting to the app...", ); // Redirect to mobile app after a brief delay setTimeout(() => { window.location.href = redirectUrl; }, 1500); } else { setMessage( "Your email has been successfully verified! You can now sign in.", ); } }, onError: (error) => { setStatus("error"); setMessage( error.message || "Failed to verify email. The link may be invalid or expired.", ); }, }), ); const resendEmailMutation = useMutation( api.users.resendVerificationEmail.mutationOptions({ onSuccess: () => { setMessage( "A new verification email has been sent to your email address.", ); }, onError: (error) => { setMessage(error.message || "Failed to resend verification email."); }, }), ); const isMobileRedirect = isMobileAppRedirect(redirectUrl); useEffect(() => { if (token && email) { verifyEmailMutation.mutate({ token, email }); } else { setStatus("error"); setMessage("Invalid verification link. Missing token or email."); } }, [token, email]); const handleResendEmail = () => { if (email) { resendEmailMutation.mutate({ email, redirectUrl }); } }; const handleSignIn = () => { if (isMobileRedirect) { window.location.href = redirectUrl; } else if (redirectUrl !== "/") { router.push(`/signin?redirectUrl=${encodeURIComponent(redirectUrl)}`); } else { router.push("/signin"); } }; return (