// File: src/components/VerificationModal.js import React, { useState, useEffect } from 'react'; import { supabase } from '../supabaseClient'; import { motion } from 'framer-motion'; export default function VerificationModal({ onClose, onVerified }) { const [step, setStep] = useState(0); // 0 = Loading Profile, 1 = Confirm Send, 2 = Enter OTP const [phone, setPhone] = useState(''); const [otp, setOtp] = useState(''); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); // 1. Fetch User's Phone on Mount useEffect(() => { const fetchUserProfile = async () => { setError(null); try { const { data: { user } } = await supabase.auth.getUser(); if (!user) throw new Error("No user found."); const { data: profile, error: profileError } = await supabase .from('profiles') .select('phone') .eq('id', user.id) .single(); if (profileError) throw profileError; if (!profile.phone) { setError("No phone number found in your profile. Please go to your Profile settings and add a phone number first."); return; } setPhone(profile.phone); setStep(1); // Ready to send } catch (err) { console.error("Profile Fetch Error:", err); setError("Could not load profile details."); } }; fetchUserProfile(); }, []); // 2. Helper to mask phone number (e.g., +1 ********99) const maskPhone = (p) => { if (!p || p.length < 5) return p; return `${p.slice(0, 3)}****${p.slice(-3)}`; }; // 3. Send OTP const handleSendOtp = async () => { setLoading(true); setError(null); try { // Call the 'otp' Edge Function with action: 'send' const { data, error } = await supabase.functions.invoke('otp', { body: { action: 'send' } }); if (error) throw error; // Check for logic error from function if (data?.error) throw new Error(data.error); // For testing only (Remove in production) if (data?.dev_otp) console.log("DEV OTP:", data.dev_otp); setStep(2); } catch (err) { setError(err.message || "Failed to send OTP"); } finally { setLoading(false); } }; // 4. Verify OTP const handleVerifyOtp = async () => { if (!otp) return setError("Please enter the code."); setLoading(true); setError(null); try { // Call the 'otp' Edge Function with action: 'verify' const { data, error } = await supabase.functions.invoke('otp', { body: { action: 'verify', userCode: otp } }); if (error) throw error; if (data?.error) throw new Error(data.error); // Success! onVerified(); } catch (err) { setError(err.message || "Invalid OTP"); } finally { setLoading(false); } }; return (
Fetching contact details...
)} {/* --- STEP 1: CONFIRM PHONE --- */} {step === 1 && ( <>We will send a code to:
{maskPhone(phone)}
Enter the 6-digit code sent to your phone.