'use client' import { useState, useEffect } from 'react' import { useSearchParams } from 'next/navigation' import { useI18n } from '@/lib/i18n' interface User { id: number username: string email: string } interface AuthModalProps { isOpen: boolean onClose: () => void onLogin: (user: User) => void } export default function AuthModal({ isOpen, onClose, onLogin }: AuthModalProps) { const { t } = useI18n() const searchParams = useSearchParams() const [isLogin, setIsLogin] = useState(true) const [username, setUsername] = useState('') const [password, setPassword] = useState('') const [email, setEmail] = useState('') const [referralId, setReferralId] = useState('') const [error, setError] = useState('') const [loading, setLoading] = useState(false) useEffect(() => { if (isOpen) { // Reset form when modal opens setUsername('') setPassword('') setEmail('') setError('') setIsLogin(true) // Auto-fill referral ID from URL if present const refFromUrl = searchParams?.get('ref') if (refFromUrl) { setReferralId(refFromUrl) } else { setReferralId('') } } }, [isOpen, searchParams]) // Update referral ID when switching to register mode and URL has ref parameter useEffect(() => { if (!isLogin) { const refFromUrl = searchParams?.get('ref') if (refFromUrl && !referralId) { setReferralId(refFromUrl) } } }, [isLogin, searchParams, referralId]) const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() setError('') setLoading(true) try { const endpoint = isLogin ? '/api/auth/login' : '/api/auth/register' // Use referral ID from input field, or fall back to URL parameter const referralIdToUse = !isLogin && referralId.trim() ? referralId.trim() : (!isLogin ? searchParams?.get('ref') : null) const body = isLogin ? { username, password } : { username, password, email, referral_id: referralIdToUse } const response = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(body), credentials: 'include', // Important for cookies }) const data = await response.json() if (!response.ok) { setError(data.error || t('auth.anErrorOccurred')) setLoading(false) return } // Success - call onLogin callback and close modal onLogin(data.user) onClose() } catch (error) { console.error('Auth error:', error) setError(t('auth.unexpectedError')) } finally { setLoading(false) } } if (!isOpen) return null return (