'use client';
import {authFetch} from '@/lib/supabase-browser';
import {BelongingWelcome} from '@/components/section-welcome';
import {useEffect,useRef,useState} from 'react';
export function SupportWorkspace({profile}:any){const [groups,setGroups]=useState<any[]>([]),[selected,setSelected]=useState(''),[info,setInfo]=useState<any>(null),[messages,setMessages]=useState<any[]>([]),[error,setError]=useState(''),[status,setStatus]=useState('Loading…'),[name,setName]=useState(''),[nickname,setNickname]=useState(profile.supportName||''),[code,setCode]=useState(''),[whatsapp,setWhatsapp]=useState(''),[body,setBody]=useState(''),[busy,setBusy]=useState(false);const last=useRef<HTMLDivElement>(null),pendingId=useRef('');async function call(x:any){const r=await authFetch('/api/support',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(x)});const d:any=await r.json();if(!r.ok)throw new Error(d.error);return d}async function list(){try{const r=await authFetch('/api/support');const d:any=await r.json();if(!r.ok)throw new Error(d.error);setGroups(d.groups);setStatus('');}catch(e:any){setError(e.message);setStatus('')}}useEffect(()=>{list()},[]);useEffect(()=>{if(!selected)return;let active=true;const controller=new AbortController();let fetching=false;async function refresh(){if(fetching)return;fetching=true;try{const r=await authFetch('/api/support?group='+encodeURIComponent(selected),{signal:controller.signal});const d:any=await r.json();if(!r.ok)throw new Error(d.error);if(active){setInfo(d.group);setMessages(d.messages);setError('');setStatus('Conversation up to date')}}catch(e:any){if(active&&e.name!=='AbortError')setError(e.message)}finally{fetching=false}}refresh();const t=setInterval(refresh,5000);return()=>{active=false;controller.abort();clearInterval(t)}},[selected]);useEffect(()=>{setWhatsapp(info?.whatsapp||'')},[info?.whatsapp,info?.id]);useEffect(()=>{last.current?.scrollIntoView({block:'nearest',behavior:'smooth'})},[messages.at(-1)?.id]);async function act(x:any){setBusy(true);setError('');try{const d=await call(x);if(d.id){setInfo(null);setMessages([]);setSelected(d.id);await list()}return true}catch(e:any){setError(e.message);return false}finally{setBusy(false)}}
return <><div className="supportwelcome"><BelongingWelcome name=""/><p>You do not have to have it all figured out to connect. Bring a little of your day to your circle.</p></div><div className="sectionheading"><div><p className="eyebrow">SUPPORT CIRCLE</p><h2>A Place To Listen, Share And Connect.</h2></div><span className="pill">Invitation-only groups</span></div><div className="panel supportnote"><p>Share only what you choose. Only the display name you enter here is shown to members; your private profile photo is not shared. Your financial plan, health records and journal are never attached to chat messages.</p><small>This is conversation with people you invite. Replies depend on members being available.</small><p className="note">If a conversation makes you uncomfortable, stop sharing and <a href="mailto:hello@hersovereign.com?subject=Support%20circle%20concern">contact Sovereign about a concern</a>. For urgent help, use SOS.</p></div>{error&&<div className="error" role="alert">{error} <button onClick={list}>Retry</button></div>}<div className="supportlayout"><aside className="panel"><h2>Your Groups</h2>{groups.length===0&&<p>Your circle can start with one trusted person. Create a group, or join with an invitation code.</p>}<div className="grouplist">{groups.map(g=><button className={selected===g.id?'selected':''} onClick={()=>{setInfo(null);setMessages([]);setSelected(g.id)}} key={g.id}>{g.name}</button>)}</div><label className="field"><span>Support-circle display name</span><input maxLength={50} className="textinput" value={nickname} onChange={e=>setNickname(e.target.value)} placeholder="Name shown to group members"/></label><form className="healthform" onSubmit={e=>{e.preventDefault();act({action:'join',code,nickname})}}><h3>Join A Group</h3><label className="field"><span>Invitation code</span><input className="textinput" required value={code} onChange={e=>setCode(e.target.value)}/></label><button disabled={busy||!nickname.trim()} className="primarybutton">Join group</button></form><form className="healthform" onSubmit={e=>{e.preventDefault();act({action:'create',name,nickname})}}><h3>Create A Support Circle</h3><label className="field"><span>Group name</span><input className="textinput" required maxLength={80} value={name} onChange={e=>setName(e.target.value)} placeholder="e.g. Our weekly reset"/></label><button disabled={busy||!nickname.trim()} className="primarybutton">Create group</button></form><p className="note sharingnote">Members need access to Sovereign as well as a group invitation code. The app’s current access is private.</p></aside><section className="panel chatpanel">{!selected?<div className="chatempty"><h2>Start With Your Circle.</h2><p>Choose a group to open its conversation. There are no automated replies.</p></div>:!info?<p>Opening your group…</p>:<><div className="between"><h2>{info.name}</h2><span className="chatstatus" role="status">{status}</span></div>{info.isOwner&&<details className="groupsettings"><summary>Group invitations & WhatsApp</summary><label className="field"><span>Private invitation code</span><input readOnly className="textinput" value={info.invite} onFocus={e=>e.target.select()}/></label><p className="note">Share this code only with the people you want in your circle.</p><form className="healthform" onSubmit={async e=>{e.preventDefault();if(await act({action:'whatsapp',group:selected,whatsapp}))setInfo({...info,whatsapp})}}><label className="field"><span>Existing WhatsApp group invitation link (optional)</span><input type="url" className="textinput" value={whatsapp} onChange={e=>setWhatsapp(e.target.value)} placeholder="https://chat.whatsapp.com/…"/></label><p className="note">Create your group in WhatsApp, then paste its invitation link here.</p><button disabled={busy} className="secondary">Save WhatsApp link</button></form></details>}{info.whatsapp&&<a className="whatsapplink" href={info.whatsapp} target="_blank" rel="noopener noreferrer">Open the group in WhatsApp</a>}<div className="messages" role="log" aria-live="polite" aria-label="Group conversation">{messages.length===0&&<p className="emptynote">The conversation starts with you. A simple hello is enough.</p>}{messages.map(m=><article className={'message '+(m.mine?'mine':'')} key={m.id}><div><b>{m.nickname}</b><time>{new Date(m.createdAt).toLocaleString(undefined,{month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'})}</time></div><p>{m.body}</p></article>)}<div ref={last}/></div><form className="messageform" onSubmit={async e=>{e.preventDefault();if(!body.trim()||busy)return;pendingId.current ||=crypto.randomUUID();if(await act({action:'message',group:selected,body,id:pendingId.current})){const sent={id:pendingId.current,nickname,body:body.trim(),createdAt:Date.now(),mine:true};setMessages(previous=>previous.some(m=>m.id===sent.id)?previous:[...previous,sent]);pendingId.current='';setBody('')}}}><label className="field"><span>Your message</span><textarea disabled={busy} maxLength={2000} rows={3} value={body} onChange={e=>{pendingId.current='';setBody(e.target.value)}} placeholder="Write something to your circle…"/></label><div className="between"><small>{body.length}/2,000 · Updates every few seconds</small><button className="primarybutton" disabled={busy||!body.trim()}>{busy?'Sending…':'Send message'}</button></div></form></>}</section></div></>}
