'use client';
import {authFetch} from '@/lib/supabase-browser';
import {useEffect,useRef,useState} from 'react';
import {createPortal} from 'react-dom';
import {Siren,X,Phone} from 'lucide-react';
import {validContacts,helpMessage,smsLink} from '@/lib/emergency';
export function EmergencyHelp({p,change,saved}:any){const [open,setOpen]=useState(false),[configured,setConfigured]=useState<boolean|null>(null),[busy,setBusy]=useState(false),[message,setMessage]=useState(''),[location,setLocation]=useState<any>(null),[results,setResults]=useState<any[]>([]);const lock=useRef(false),close=useRef<HTMLButtonElement>(null),trigger=useRef<HTMLButtonElement>(null);const contacts=p.emergencyContacts||Array.from({length:3},()=>({name:'',phone:''}));const ready=validContacts(contacts,true)&&saved;
useEffect(()=>{authFetch('/api/emergency').then(r=>r.ok?r.json():Promise.reject()).then((x:any)=>setConfigured(x.configured)).catch(()=>setConfigured(null))},[]);
useEffect(()=>{if(!open)return;const prior=document.body.style.overflow;document.body.style.overflow='hidden';close.current?.focus();const key=(e:KeyboardEvent)=>{if(e.key==='Escape'&&!lock.current)setOpen(false);if(e.key==='Tab'){const list=Array.from(document.querySelectorAll<HTMLElement>('.emergencydialog button:not(:disabled),.emergencydialog input,.emergencydialog a[href]'));const first=list[0],last=list.at(-1);if(e.shiftKey&&document.activeElement===first){e.preventDefault();last?.focus()}else if(!e.shiftKey&&document.activeElement===last){e.preventDefault();first?.focus()}}};document.addEventListener('keydown',key);return()=>{document.body.style.overflow=prior;document.removeEventListener('keydown',key);trigger.current?.focus()}},[open]);
async function locate(){setMessage('Getting your current location…');const point:any=await new Promise(resolve=>{if(!navigator.geolocation){resolve(null);return}navigator.geolocation.getCurrentPosition(v=>resolve({lat:v.coords.latitude,lng:v.coords.longitude,accuracy:v.coords.accuracy,time:v.timestamp}),()=>resolve(null),{enableHighAccuracy:true,timeout:10000,maximumAge:0})});setLocation(point);return point}
async function send(){if(lock.current||!ready||!configured)return;lock.current=true;setBusy(true);setResults([]);try{const point=await locate();setMessage(point?'Sending your request for help…':'Location unavailable. Sending your request without a location…');const r=await authFetch('/api/emergency',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:crypto.randomUUID(),location:point}),signal:AbortSignal.timeout(25000)});const x:any=await r.json();setResults(x.results||[]);setMessage(x.error||x.message)}catch{setMessage('Sending is unconfirmed. Call or send a message below now.')}finally{lock.current=false;setBusy(false)}}
const text=helpMessage(p.profile.displayName,location);return <><button ref={trigger} className="sosbutton" onClick={()=>setOpen(true)} aria-label="Get help · emergency contacts"><Siren size={23}/> SOS · Get help</button>{open&&createPortal(<div className="emergencyoverlay"><section className="emergencydialog" role="dialog" aria-modal="true" aria-labelledby="emergency-title"><div className="between"><h1 id="emergency-title"><Siren/> Get help</h1><button ref={close} aria-label="Close get help" disabled={busy} onClick={()=>setOpen(false)}><X/></button></div><div className="sosdirect"><h2>Need urgent help in South Africa?</h2><a className="secondary" href="tel:10111">Call police · 10111</a><a className="secondary" href="tel:0800428428">GBV support · 0800 428 428</a><p className="note">Calls open your phone’s dialler. <a href="https://www.gov.za/about-government/government-call-centres-and-help-lines" target="_blank" rel="noreferrer">Government helpline information</a>.</p></div><p>Ask your three nominated people for help. Your location is requested only when you choose to send or add it.</p><div className="sosnotice"><b>{configured===true?'Automatic SMS alerts available':configured===false?'Automatic alerts are not active':'Automatic alert service unavailable'}</b><p>{configured===true?'An alert sends a help message to all three contacts. SMS delivery and a response are not guaranteed.':'A sending service must be connected before this button can notify your contacts automatically. You can call or open a message below.'}</p></div><button className="sendhelp" disabled={!ready||!configured||busy} onClick={send}>{busy?'Requesting help…':'Send help alert to my 3 contacts'}</button>{!ready&&<p className="note">Enter three different contacts using country codes (for example +27821234567). Wait until your contacts show Saved before sending.</p>}<div role="status" aria-live="polite"><p>{message}</p>{results.map((x,i)=><p key={i}><b>{x.name}:</b> {x.status==='submitted'?'Submitted to SMS service · delivery unconfirmed':x.status==='failed'?'Could not send':'Sending unconfirmed'}</p>)}</div><details open={!validContacts(contacts,true)} className="optionaltools"><summary>My 3 emergency contacts</summary><p>Choose people who have agreed to be your emergency contacts.</p>{contacts.map((c:any,i:number)=><fieldset key={i}><legend>Contact {i+1}</legend><label className="field"><span>Name</span><input maxLength={80} className="textinput" value={c.name} onChange={e=>change((x:any)=>{x.emergencyContacts??=contacts;x.emergencyContacts[i].name=e.target.value})}/></label><label className="field"><span>Mobile number with country code</span><input type="tel" maxLength={30} className="textinput" placeholder="+27821234567" value={c.phone} onChange={e=>change((x:any)=>{x.emergencyContacts??=contacts;x.emergencyContacts[i].phone=e.target.value.replace(/[\s()-]/g,'')})}/></label></fieldset>)}<p role="status">{saved?'Saved':'Contacts saving · keep this page open'}</p></details><p className="note"><a href="/legal/sos" target="_blank" rel="noreferrer">How SOS works</a> · <a href="/legal/privacy" target="_blank" rel="noreferrer">Your contacts and location privacy</a>. Add and share your location with your nominated contacts. For manual messages, press Send in your messaging app to share the pin.</p><h2>Call Or Message Now</h2><button className="secondary" disabled={busy} onClick={async()=>{if(lock.current)return;lock.current=true;setBusy(true);try{const v=await locate();setMessage(v?'Location added to the messages below. You must press Send in your messaging app.':'Location unavailable. You can still call or send a message below.')}finally{lock.current=false;setBusy(false)}}}>Add and share</button>{location&&<p><a href={`https://maps.google.com/?q=${location.lat},${location.lng}`} target="_blank" rel="noreferrer">View location</a> · approximately {Math.round(location.accuracy)}m accuracy</p>}<p className="note">“Open message” opens your phone’s messaging app. You must press Send there for each contact. Calls and messages depend on your device and network.</p>{contacts.filter((c:any)=>/^\+[1-9]\d{7,14}$/.test(c.phone)).map((c:any,i:number)=><div className="contactactions" key={i}><b>{c.name||`Contact ${i+1}`}</b><a href={'tel:'+c.phone}><Phone size={16}/> Call</a><a href={smsLink(c.phone,text)}>Open message</a></div>)}<p className="note">This feature does not dispatch emergency services or monitor your safety. If you are in immediate danger, contact your local emergency services directly.</p></section></div>,document.body)}</>}
