import React, { useState, useEffect, useRef } from 'react'; import { View, Text, StyleSheet, KeyboardAvoidingView, Platform, ScrollView, TouchableOpacity, Modal, TextInput, 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, BorderRadius, FontSizes, Spacing } from '@/constants/theme'; export default function VerifyEmailScreen() { const { requestOtp, isLoading, error, clearError } = useAuth(); const params = useLocalSearchParams<{ email: string }>(); const email = params.email || ''; // Invite code state const [inviteCode, setInviteCode] = useState(''); const [inviteModalVisible, setInviteModalVisible] = useState(false); const [tempInviteCode, setTempInviteCode] = useState(''); // OTP sending state 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('[VerifyEmail] Auto-sending OTP to:', email); const result = await requestOtp(email); console.log('[VerifyEmail] 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 for new user console.log('[VerifyEmail] -> verify-otp'); router.push({ pathname: '/(auth)/verify-otp', params: { email, isNewUser: '1', inviteCode } }); }; const handleBack = () => { router.back(); }; const handleInviteCodeSubmit = () => { setInviteCode(tempInviteCode); setInviteModalVisible(false); }; const openInviteModal = () => { setTempInviteCode(inviteCode); setInviteModalVisible(true); }; return ( Let's get started! {sendingOtp ? ( Sending verification code... ) : codeSent ? ( We've sent a verification code to ) : ( We'll send a verification code to )} {email} {/* Invite Code */} {inviteCode ? ( Invite code: {inviteCode} ) : ( Have an invite code? )} {error && ( )}