import {useEffect,useState} from 'react';import {BriefcaseBusiness,CalendarDays,Check,Image,MessageCircle,PlayCircle,Send,ShieldCheck} from 'lucide-react';import api from '../api/client';
const rows=d=>d?.results||d||[];
export function ForumPage(){const[topics,setTopics]=useState([]),[form,setForm]=useState({title:'',body:'',visibility:'GENERAL'}),[error,setError]=useState('');const load=async()=>{try{const{data}=await api.get('/community/forum/');setTopics(rows(data));setError('')}catch{setError('Unable to load community conversations.')}};useEffect(()=>{load()},[]);const submit=async e=>{e.preventDefault();try{await api.post('/community/forum/',form);setForm({title:'',body:'',visibility:'GENERAL'});await load()}catch{setError('Unable to publish this conversation.')}};return <Page title="Community Forum" eyebrow="BELONG · SHARE · GROW">{error&&<p className="notice error">{error}</p>}<div className="portal-grid"><section className="portal-card"><h2>Start a conversation</h2><form className="portal-form" onSubmit={submit}><input required placeholder="Conversation title" value={form.title} onChange={e=>setForm({...form,title:e.target.value})}/><textarea required placeholder="What would you like to share?" value={form.body} onChange={e=>setForm({...form,body:e.target.value})}/><select value={form.visibility} onChange={e=>setForm({...form,visibility:e.target.value})}><option value="GENERAL">Entire HSM community</option><option value="CAMPUS">My campus only</option></select><button className="portal-btn primary"><Send size={16}/>Publish</button></form></section><section className="portal-card wide"><div className="discussion-list">{topics.map(t=><article key={t.id}><span className="discussion-icon"><MessageCircle/></span><div><small>{t.visibility==='GENERAL'?'GENERAL COMMUNITY':t.campus_name}</small><h3>{t.title}</h3><p>{t.body}</p><footer>{t.author_name} · {t.reply_count} replies</footer></div></article>)}</div></section></div></Page>}
export function AttendancePage(){const[services,setServices]=useState([]),[mine,setMine]=useState([]),[error,setError]=useState('');const load=async()=>{try{const[a,b]=await Promise.all([api.get('/community/services/?ordering=-starts_at'),api.get('/community/my-attendance/')]);setServices(rows(a.data));setMine(rows(b.data));setError('')}catch{setError('Unable to load attendance information.')}};useEffect(()=>{load()},[]);const register=async id=>{try{await api.post(`/community/services/${id}/register/`);await load()}catch{setError('Unable to register attendance.')}};return <Page title="Attendance & Services" eyebrow="SHOW UP · SERVE · GROW">{error&&<p className="notice error">{error}</p>}<div className="portal-grid"><section className="portal-card wide"><h2>Campus services & activities</h2><div className="event-grid">{services.map(s=><article key={s.id}><span>{s.event_type.replaceAll('_',' ')}</span><h3>{s.title}</h3><p><CalendarDays size={15}/>{new Date(s.starts_at).toLocaleString()}</p><small>{s.venue} · {s.attendance_count} registered</small><button disabled={s.registered} onClick={()=>register(s.id)} className="portal-btn primary">{s.registered?<><Check/>Registered</>:<>Register attendance</>}</button></article>)}</div></section><section className="portal-card"><h2>My attendance history</h2>{mine.map(a=><article className="attendance-detail" key={a.id}><Check/><div><span>{a.activity_type} · {a.campus_name}</span><h3>{a.title}</h3><p>{new Date(a.date).toLocaleDateString()} · {a.venue||'Venue not specified'}</p>{a.details&&<small>{a.details}</small>}</div></article>)}{!mine.length&&<div className="portal-empty">No recorded attendance yet.</div>}</section></div></Page>}
export function MediaPage(){const[sermons,setSermons]=useState([]),[gallery,setGallery]=useState([]);useEffect(()=>{api.get('/community/sermons/').then(r=>setSermons(rows(r.data)));api.get('/community/gallery/').then(r=>setGallery(rows(r.data)))},[]);return <Page title="Sermons & Kingdom Stories" eyebrow="WATCH · LISTEN · REMEMBER"><section className="media-grid">{sermons.map(s=><a href={s.media_url} target="_blank" className="sermon-card" key={s.id}><div style={{backgroundImage:`url(${s.thumbnail_url||''})`}}><PlayCircle/></div><span>{s.scripture||'THE WORD'}</span><h3>{s.title}</h3><p>{s.preacher} · {new Date(s.preached_on).toLocaleDateString()}</p></a>)}</section><section className="portal-card"><div className="card-head"><div><span>KINGDOM MOMENTS</span><h2>Gallery</h2></div><Image/></div><div className="gallery-grid">{gallery.map(g=><figure key={g.id}><img src={g.image_url} alt={g.title}/><figcaption><strong>{g.title}</strong><small>{g.caption}</small></figcaption></figure>)}</div></section></Page>}
export function DirectoryPage(){const[list,setList]=useState([]),[q,setQ]=useState(''),[error,setError]=useState('');useEffect(()=>{const controller=new AbortController();const timer=setTimeout(()=>{api.get(`/auth/professionals/?search=${encodeURIComponent(q)}`,{signal:controller.signal}).then(r=>{setList(rows(r.data));setError('')}).catch(e=>{if(e.code!=='ERR_CANCELED')setError('Unable to load the member network.')})},200);return()=>{clearTimeout(timer);controller.abort()}},[q]);return <Page title="Professional Network" eyebrow="CONNECT · MENTOR · BUILD"><section className="portal-card"><input className="directory-search" placeholder="Search by member, profession or employer..." value={q} onChange={e=>setQ(e.target.value)}/>{error&&<p className="notice error">{error}</p>}<div className="professional-grid">{list.map(p=><article key={p.id}><span><BriefcaseBusiness/></span><h3>{p.full_name}</h3><strong>{p.job_title||p.profession||'Professional details pending'}</strong><p>{p.employer||(p.profile_ready?'Independent professional':'Member profile')}</p><small>{p.campus_name}</small></article>)}</div>{!error&&!list.length&&<div className="portal-empty">No members match your search.</div>}</section></Page>}
export function GivingPage(){const[list,setList]=useState([]),[form,setForm]=useState({purpose:'OFFERTORY',amount:'',anonymous:false,note:''}),[message,setMessage]=useState(''),[error,setError]=useState('');const load=async()=>{try{const{data}=await api.get('/payments/contributions/');setList(rows(data));setError('')}catch{setError('Unable to load your giving history.')}};useEffect(()=>{load()},[]);const give=async e=>{e.preventDefault();setError('');try{const{data}=await api.post('/payments/contributions/',form);if(data.authorization_url?.includes('mock=success')){await api.post('/payments/contributions/verify/',{reference:data.reference});setMessage('Thank you. Your giving was received successfully.');await load()}else if(data.authorization_url){location.assign(data.authorization_url)}else setError('The payment provider did not return a checkout link.')}catch(e){const detail=e.response?.data;setError(detail?.detail||detail?.amount?.[0]||'Unable to start this payment.')}};return <Page title="Giving" eyebrow="GENEROUS HEARTS · KINGDOM IMPACT">{error&&<p className="notice error">{error}</p>}<div className="portal-grid"><section className="giving-card"><ShieldCheck/><span>SECURE GIVING</span><h2>Your generosity moves the mission forward.</h2><p>Give an offertory, support missions, welfare, or a Kingdom project through our secure payment partners.</p></section><section className="portal-card"><form className="portal-form" onSubmit={give}><label>Purpose<select value={form.purpose} onChange={e=>setForm({...form,purpose:e.target.value})}>{['OFFERTORY','DONATION','TITHE','MISSIONS','WELFARE','PROJECT','OTHER'].map(x=><option key={x}>{x.replace('_',' ')}</option>)}</select></label><label>Amount (GHS)<input required min="1" step="0.01" type="number" value={form.amount} onChange={e=>setForm({...form,amount:e.target.value})}/></label><label>Note<input value={form.note} onChange={e=>setForm({...form,note:e.target.value})}/></label><label className="check"><input type="checkbox" checked={form.anonymous} onChange={e=>setForm({...form,anonymous:e.target.checked})}/>Give anonymously</label><button className="portal-btn primary">Continue securely</button>{message&&<p className="success-note">{message}</p>}</form></section></div><section className="portal-card"><h2>My giving history</h2>{list.map(x=><div className="history-row" key={x.id}><span><strong>{x.purpose_display}</strong><small>{new Date(x.created_at).toLocaleDateString()} · {x.reference}</small></span><b>GHS {x.amount} · {x.status}</b></div>)}</section></Page>}
function Page({title,eyebrow,children}){return <><header className="page-intro"><span>{eyebrow}</span><h1>{title}</h1></header>{children}</>}
