import { useState } from 'react'; import { useStore } from '../store'; import { useNavigate } from 'react-router-dom'; import { Leaf, Store, User, Camera, Loader2, X, MapPin, Check } from 'lucide-react'; import { motion, AnimatePresence } from 'framer-motion'; import { CameraCapture } from './CameraCapture'; import { INDIA_DATA } from '../data/india-data'; const INDIAN_STATES = Object.keys(INDIA_DATA); export function Auth() { const { login, deviceId, initDevice, deviceProfiles, deviceProfilesLoaded } = useStore(); const navigate = useNavigate(); const [name, setName] = useState(''); const [contact, setContact] = useState(''); const [nearestCity, setNearestCity] = useState(''); const [district, setDistrict] = useState(''); const [state, setState] = useState(''); const [pincode, setPincode] = useState(''); const [role, setRole] = useState('buyer'); const [showStateList, setShowStateList] = useState(false); const [filteredStates, setFilteredStates] = useState(INDIAN_STATES); const [showDistrictList, setShowDistrictList] = useState(false); const [filteredDistricts, setFilteredDistricts] = useState([]); const [location, setLocation] = useState(null); const [locating, setLocating] = useState(false); const [selfieFile, setSelfieFile] = useState(null); const [selfiePreview, setSelfiePreview] = useState(null); const [showCamera, setShowCamera] = useState(false); const [isCreating, setIsCreating] = useState(false); const [error, setError] = useState(''); const [isSubmitting, setIsSubmitting] = useState(false); // Auto-init device id just in case they hit auth directly if (!deviceId) initDevice(); const removeImage = () => { setSelfieFile(null); setSelfiePreview(null); }; const getLocation = () => { setLocating(true); setError(''); if (!('geolocation' in navigator)) { setError('Geolocation is not supported by your browser.'); setLocating(false); return; } const options = { enableHighAccuracy: true, timeout: 15000, maximumAge: 0 }; navigator.geolocation.getCurrentPosition( (position) => { setLocation({ lat: position.coords.latitude, lng: position.coords.longitude, address: `Precise GPS: ${position.coords.latitude.toFixed(4)}, ${position.coords.longitude.toFixed(4)}` }); setLocating(false); }, (err) => { console.error("Auth Location Error:", err); let msg = 'Failed to get precise GPS location.'; if (err.code === 1) msg = 'Location permission denied. Please allow location access in your browser settings.'; else if (err.code === 3) msg = 'Location request timed out. Please try again in an open area.'; setError(msg); setLocating(false); }, options ); }; const handleLogin = async (e) => { e.preventDefault(); if (!name.trim()) return; // Validate Indian phone number format const phoneRegex = /^(?:\+?91[-\s]?)?[0]?(?:91)?[6789]\d{9}$/; if (!phoneRegex.test(contact)) { setError('Please enter a valid 10-digit Indian phone number.'); return; } if (!selfieFile) { setError('A live selfie snapshot is strictly required to ensure network trust.'); return; } if (!location) { setError('Please capture your primary GPS location.'); return; } if (!nearestCity || !district || !state || !pincode) { setError('Please fill in all location details.'); return; } setIsSubmitting(true); setError(''); try { const { deviceId: currentDeviceId, deviceToken } = deviceId ? { deviceId, deviceToken: useStore.getState().deviceToken } : initDevice(); const formData = new FormData(); formData.append('id', currentDeviceId); formData.append('deviceToken', deviceToken); formData.append('name', name); formData.append('contact', contact); formData.append('role', role); formData.append('nearestCity', nearestCity); formData.append('district', district); formData.append('state', state); formData.append('pincode', pincode); formData.append('location', JSON.stringify(location)); formData.append('selfie', selfieFile); const res = await fetch('/api/users', { method: 'POST', body: formData, }); const data = await res.json(); if (!res.ok) { throw new Error(data.error || 'Failed to register identity.'); } console.log('REGISTRATION SUCCESS:', data); console.log('NAVIGATING TO:', (role === 'buyer' ? '/buyer' : '/seller')); // Zustand handles our local user binding login(data); navigate(role === 'buyer' ? '/buyer' : '/seller'); } catch (err) { console.error(err); setError(err.message || 'Registration failed. Please try again.'); } finally { setIsSubmitting(false); } }; const handleProfileSelect = (profile) => { login(profile); navigate(profile.role === 'buyer' ? '/buyer' : '/seller'); }; const hasProfiles = deviceProfilesLoaded && deviceProfiles.length > 0; const isCreatingNew = !hasProfiles || isCreating; const hasBuyer = deviceProfiles.some(p => p.role === 'buyer'); const hasSeller = deviceProfiles.some(p => p.role === 'seller'); if (!deviceProfilesLoaded) { return (
The smart way to buy and sell crops directly.