'use client';
import {legalVersion} from '@/lib/legal';
import {useState} from 'react';
import {sovereignAuth} from '@/lib/supabase-browser';
import {authReturnUrl} from '@/lib/supabase-config';
export type AuthMode='welcome'|'login'|'signup'|'reset'|'update';
export function AuthWorkspace({mode,setMode,onComplete}: {mode:AuthMode;setMode:(mode:AuthMode)=>void;onComplete:()=>void}){
 const [email,setEmail]=useState(''),[password,setPassword]=useState(''),[confirm,setConfirm]=useState(''),[busy,setBusy]=useState(false),[error,setError]=useState(''),[notice,setNotice]=useState('');
 const [accepted,setAccepted]=useState(false);
 function switchMode(next:AuthMode){setError('');setNotice('');setPassword('');setConfirm('');setAccepted(false);setMode(next);}
 async function submit(event:React.FormEvent){event.preventDefault();setBusy(true);setError('');setNotice('');try{
  if(mode==='signup'&&!accepted)throw new Error('Please accept the terms and read the privacy notice before creating an account.');
  const auth=sovereignAuth().auth;
  if((mode==='signup'||mode==='update')&&password!==confirm)throw new Error('Your passwords do not match.');
  if(mode==='login'){const {error}=await auth.signInWithPassword({email:email.trim(),password});if(error)throw error;setPassword('');onComplete();}
  if(mode==='signup'){const {error}=await auth.signUp({email:email.trim(),password,options:{emailRedirectTo:authReturnUrl,data:{terms_version:legalVersion,terms_accepted_at:new Date().toISOString()}}});if(error)throw error;setPassword('');setConfirm('');setNotice('Check your inbox for your Sovereign confirmation email. Open the link to verify your email, then log in.');}
  if(mode==='reset'){const {error}=await auth.resetPasswordForEmail(email.trim(),{redirectTo:authReturnUrl});if(error)throw error;setNotice('If this email has a Sovereign account, a password-reset link is on its way. Check your inbox and spam folder.');}
  if(mode==='update'){const {error}=await auth.updateUser({password});if(error)throw error;setPassword('');setConfirm('');onComplete();}
 }catch(e:any){setError(e.message||'Please try again.');}finally{setBusy(false);}}
 return <section className="sovereignauth"><div className="authintro"><span className="authslogan">Becoming your best self.<br/>Empowered together.</span><p className="authsisterhood">A sisterhood to rise with.</p><h1>{mode==='welcome'?'Your life. Your space. Your Sovereign.':mode==='signup'?'Welcome to Sovereign':mode==='reset'?'Let’s help you back in':mode==='update'?'Choose your new password':'Welcome back'}</h1><p>A warm, private space for women of every background and belief. Care for your wellbeing, plan your money and take small steps towards the life you want.</p></div><div className="authcard">
 {mode==='welcome'?<><h2>Your private space starts here</h2><p>Log in with your email, or create your Sovereign account.</p><button className="primarybutton" onClick={()=>switchMode('login')}>Login</button><button className="secondary" onClick={()=>switchMode('signup')}>Sign up</button></>:<form onSubmit={submit}><h2>{mode==='signup'?'Create your account':mode==='reset'?'Reset your password':mode==='update'?'Set a new password':'Login to Sovereign'}</h2>{mode!=='update'&&<label>Email address<input type="email" autoComplete="email" required value={email} onChange={e=>setEmail(e.target.value)} disabled={busy}/></label>}{mode!=='reset'&&<label>{mode==='update'?'New password':'Password'}<input type="password" required minLength={mode==='login'?1:12} autoComplete={mode==='login'?'current-password':'new-password'} value={password} onChange={e=>setPassword(e.target.value)} disabled={busy}/></label>}{(mode==='signup'||mode==='update')&&<><p className="authhint">Use at least 12 characters.</p><label>Confirm password<input type="password" required minLength={12} autoComplete="new-password" value={confirm} onChange={e=>setConfirm(e.target.value)} disabled={busy}/></label></>}{mode==='signup'&&<label className="legalaccept"><input type="checkbox" required checked={accepted} onChange={e=>setAccepted(e.target.checked)} disabled={busy}/><span>I am 18 or older and agree to the <a href="/legal/terms" target="_blank" rel="noreferrer">Terms &amp; Conditions</a>. I have read the <a href="/legal/privacy" target="_blank" rel="noreferrer">Privacy Policy</a>. Creating an account does not sign me up for marketing.</span></label>}{error&&<p className="error" role="alert">{error}</p>}{notice&&<p className="authnotice" role="status">{notice}</p>}<button className="primarybutton" disabled={busy}>{busy?'Please wait…':mode==='signup'?'Create account':mode==='reset'?'Send reset link':mode==='update'?'Save new password':'Login'}</button>{mode==='login'&&<button type="button" className="textbutton" onClick={()=>switchMode('reset')}>Forgot password?</button>}{mode!=='update'&&<button type="button" className="textbutton" onClick={()=>switchMode(mode==='signup'?'login':'signup')}>{mode==='signup'?'Already a member? Login':'New here? Create an account'}</button>}</form>}
 </div></section>;
}
