import {useState} from 'react';import {useNavigate,Link} from 'react-router-dom';import api from '../api/client';import {useAuth} from '../context/AuthContext';
export default function LoginPage(){const[phone,setPhone]=useState('+233');const[code,setCode]=useState('');const[step,setStep]=useState(1);const[busy,setBusy]=useState(false);const[msg,setMsg]=useState('');const{verify}=useAuth();const nav=useNavigate();async function send(e){e.preventDefault();setBusy(true);setMsg('');try{const{data}=await api.post('/auth/otp/request/',{phone_number:phone});setStep(2);const context=data.member_exists?'We found your member record. Verify to continue.':'This number is new. Verify it to create your profile.';setMsg(context)}catch(e){setMsg(e.response?.data?.phone_number?.[0]||'Unable to send OTP.')}finally{setBusy(false)}}async function confirm(e){e.preventDefault();setBusy(true);setMsg('');try{const data=await verify(phone,code);nav(data.needs_profile?'/signup':'/portal')}catch(e){setMsg(e.response?.data?.non_field_errors?.[0]||'Invalid or expired OTP.')}finally{setBusy(false)}}return <AuthCard title="Continue with your phone" text="Enter your registered mobile number. We will find your member record and send a one-time code.">{step===1?<form onSubmit={send}><label>Mobile number<input required value={phone} onChange={e=>setPhone(e.target.value)} placeholder="+233 24 000 0000" autoComplete="tel"/></label><button className="btn primary" disabled={busy}>{busy?'Sending...':'Send OTP'}</button></form>:<form onSubmit={confirm}><label>6-digit OTP<input required value={code} onChange={e=>setCode(e.target.value.replace(/\D/g,''))} inputMode="numeric" autoComplete="one-time-code" maxLength="6"/></label><button className="btn primary" disabled={busy||code.length!==6}>{busy?'Verifying...':'Verify and continue'}</button><button type="button" className="linkbtn" onClick={()=>{setStep(1);setCode('');setMsg('')}}>Change phone number</button></form>}{msg&&<p className="notice">{msg}</p>}<small>Your number is your account identity. No password required.</small></AuthCard>}
export function AuthCard({title,text,children}){return <div className="auth-page"><div className="auth-card"><Link to="/" className="brand"><span>CA</span><strong>Church Alumni</strong></Link><h1>{title}</h1><p>{text}</p>{children}</div></div>}


