import { OnboardingData } from "@/pages/Onboarding"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import { Badge } from "@/components/ui/badge"; import { CheckCircle, ArrowRight, Sparkles, ShieldCheck, MailCheck, MailWarning, Loader2, } from "lucide-react"; import { Link } from "react-router-dom"; import { useEffect, useState, useRef } from "react"; import type { AethexAchievement } from "@/lib/aethex-database-adapter"; import { useAuth } from "@/contexts/AuthContext"; import { supabase } from "@/lib/supabase"; import { useAethexToast } from "@/hooks/use-aethex-toast"; interface WelcomeProps { data: OnboardingData; onFinish?: () => void; isFinishing?: boolean; achievement?: AethexAchievement; } export default function Welcome({ data, onFinish, isFinishing, achievement, }: WelcomeProps) { const { user, refreshProfile } = useAuth(); const { success: toastSuccess, error: toastError, warning: toastWarning, info: toastInfo, } = useAethexToast(); const emailAddress = data.personalInfo.email || user?.email || ""; const deriveConfirmed = (source?: any) => Boolean(source?.email_confirmed_at || source?.confirmed_at); const [isVerified, setIsVerified] = useState(() => deriveConfirmed(user), ); const [isCheckingVerification, setIsCheckingVerification] = useState(false); const fullNameValue = `${(data.personalInfo.firstName || "").trim()} ${(data.personalInfo.lastName || "").trim()}`.trim() || ((user as any)?.user_metadata?.full_name as string | undefined); useEffect(() => { const confirmed = deriveConfirmed(user); setIsVerified(confirmed); }, [user]); const handleCheckVerification = async () => { setIsCheckingVerification(true); try { const { data: authData, error } = await supabase.auth.getUser(); if (error) throw error; const confirmed = deriveConfirmed(authData?.user); if (confirmed) { setIsVerified(true); toastSuccess({ title: "Email verified", description: "You're all set. You can sign in with this email.", }); try { await refreshProfile(); } catch (refreshError) { console.warn( "Unable to refresh profile after verification", refreshError, ); } } else { toastInfo({ title: "Verification pending", description: "We still don't see the confirmation. Check your inbox or resend the email.", }); } } catch (error: any) { console.error("Check verification failed", error); // If the client has no active session (common in signup flows), fall back // to a server-side check using the admin Supabase client. const isSessionMissing = (error && ((error.name && error.name.includes("AuthSessionMissing")) || (error.message && error.message.includes("Auth session missing")))) || false; if (isSessionMissing && emailAddress) { try { const resp = await fetch("/api/auth/check-verification", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: emailAddress }), }); const payload = await resp.json().catch(() => ({}) as any); if (!resp.ok) { const serverMessage = payload?.error || payload?.message || (Object.keys(payload || {}).length ? JSON.stringify(payload) : "Server check failed"); console.error("Server check-verification failed:", serverMessage); toastError({ title: "Unable to verify", description: serverMessage, }); } else { const confirmed = Boolean(payload?.verified); if (confirmed) { setIsVerified(true); toastSuccess({ title: "Email verified", description: "You're all set. You can sign in with this email.", }); try { await refreshProfile(); } catch (refreshError) { console.warn( "Unable to refresh profile after verification", refreshError, ); } } else { toastInfo({ title: "Verification pending", description: "We still don't see the confirmation. Check your inbox or resend the email.", }); // If the server returned a verification link (manual fallback), surface it. if ( payload?.user && payload?.user?.email && payload?.user?.confirmation_sent_at && !payload?.verified ) { // nothing specific to do here other than logging console.debug("User found but not verified", payload.user); } } } } catch (e: any) { console.error("Server-side check failed", e); toastError({ title: "Unable to verify", description: e?.message || "Server verification failed", }); } finally { setIsCheckingVerification(false); } return; } toastError({ title: "Unable to verify", description: error?.message || "We couldn't confirm your email status yet.", }); } finally { setIsCheckingVerification(false); } }; const VerificationIcon = isVerified ? MailCheck : MailWarning; const verificationBorderClass = isVerified ? "border-emerald-500/40" : "border-amber-500/40"; const verificationIconBg = isVerified ? "bg-emerald-500 text-white" : "bg-amber-500 text-white"; const verificationBadgeClass = isVerified ? "bg-emerald-500/20 text-emerald-100 border border-emerald-500/40" : "bg-amber-500/20 text-amber-100 border border-amber-500/40"; const verificationDescriptionClass = isVerified ? "text-emerald-100/80" : "text-amber-100/80"; const getUserTypeLabel = () => { switch (data.userType) { case "game-developer": return "Game Development"; case "client": return "Consulting"; case "member": return "Community"; case "customer": return "Get Started"; default: return "User"; } }; const getNextSteps = () => { switch (data.userType) { case "game-developer": return [ { title: "Access Development Tools", description: "Get started with our development toolkit and resources", }, { title: "Join Mentorship Program", description: "Connect with experienced developers for guidance", }, { title: "Explore Projects", description: "Browse collaborative projects and opportunities", }, { title: "Attend Workshops", description: "Join our next technical workshop or boot camp", }, ]; case "client": return [ { title: "Schedule Consultation", description: "Book a free consultation to discuss your project", }, { title: "View Our Portfolio", description: "Explore our previous work and case studies", }, { title: "Get Project Quote", description: "Receive a detailed quote for your development needs", }, { title: "Meet Your Team", description: "Connect with our development specialists", }, ]; case "member": return [ { title: "Explore Research", description: "Access our latest research and publications", }, { title: "Join Community", description: "Connect with other members in our forums", }, { title: "Upcoming Events", description: "Register for community events and workshops", }, { title: "Innovation Labs", description: "Participate in cutting-edge research projects", }, ]; case "customer": return [ { title: "Browse Products", description: "Explore our games, tools, and digital products", }, { title: "Join Beta Programs", description: "Get early access to new releases and features", }, { title: "Community Hub", description: "Connect with other users and share feedback", }, { title: "Support Center", description: "Access documentation and customer support", }, ]; default: return []; } }; const nextSteps = getNextSteps(); return (

Welcome to AeThex, {data.personalInfo.firstName}!

Your {getUserTypeLabel().toLowerCase()} account has been successfully set up

{/* User Summary */} Your AeThex Profile
Role:

{getUserTypeLabel()}

Experience:

{data.experience.level}

Skills:

{data.experience.skills.slice(0, 3).join(", ")} {data.experience.skills.length > 3 ? "..." : ""}

Primary Goals:

{data.interests.primaryGoals.length} selected

{/* Email Verification Reminder */}
{isVerified ? "Email verified" : "Verify your email to continue"} {isVerified ? `You're verified with ${emailAddress || "your email address"}.` : `Confirm ${emailAddress || "your email"} so you can sign back in after onboarding.`}
{isVerified ? "Verified" : "Action required"}
{isVerified ? (

You're good to go. Keep this email handy for account recovery and notifications.

) : ( <>

Check your inbox for the AeThex confirmation email we sent during sign-up. Click the verification link in that email to confirm your account.

  • Check your email inbox and spam folder.
  • The confirmation email is from support@aethex.tech
  • Once verified, click the button below to continue.
)}
{/* Achievement Badge */} {achievement && (
{achievement.icon || "🎖️"}
Achievement Unlocked {achievement.name}
AeThex Passport
{achievement.description &&

{achievement.description}

} {typeof achievement.xp_reward === "number" && achievement.xp_reward > 0 && (
+{achievement.xp_reward} XP added to your passport progression
)}
Profile Verified Passport Updated
)} {/* Next Steps */}

What's Next?

{nextSteps.map((step, index) => ( {step.title} {step.description} ))}
{/* Action Buttons */}

Need help getting started?{" "} Contact our support team

); }