'use client';
import {authFetch} from '@/lib/supabase-browser';
import {useEffect,useState} from 'react';
const plans=[{id:'personal',name:'Personal membership',price:'R99,99',description:'Your private life-planning workspace.',features:['My Life overview & daily check-in','Financial planning & health tracking','Goals, journal & spiritual practices','Invitation-only support circles']},{id:'affiliate',name:'Business affiliate listing',price:'R299,99',description:'A Shop Now listing for approved businesses, separate from personal membership.',features:['Monthly business listing in Shop Now','Complete your business application for listing approval']}];
export function MembershipWorkspace({navigate,onAccessChange}:any){const [settings,setSettings]=useState<any>(null),[error,setError]=useState(''),[notice,setNotice]=useState(''),[busy,setBusy]=useState(''),[consent,setConsent]=useState<Record<string,boolean>>({});async function load(){try{const r=await authFetch('/api/payments/settings');const x:any=await r.json();if(!r.ok)throw Error(x.error);setSettings(x);onAccessChange?.(x.access);}catch(e:any){setError(e.message||'Payment settings could not be loaded.');}}
useEffect(()=>{load();const state=new URLSearchParams(location.search).get('payment');if(state==='cancel')setNotice('Checkout was cancelled. No membership is confirmed from this return.');if(state==='return')setNotice('Welcome back. We are checking your payment confirmation with Payfast. Your subscription appears below once confirmed.');const timer=setInterval(load,state==='return'?5000:60000);window.addEventListener('focus',load);return()=>{clearInterval(timer);window.removeEventListener('focus',load)};},[]);
async function checkout(plan:string){setBusy(plan);setError('');try{const r=await authFetch('/api/payments/checkout',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({plan,consent:consent[plan]===true})});const x:any=await r.json();if(!r.ok)throw Error(x.error);if(!['https://www.payfast.co.za/eng/process','https://sandbox.payfast.co.za/eng/process'].includes(x.action))throw Error('Checkout unavailable.');const form=document.createElement('form');form.method='POST';form.action=x.action;for(const [name,value] of Object.entries(x.fields)){const input=document.createElement('input');input.type='hidden';input.name=name;input.value=String(value);form.appendChild(input);}document.body.appendChild(form);form.submit();}catch(e:any){setError(e.message);setBusy('');}}
async function cancel(id:string){if(!confirm('Cancel your subscription and stop future charges? Your remaining free trial or paid period stays available.'))return;setBusy(id);setError('');try{const r=await authFetch('/api/payments/cancel',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id})});const x:any=await r.json();if(!r.ok)throw Error(x.error);setNotice('Your subscription has been cancelled. Payfast has confirmed that future payments are stopped.');await load();}catch(e:any){setError(e.message);}finally{setBusy('');}}
return <section className="panel membership"><p className="eyebrow">SOVEREIGN MEMBERSHIP</p><h1>Your life, with room for you.</h1><div className="trialwelcome"><span className="trialbadge">FREE 30-DAY TRIAL</span><h2>A little space to bloom. Your first 30 days are our gift to you.</h2><p>Make a little room for yourself. Add your card securely through Payfast and enjoy 30 days to explore your personal sanctuary. R0 today, then R99,99 per month automatically after your trial unless you cancel. Cancel anytime before the trial ends to avoid the first charge.</p><a className="primarybutton" href="#personal-membership">Begin my 30 days of me</a><p className="trialfineprint">One personal trial per account. Business affiliate listings are charged separately.</p></div>{settings?.access?.kind==='trial'&&<div className="reserve" role="status"><b>{settings.access.trial.daysLeft} {settings.access.trial.daysLeft===1?'day':'days'} left in your free trial</b><p>Your trial ends {new Date(settings.access.trial.endsAt).toLocaleDateString('en-ZA',{timeZone:'Africa/Johannesburg'})}. With a card subscription, billing begins after your trial. Cancel below anytime before the trial ends to avoid being charged.</p><button className="secondary" onClick={()=>navigate('home')}>Enjoy my free trial</button></div>}{settings?.access?.kind==='expired'&&<div className="reserve" role="status"><b>Your free trial has ended</b><p>Your saved information is kept. Choose a personal membership below to continue. You have not been charged for your trial.</p></div>}{notice&&<div className="reserve" role="status">{notice}</div>}{error&&<div className="error" role="alert">{error} <button onClick={load}>Refresh</button></div>}{settings&&!settings.ready&&<div className="reserve"><b>{settings.mode==='sandbox'?'Payfast test checkout':'Payfast is being connected'}</b><p>{settings.mode==='sandbox'?'Live payments are not open. Test checkout is available only to the owner.':'Subscriptions will open once the Payfast account is connected and approved.'}</p></div>}<a className="secondary" href="/signup">Complete signup / business application</a><div className="paymentplans">{plans.map(plan=>{const active=settings?.subscriptions?.find((s:any)=>s.plan===plan.id&&['active','overdue'].includes(s.status));const available=settings?.ready||settings?.owner&&settings?.mode==='sandbox';const inTrial=plan.id==='personal'&&(!settings?.access?.trial||settings.access.trial.daysLeft>0);return <article id={plan.id==='personal'?'personal-membership':undefined} className={'paymentplan '+(plan.id==='personal'?'personalpaymentplan':'')} key={plan.id}><p className="eyebrow">{plan.name}</p>{plan.id==='personal'&&<span className="plantrialbadge">30 days free</span>}<div className="membershipprice">{plan.price}<span>/ month</span></div><p>{plan.description}{plan.id==='personal'?' R99,99 per month only after your free trial ends.':''}</p><div className="membershipfeatures">{plan.features.map(f=><p key={f}>{f}</p>)}</div>{active?<p className="paymentstate" role="status">{active.status==='overdue'?'Payment overdue · please check your Payfast subscription':active.mode==='sandbox'?'Test subscription confirmed':inTrial?'Free trial · card confirmed':'Subscription active'}</p>:<><label className="paymentconsent"><input type="checkbox" checked={!!consent[plan.id]} onChange={e=>setConsent({...consent,[plan.id]:e.target.checked})}/><span>{plan.id==='personal'?(inTrial?'I authorise Payfast to save my card. R0 is charged today. R99,99 per month starts automatically after my 30-day trial unless I cancel. I can cancel anytime before the trial ends to avoid the first charge.':'I agree to R99,99 charged today and monthly until I cancel. My one free trial has ended.'):'I agree to '+plan.price+' charged today and every month until I cancel. My business listing has been approved by Sovereign.'} <span>I also agree to the <a href="/legal/terms" target="_blank" rel="noreferrer">Terms</a> and <a href="/legal/membership" target="_blank" rel="noreferrer">Membership &amp; Cancellation policy</a>.</span></span></label><button className="primarybutton" disabled={!available||!consent[plan.id]||!!busy} onClick={()=>checkout(plan.id)}>{busy===plan.id?'Opening Payfast…':settings?.mode==='sandbox'?'Test with Payfast':inTrial?'Start my 30 days of me':'Subscribe with Payfast'}</button></>}</article>})}</div><p className="note">Payment details are entered on Payfast. Monthly recurring payments use a card. Cancel future payments below; a listing payment does not automatically publish a business.</p>{settings?.subscriptions?.some((s:any)=>['active','overdue','cancelled'].includes(s.status))&&<section className="panel"><h2>Your subscriptions</h2><p>Cancel anytime. Cancel before your free trial ends to avoid the first charge.</p>{settings.subscriptions.filter((s:any)=>['active','overdue','cancelled'].includes(s.status)).map((s:any)=><article className="subscriptionrow" key={s.id}><div><b>{s.plan==='personal'?'Personal membership':'Business affiliate listing'}</b><p>{s.mode==='sandbox'?'Test · ':''}{s.status==='cancelled'?'Cancelled · future payments stopped':s.status==='overdue'?'Payment overdue':'Active'}{s.paid_until?' · Paid through '+new Date(s.paid_until).toLocaleDateString('en-ZA'):''}</p></div>{['active','overdue'].includes(s.status)&&<button className="secondary" disabled={!!busy} onClick={()=>cancel(s.id)}>{busy===s.id?'Cancelling…':'Cancel subscription'}</button>}</article>)}</section>}{settings?.owner&&<PayfastSetup settings={settings} onSaved={load}/>}{settings?.access?.allowed&&<button className="textbutton" onClick={()=>navigate('home')}>Back to My Life</button>}</section>;
}
function PayfastSetup({settings,onSaved}:any){const [id,setId]=useState(settings.merchantId||''),[key,setKey]=useState(''),[phrase,setPhrase]=useState(''),[mode,setMode]=useState(settings.mode||'sandbox'),[confirmed,setConfirmed]=useState(false),[busy,setBusy]=useState(false),[message,setMessage]=useState('');async function save(e:React.FormEvent){e.preventDefault();setBusy(true);setMessage('');try{const r=await authFetch('/api/payments/settings',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({merchantId:id,merchantKey:key,passphrase:phrase,mode,confirmed})});const x:any=await r.json();if(!r.ok)throw Error(x.error);setKey('');setPhrase('');setMessage(mode==='live'?'Payfast connected. Live subscriptions are now available.':'Sandbox connected. You can make a test checkout above.');await onSaved();}catch(e:any){setMessage(e.message);}finally{setBusy(false);}}
return <details className="panel paymentsetup" open={!settings.configured}><summary>Connect your Payfast account · owner only</summary><p>In your Payfast dashboard, open Settings → Integration. Copy your Merchant ID and Merchant Key, and set a security passphrase. For monthly subscriptions, enable recurring billing. Enter these details here; do not send them in chat.</p><form onSubmit={save}><label className="field"><span>Checkout mode</span><select value={mode} onChange={e=>{setMode(e.target.value);setConfirmed(false)}}><option value="sandbox">Sandbox · test payments</option><option value="live">Live · real payments</option></select></label><p className="note">Sandbox needs separate credentials from your Payfast sandbox account. Live uses your approved merchant account.</p><label className="field"><span>Merchant ID</span><input inputMode="numeric" required pattern="[0-9]{8}" value={id} onChange={e=>setId(e.target.value.trim())}/></label><label className="field"><span>Merchant Key</span><input type="password" autoComplete="off" required value={key} onChange={e=>setKey(e.target.value.trim())}/></label><label className="field"><span>Security passphrase</span><input type="password" autoComplete="off" required maxLength={100} value={phrase} onChange={e=>setPhrase(e.target.value)}/></label>{mode==='live'&&<label className="paymentconsent"><input type="checkbox" required checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/><span>Payfast has approved my account, and recurring billing is enabled. I want to accept real monthly subscription payments.</span></label>}<button className="primarybutton" disabled={busy}>{busy?'Connecting…':mode==='live'?'Connect live Payfast':'Connect sandbox'}</button>{message&&<p role="status">{message}</p>}</form><p className="note">Your settings are encrypted. Your security passphrase stays on the server and is never included in customer checkout forms.</p></details>;
}
