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 (
); } return ( {showCamera && ( setShowCamera(false)} onCapture={(file, dataUrl) => { setSelfieFile(file); setSelfiePreview(dataUrl); setShowCamera(false); setError(''); }} /> )}

Welcome to Meri Mandi

The smart way to buy and sell crops directly.

{error && (
{error}
)} {isCreatingNew ? (
{hasProfiles && (
)} {/* Selfie Upload UI */}

Take a Live Selfie Profile

{selfiePreview ? (
Selfie
) : (
setShowCamera(true)} style={{ width: '120px', height: '120px', borderRadius: '50%', border: '2px dashed var(--primary-color)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', background: 'var(--primary-glow)', gap: '8px' }} > Snap Live
)}

We strictly ask for you to take a live photo over the network.

setName(e.target.value)} disabled={isSubmitting} required />
setContact(e.target.value)} disabled={isSubmitting} required />
{/* New Location Fields */}
{ const val = e.target.value; setState(val); setFilteredStates(INDIAN_STATES.filter(s => s.toLowerCase().includes(val.toLowerCase()))); setShowStateList(true); setDistrict(''); // Reset district on state change }} onFocus={() => setShowStateList(true)} disabled={isSubmitting} required /> {showStateList && filteredStates.length > 0 && ( {filteredStates.map(s => (
{ setState(s); setShowStateList(false); setError(''); setDistrict(''); setFilteredDistricts(INDIA_DATA[s] || []); }} style={{ padding: '12px 16px', cursor: 'pointer', borderBottom: '1px solid var(--border-color)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }} onMouseEnter={e => e.currentTarget.style.background = 'var(--primary-glow)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'} > {s} {state === s && }
))}
)}
{showStateList &&
setShowStateList(false)} style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, zIndex: 105 }} />}
{ const val = e.target.value; setDistrict(val); const ds = INDIA_DATA[state] || []; setFilteredDistricts(ds.filter(d => d.toLowerCase().includes(val.toLowerCase()))); setShowDistrictList(true); }} onFocus={() => { if (state) { const ds = INDIA_DATA[state] || []; setFilteredDistricts(ds.filter(d => d.toLowerCase().includes(district.toLowerCase()))); setShowDistrictList(true); } }} disabled={isSubmitting || !state} required /> {showDistrictList && filteredDistricts.length > 0 && ( {filteredDistricts.map(d => (
{ setDistrict(d); setShowDistrictList(false); setError(''); }} style={{ padding: '12px 16px', cursor: 'pointer', borderBottom: '1px solid var(--border-color)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }} onMouseEnter={e => e.currentTarget.style.background = 'var(--primary-glow)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'} > {d} {district === d && }
))}
)}
{showDistrictList &&
setShowDistrictList(false)} style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, zIndex: 105 }} />}
setNearestCity(e.target.value)} disabled={isSubmitting} required />
setPincode(e.target.value)} disabled={isSubmitting} required />
{location ? 'Precise Location Captured' : 'Get Primary Location (GPS)'} {location && {location.address}}
{locating && }
!isSubmitting && !hasBuyer && setRole('buyer')} style={{ flex: 1, padding: '16px', borderRadius: '16px', border: `2px solid ${role === 'buyer' ? 'var(--primary-color)' : 'var(--border-color)'}`, background: role === 'buyer' ? 'var(--primary-glow)' : 'transparent', cursor: isSubmitting || hasBuyer ? 'not-allowed' : 'pointer', textAlign: 'center', transition: 'all 0.2s', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '8px', opacity: isSubmitting || hasBuyer ? 0.5 : 1 }} > {hasBuyer ? 'Buyer (Owned)' : 'Buyer'}
!isSubmitting && !hasSeller && setRole('seller')} style={{ flex: 1, padding: '16px', borderRadius: '16px', border: `2px solid ${role === 'seller' ? 'var(--primary-color)' : 'var(--border-color)'}`, background: role === 'seller' ? 'var(--primary-glow)' : 'transparent', cursor: isSubmitting || hasSeller ? 'not-allowed' : 'pointer', textAlign: 'center', transition: 'all 0.2s', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '8px', opacity: isSubmitting || hasSeller ? 0.5 : 1 }} > {hasSeller ? 'Seller (Owned)' : 'Seller'}
) : (

Select Profile

{deviceProfiles.map(profile => (
handleProfileSelect(profile)} className="glass-panel" style={{ padding: '20px', display: 'flex', alignItems: 'center', gap: '16px', cursor: 'pointer', transition: 'transform 0.2s, box-shadow 0.2s' }} onMouseOver={(e) => e.currentTarget.style.transform = 'translateY(-2px)'} onMouseOut={(e) => e.currentTarget.style.transform = 'translateY(0)'} >
Selfie

{profile.name}

{profile.role === 'buyer' ? : } {profile.role}
))}
{deviceProfiles.length < 2 && ( )}
)} ); }