 'use client';
import {useEffect,useState} from 'react';
import {authFetch,sovereignAuth} from '@/lib/supabase-browser';
import {AuthWorkspace,type AuthMode} from './auth-workspace';
export function EnrolmentWorkspace(){const [signed,setSigned]=useState(false),[mode,setMode]=useState<AuthMode>('signup'),[kind,setKind]=useState('personal'),[rows,setRows]=useState<any[]>([]),[owner,setOwner]=useState(false),[review,setReview]=useState(false),[message,setMessage]=useState(''),[busy,setBusy]=useState(false),[ready,setReady]=useState(false);async function load(){const {data}=await sovereignAuth().auth.getSession();setSigned(!!data.session);setReady(true);if(data.session){const r=await authFetch('/api/enrolment'+(review?'?review=1':''));const x:any=await r.json();if(!r.ok)throw Error(x.error);setRows(x.rows);setOwner(x.owner);}}useEffect(()=>{load().catch(e=>setMessage(e.message));const {data}=sovereignAuth().auth.onAuthStateChange(()=>{setTimeout(()=>load().catch(e=>setMessage(e.message)),0)});return()=>data.subscription.unsubscribe();},[review]);async function submit(e:React.FormEvent<HTMLFormElement>){e.preventDefault();setBusy(true);setMessage('');try{const form=new FormData(e.currentTarget);form.set('kind',kind);const r=await authFetch('/api/enrolment',{method:'POST',body:form});const x:any=await r.json();if(!r.ok)throw Error(x.error);setMessage(x.message);await load();}catch(e:any){setMessage(e.message);}finally{setBusy(false);}}async function decide(row:any,status:string){setBusy(true);try{const note=window.prompt('Optional message to the business:',row.review_note)||'';const r=await authFetch('/api/enrolment',{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:row.id,status,note})});const x:any=await r.json();if(!r.ok)throw Error(x.error);await load();}catch(e:any){setMessage(e.message);}finally{setBusy(false);}}async function download(file:any){try{const r=await authFetch('/api/enrolment?file='+encodeURIComponent(file.key));if(!r.ok)throw Error('File could not be opened.');const url=URL.createObjectURL(await r.blob()),a=document.createElement('a');a.href=url;a.download=file.name;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}catch(e:any){setMessage(e.message);}}
const current=rows.find(r=>r.kind===kind)?.data||{};return <main className="enrolment"><header><a href="/"><img src="/sovereign-logo-master.png" alt="Sovereign" width="160"/></a><a className="secondary" href="/">Back to home</a></header><section className="panel"><p className="eyebrow">GROW WITH SOVEREIGN</p><h1>Your next chapter starts here.</h1><p>Choose your personal sanctuary or introduce your business to our sisterhood.</p><div className="signupchoices" role="tablist" aria-label="Signup option">{['personal','affiliate'].map(k=><button role="tab" aria-selected={kind===k} className={kind===k?'primarybutton':'secondary'} key={k} onClick={()=>{setKind(k);setReview(false);setMessage('');}}>{k==='personal'?'Personal membership':'Business affiliate'}</button>)}</div><p>{kind==='personal'?'30 days free, then R99,99 monthly. Card required through Payfast. Cancel anytime.':'Business membership is R299,99 per month once your application is approved. You’re welcome to apply at no cost—we’ll review your business before you choose to subscribe and your listing goes live.'}</p></section>{!ready?<p>Opening signup…</p>:!signed?<><AuthWorkspace mode={mode} setMode={setMode} onComplete={load}/><p className="note">First create and verify your account, then return here to complete your details and uploads. Choose Login above if you already have an account.</p></>:<><section className="panel"><h2>{kind==='personal'?'Make this space yours':'Tell us about your business'}</h2><p>Your login email comes from your verified account. You can supply a separate business email below. Fields marked * are required. Uploads are optional, private, and reviewed before any business content is published.</p>{kind==='affiliate'&&<div className="reserve"><b>Apply online or complete the same application by hand</b><p><a href="/Sovereign_Business_Affiliate_Pack.pdf" target="_blank" rel="noreferrer">Download the business affiliate pack and application</a>. The application is on pages 5–6; community guidelines are on page 4. Return your completed paper form and listing material to the Sovereign representative who invited you, or email <a href="mailto:hello@hersovereign.com">hello@hersovereign.com</a>. Please do not send payment or card details.</p></div>}<form key={kind+String(rows.find(r=>r.kind===kind)?.updated_at||'new')} className="enrolmentform" onSubmit={submit}><div className="twofields">{[['fullName',kind==='affiliate'?'Contact person *':'Full name *'],['phone','Phone / WhatsApp *'],['town','Town / province *']].map(([n,l])=><label className="field" key={n}><span>{l}</span><input defaultValue={current[n]||''} name={n} required maxLength={150} type={n==='phone'?'tel':'text'}/></label>)}</div>{kind==='affiliate'&&<><div className="twofields"><label className="field"><span>Business name *</span><input defaultValue={current.businessName||''} name="businessName" required maxLength={150}/></label>{[['tradingName','Trading name (if different)'],['role','Contact person’s role'],['businessEmail','Business email *'],['serviceArea','Service / delivery area']].map(([n,l])=><label className="field" key={n}><span>{l}</span><input defaultValue={current[n]||''} name={n} type={n==='businessEmail'?'email':'text'} required={n==='businessEmail'} maxLength={500}/></label>)}<label className="field"><span>Category *</span><select defaultValue={current.category||''} name="category" required><option value="">Choose a category</option>{['Beauty & wellness','Products & retail','Professional services','Classes & experiences','Food & hospitality','Other'].map(c=><option key={c}>{c}</option>)}</select></label><label className="field"><span>Website / social page / booking link</span><input defaultValue={current.website||''} name="website" type="url" placeholder="https://" maxLength={500}/></label><label className="field"><span>Registration number (if registered)</span><input defaultValue={current.registration||''} name="registration" maxLength={100}/></label></div><label className="field"><span>Business introduction and main offer *</span><textarea defaultValue={current.description||''} name="description" required maxLength={2000} rows={5}/></label>{[['prices','Prices and availability *','Provide your prices, availability or a price-list / booking link.'],['experience','Experience details (if applicable)','Venue, schedule, group size, inclusions, accessibility, age limits, participation requirements, alcohol / alcohol-free options and relevant safety arrangements.'],['policies','Booking, delivery, cancellation and refund information *','Explain your arrangements or provide a policy link.']].map(([n,l,h])=><label className="field" key={n}><span>{l}</span><textarea defaultValue={current[n]||''} name={n} required={n!=='experience'} rows={4} maxLength={2000} placeholder={h}/></label>)}<label className="field"><span>Special member offer (optional)</span><textarea defaultValue={current.offer||''} name="offer" rows={3} maxLength={2000}/></label></>}{kind==='affiliate'&&<><h3>Your business uploads (optional)</h3><p className="note">Up to 5 MB each. JPG, PNG or WebP; supporting documents may also be PDF. Please do not upload ID documents, bank statements or card details.</p></>}{kind==='personal'&&<p className="note">You can add an optional photo and preferred name in My Profile after opening your personal space.</p>}{(kind==='personal'?[]:[['logo','Business logo'],['product','Proposed image 1'],['product2','Proposed image 2'],['product3','Proposed image 3'],['priceList','Price list (or supply a link above)'],['qualifications','Product information / qualifications'],['schedule','Experience schedule (if applicable)'],['document','Business profile / other supporting document']]).map(([n,l])=><label className="field" key={n}><span>{l}</span><input type="file" name={n} accept={['document','priceList','qualifications','schedule'].includes(n)?'application/pdf,image/jpeg,image/png,image/webp':'image/jpeg,image/png,image/webp'}/></label>)}{kind==='affiliate'&&<><p className="note">Up to three proposed images are collected for review. Final listing allowances, scope, start date, payment method and any applicable tax or extra charges will be confirmed before activation.</p><div className="twofields"><label className="field"><span>Applicant name *</span><input defaultValue={current.applicantName||''} name="applicantName" required maxLength={150}/></label><label className="field"><span>Application date *</span><input name="applicationDate" type="date" required defaultValue={new Date().toLocaleDateString('en-CA',{timeZone:'Africa/Johannesburg'})}/></label></div><label className="paymentconsent"><input type="checkbox" name="confirmation" value="yes" required/><span>I am authorised to apply and the details are accurate. I have permission to use the supplied material. I have read the <a href="/Sovereign_Business_Affiliate_Pack.pdf" target="_blank" rel="noreferrer">draft guidelines (page 4)</a> and agree that Sovereign may contact me about this application. I understand that applying does not guarantee approval or activate billing. My name, date and this confirmation serve as my online application confirmation; printed applications should be signed and dated.</span></label></>}<label className="paymentconsent"><input type="checkbox" name="consent" value="yes" required/><span>I am 18 or older. I agree to the <a href="/legal/terms">Terms</a> and have read the <a href="/legal/privacy">Privacy Policy</a>. {kind==='affiliate'?'I confirm I can represent this business and have permission to use its uploaded content. Approved listing information may be published; supporting documents remain private.':'My contact details remain private.'}</span></label><button className="primarybutton" disabled={busy}>{busy?'Saving…':kind==='personal'?'Save my signup details':'Submit business application'}</button><p className="note">Your uploaded files are kept unless you replace them. Updating a submitted business application starts a new review.</p></form></section>{owner&&<button className="secondary" onClick={()=>setReview(!review)}>{review?'My applications':'Review business applications · owner'}</button>}{rows.filter(r=>review?r.kind==='affiliate':r.kind===kind).map(r=><section className="panel" key={r.id}><h2>{r.data.businessName||r.data.fullName}</h2><p><b>Status: {r.status}</b></p>{review&&<><p>{r.user_email} · {r.data.fullName} · {r.data.phone} · {r.data.town}</p><p>{r.data.category} · {r.data.registration}</p>{[['tradingName','Trading name'],['role','Contact role'],['businessEmail','Business email'],['serviceArea','Service area'],['prices','Prices and availability'],['experience','Experience details'],['policies','Booking / delivery / cancellation / refunds'],['applicantName','Applicant'],['applicationDate','Application date'],['confirmation','Confirmation']].map(([k,l])=>r.data[k]&&<p key={k}><b>{l}:</b> {r.data[k]}</p>)}<p>{r.data.description}</p><p>{r.data.offer}</p><p>{r.data.website}</p>{r.data.files.map((f:any)=><button className="secondary" key={f.key} onClick={()=>download(f)}>{f.slot}: {f.name}</button>)}<div className="signupchoices">{['approved','declined','submitted'].map(s=><button className="secondary" key={s} disabled={busy} onClick={()=>decide(r,s)}>{s==='submitted'?'Request changes':s==='approved'?'Approve':'Decline'}</button>)}</div></>}{r.review_note&&<p>{r.review_note}</p>}{!review&&(r.kind==='personal'||r.status==='approved')&&<a href="/?payment=return" className="primarybutton">Continue to membership & payment</a>}</section>)}</>}{message&&<div className="reserve" role="status">{message}</div>}</main>}
