import React, { useEffect, useState, useRef } from 'react'; import { View, Text, StyleSheet, KeyboardAvoidingView, Platform, ScrollView, TouchableOpacity, ActivityIndicator, } from 'react-native'; import { router, useLocalSearchParams } from 'expo-router'; import { Ionicons } from '@expo/vector-icons'; import { useAuth } from '@/contexts/AuthContext'; import { Button } from '@/components/ui/Button'; import { ErrorMessage } from '@/components/ui/ErrorMessage'; import { AppColors, FontSizes, Spacing } from '@/constants/theme'; export default function WelcomeBackScreen() { const { requestOtp, isLoading, error, clearError } = useAuth(); const params = useLocalSearchParams<{ email: string; name: string }>(); const email = params.email || ''; const name = params.name || ''; const [codeSent, setCodeSent] = useState(false); const [sendingOtp, setSendingOtp] = useState(false); const hasSentOtp = useRef(false); // Clear errors on mount useEffect(() => { clearError(); }, []); // Auto-send OTP on mount useEffect(() => { if (!email || hasSentOtp.current) return; const sendOtp = async () => { hasSentOtp.current = true; setSendingOtp(true); console.log('[WelcomeBack] Auto-sending OTP to:', email); const result = await requestOtp(email); console.log('[WelcomeBack] Result:', JSON.stringify(result)); setSendingOtp(false); if (result.success) { setCodeSent(true); } }; sendOtp(); }, [email]); const handleContinue = async () => { clearError(); if (!email) { router.replace('/(auth)/login'); return; } // If code wasn't sent, try sending first if (!codeSent) { setSendingOtp(true); const result = await requestOtp(email); setSendingOtp(false); if (!result.success) return; setCodeSent(true); } // Navigate to OTP verification console.log('[WelcomeBack] -> verify-otp'); router.push({ pathname: '/(auth)/verify-otp', params: { email, isNewUser: '0' } }); }; const handleBack = () => { router.replace('/(auth)/login'); }; const displayName = name || email.split('@')[0]; return ( Welcome back{displayName ? `, ${displayName}` : ''}! {sendingOtp ? ( Sending verification code... ) : codeSent ? ( We've sent a verification code to ) : ( We'll send a verification code to )} {email} {error && ( )}