'use client';
import {SectionStepHeader} from '@/components/section-step-header';
import {BelongingWelcome,SectionWelcome} from '@/components/section-welcome';
import {useState,useEffect} from 'react';
import {Wallet,Brain,Heart,Activity,Sun,Users,NotebookPen,Check,CalendarDays,ChevronDown,ShoppingBag,Leaf} from 'lucide-react';
import {Checkbox} from '@/components/ui/checkbox';
import {Select,SelectTrigger,SelectValue,SelectContent,SelectItem} from '@/components/ui/select';
import {effectiveTone,orderedAspects,reflectionPrompt} from '@/lib/profile';
import {dailyQuote,thoughtDate} from '@/lib/quotes';
import {aspects,todayKey,weekKey,addTask,upcomingBills} from '@/lib/life';
const icons:any={wallet:Wallet,mind:Brain,heart:Heart,activity:Activity,sun:Sun,people:Users};
const cash=(v:number)=>new Intl.NumberFormat('en-ZA',{style:'currency',currency:'ZAR',maximumFractionDigits:0}).format(v);
function Choice({label,value,onChange,options}:any){return <Select value={value} onValueChange={onChange}><SelectTrigger aria-label={label}><SelectValue/></SelectTrigger><SelectContent>{options.map(([v,l]:any)=><SelectItem key={v} value={v}>{l}</SelectItem>)}</SelectContent></Select>}
const areaOptions=aspects.map(x=>[x.id,x.name]);
const wellbeingAreas=['mental','emotional','spiritual','relationships'];
const wellbeingQuestions=[['spiritual','When do I feel most like myself, and what matters deeply to me?'],['emotional','What are my feelings telling me about my needs and boundaries?'],['mental','What story am I telling myself, and how could I respond with kindness?'],['relationships','Who do I want to become, and what small choice can I make today?']];
const reflectionGuides:Record<string,string>={spiritual:'Think of a moment when you felt true to yourself. Which values or strengths were you expressing? Where are your choices shaped by what others expect, and what would you choose for yourself?',emotional:'Recall a recent moment that stirred a strong feeling. What happened, what did you notice in your body, and what need might be underneath? What boundary or support could honour that need?',mental:'Notice a thought that keeps returning. What facts support it, and what might you be assuming? What would you say to a friend in the same situation? Try offering yourself that same understanding.',relationships:'Describe the qualities you want to practise, rather than a perfect version of yourself. What strength can you build on? Choose one small action within your control, and decide when you will take it.'};
export function LifeHub({mode,p,change,navigate,area='mental',practicesOnly=false}:any){const [quoteDate,setQuoteDate]=useState(thoughtDate);const [today,setToday]=useState(todayKey);useEffect(()=>{const refresh=()=>{setToday(todayKey());setQuoteDate(thoughtDate())};const timer=window.setInterval(refresh,60000);window.addEventListener('focus',refresh);return()=>{window.clearInterval(timer);window.removeEventListener('focus',refresh)}},[]);const tone=effectiveTone(p.profile,today),simple=p.profile.structure==='simple',prompt=reflectionPrompt(p.profile,tone,today);const life=p.life,[draft,setDraft]=useState(''),[showHidden,setShowHidden]=useState(false),[entry,setEntry]=useState(''),[entryArea,setEntryArea]=useState('emotional'),[goal,setGoal]=useState(''),[target,setTarget]=useState(''),[goalDate,setGoalDate]=useState(''),[goalArea,setGoalArea]=useState('mental'),[appt,setAppt]=useState(''),[apptDate,setApptDate]=useState(today),[apptTime,setApptTime]=useState(''),[practice,setPractice]=useState(''),[journalDate,setJournalDate]=useState(today),[reflectionTab,setReflectionTab]=useState(mode==='weekly'?'weekly':'journal');useEffect(()=>{setEntryArea(mode==='area'?area:'emotional')},[area,mode]);const visibleEntries=life.entries.filter((x:any)=>mode==='area'?x.area===area:wellbeingAreas.includes(x.area));const selectedQuestion=wellbeingQuestions.find(([id])=>id===entryArea)?.[1]||wellbeingQuestions[0][1];const bills=upcomingBills(p.budget,today),checkin=life.checkins[today]||{},week=weekKey(journalDate),review=life.reviews[week]||{};function update(fn:any){change((x:any)=>fn(x.life))}function capture(e:any){e.preventDefault();if(!draft.trim())return;update((l:any)=>addTask(l,draft,area));setDraft('')}
const Capture=<form className="capture" onSubmit={capture}><input aria-label="Capture a thought or task" value={draft} onChange={e=>setDraft(e.target.value)} placeholder="Put it down here. You can sort it later."/><button className="primarybutton" disabled={!draft.trim()}>Add thought</button></form>;
function journal(numbered=false){return <>{numbered&&<SectionStepHeader step={2} title="Get To Know Yourself">Explore your values, feelings, inner voice and the woman you want to become. Choose one question and take it at your own pace. Small, honest reflections can guide your next step.</SectionStepHeader>}<div className="between">{!numbered&&<h2>Your Private Journal</h2>}<label className="field"><span>Entry date</span><input className="textinput" type="date" value={journalDate} onChange={e=>e.target.value&&setJournalDate(e.target.value)}/></label></div><form className="healthform" onSubmit={e=>{e.preventDefault();if(!entry.trim())return;update((l:any)=>l.entries.push({id:crypto.randomUUID(),date:journalDate,area:entryArea,text:selectedQuestion+'\n\n'+entry.trim()}));setEntry('')}}><label className="field"><span>A question for your wellbeing</span><Choice label="Wellbeing reflection question" value={entryArea} onChange={setEntryArea} options={wellbeingQuestions}/></label><label className="field"><span>{selectedQuestion}</span><p className="reflectionguidance">{reflectionGuides[entryArea]}</p><textarea rows={5} value={entry} onChange={e=>setEntry(e.target.value)} placeholder="Start with one real example. What do you notice about yourself?"/></label><button className="primarybutton" disabled={!entry.trim()}>Add reflection</button><small className="note">You can skip any question. Growth takes practice, not perfection. Choose Add reflection to save; edits save automatically.</small></form><div className="reflectionlist">{[...visibleEntries].reverse().map((x:any,i:number)=><article key={x.id}><div className="between"><b>{aspects.find(a=>a.id===x.area)?.name}</b><span>{x.date}</span></div><textarea aria-label={'Edit reflection '+x.date} rows={3} value={x.text} onChange={e=>update((l:any)=>l.entries.find((v:any)=>v.id===x.id).text=e.target.value)}/></article>)}{visibleEntries.length===0&&<p className="emptynote">A private place to think, without having to find the perfect words.</p>}</div></>}
function checkinPanel(numbered=false){return <section className="panel checkin"><div className="between"><div>{numbered?<SectionStepHeader step={1} title="Check In With Yourself">Notice your mood, energy and stress, then add what you need today. Every question is optional; your answers save as you make changes.</SectionStepHeader>:<><p className="eyebrow">A MOMENT FOR YOU</p><h2>How Are You Arriving Today?</h2></>}</div><span className="datecaption">{today}</span></div><div className="checkinfields">{[['mood','How do you feel?',[['unanswered','Choose if you like'],['good','Good'],['steady','Steady'],['low','Low'],['overwhelmed','Overwhelmed'],['mixed','Mixed']]],['energy','Your energy',[['unanswered','Choose if you like'],['low','Low'],['some','Some energy'],['high','Plenty of energy']]],['stress','Your stress',[['unanswered','Choose if you like'],['low','Low'],['moderate','Moderate'],['high','High']]]].filter(([k]:any)=>!simple||k==='mood').map(([k,label,options]:any)=><label className="field" key={k}><span>{label}</span><Choice label={label} value={checkin[k]||'unanswered'} options={options} onChange={(v:string)=>update((l:any)=>{l.checkins[today]??={};l.checkins[today][k]=v})}/></label>)}</div><label className="field"><span>What do you need today?</span><input className="textinput" value={checkin.need||''} placeholder="Rest, clarity, help, connection…" onChange={e=>update((l:any)=>{l.checkins[today]??={};l.checkins[today].need=e.target.value})}/></label><small>There is no score to reach.</small></section>}
function tasks(){return <section className="panel"><h2>Thoughts And Tasks</h2><p>Write down what is on your mind. Choose what to do when you feel ready.</p>{Capture}<div className="tasklist">{life.tasks.filter((t:any)=>wellbeingAreas.includes(t.aspect)&&!t.done&&t.action!=='letgo').map((t:any)=><div className="loaditem" key={t.id}><div className="loadtitle"><Checkbox aria-label={'Complete '+t.title} checked={t.done} onCheckedChange={v=>update((l:any)=>l.tasks.find((x:any)=>x.id===t.id).done=v===true)}/><input className="inlineinput" aria-label="Task title" value={t.title} onChange={e=>update((l:any)=>l.tasks.find((x:any)=>x.id===t.id).title=e.target.value)}/></div><div className="loadoptions"><Choice label={'Action for '+t.title} value={t.action} options={[['inbox','Sort later'],['do','Do'],['schedule','Schedule'],['help','Ask for help'],['letgo','Let go']]} onChange={(v:string)=>update((l:any)=>l.tasks.find((x:any)=>x.id===t.id).action=v)}/><Choice label={'Life area for '+t.title} value={t.aspect} options={areaOptions.filter(([id])=>wellbeingAreas.includes(id))} onChange={(v:string)=>update((l:any)=>l.tasks.find((x:any)=>x.id===t.id).aspect=v)}/>{t.action==='schedule'&&<input type="date" className="textinput" aria-label={'Schedule '+t.title} value={t.date} onChange={e=>update((l:any)=>l.tasks.find((x:any)=>x.id===t.id).date=e.target.value)}/>} {t.action==='help'&&<input className="textinput" aria-label={'Support for '+t.title} placeholder="Who could help? What will you ask?" value={t.support} onChange={e=>update((l:any)=>l.tasks.find((x:any)=>x.id===t.id).support=e.target.value)}/>}</div></div>)}</div>{life.tasks.length===0&&<p className="emptynote">You do not have to keep everything in your head.</p>}<details className="loadarchive"><summary>Completed & let go ({life.tasks.filter((t:any)=>wellbeingAreas.includes(t.aspect)&&(t.done||t.action==='letgo')).length})</summary>{life.tasks.filter((t:any)=>wellbeingAreas.includes(t.aspect)&&(t.done||t.action==='letgo')).map((t:any)=><div className="between archived" key={t.id}><span>{t.title}</span><button className="textbutton" onClick={()=>update((l:any)=>{const x=l.tasks.find((x:any)=>x.id===t.id);x.done=false;x.action='inbox'})}>Restore</button></div>)}</details></section>}
if(mode==='home')return <><BelongingWelcome name={p.profile.displayName}/><details className="panel startguide"><summary>New here? Start with one small step</summary><p>You do not need to finish every section. Choose what would help you today.</p><ol><li><b>My Wellbeing:</b> notice how you feel and write one reflection.</li><li><b>My Finances:</b> enter money coming in and your monthly costs.</li><li><b>My Health:</b> choose one small health goal. Trackers are optional.</li><li><b>Plan My Day:</b> choose one priority or add an appointment.</li></ol><p>Your personal entries are private. To talk with trusted people, open My Support Circle. You can come back to any section later.</p></details><div className="homefocus"><h2>A Little Space For You</h2><div className="gentlereminder"><span className="reminderheart"><Heart size={20} strokeWidth={1.5} aria-hidden="true"/></span><p>Choose what you need today.<em>One small step is enough.</em></p></div></div><div className="lifecards sectioncards">{[['wellbeing','My Wellbeing','Make room for your mind, heart and spirit.',Brain],['overview','My Finances','See what comes in, what goes out and what you can plan for.',Wallet],['health','My Health','Care for your body, in a way that feels right for you.',Activity],['shop','Shop Now','Discover women’s businesses, useful services and experiences to enjoy together.',ShoppingBag]].map(([id,name,description,Icon]:any)=><article className={"lifecard illustratedcard illustratedcard-"+id} key={id}>{['shop','overview'].includes(id)?<div className={id==='shop'?'shopartframe':'financeartframe'}><img loading="lazy" decoding="async" className="sectionart" src={"/illustrations/"+(id==='overview'?'blonde-welcome':id==='shop'?'classy-african-woman-headroom':id==='health'?'health-indian':id)+".webp"} alt="" width={400} height={260}/></div>:<img loading="lazy" decoding="async" className="sectionart" src={"/illustrations/"+(id==='overview'?'blonde-welcome':id==='shop'?'classy-african-woman-headroom':id==='health'?'health-indian':id)+".webp"} alt="" width={400} height={260}/>}<div className="illustratedcard-copy"><span className="sectionicon"><Icon size={18} aria-hidden="true"/></span><h2>{name}</h2><p>{description}</p><button className="primarybutton" onClick={()=>navigate(id)}>{id==='wellbeing'?'Make Room For Me':id==='overview'?'Plan My Money':id==='shop'?'Shop & Explore Together':'Care For My Body'}</button></div></article>)}</div><div className="belongingcircle"><div><Users size={22} aria-hidden="true"/><div><h3>A Little Connection Goes A Long Way.</h3><p>Your support circle is a place to listen, share and feel heard.</p></div></div><button className="secondary" onClick={()=>navigate('support')}>My Support Circle</button></div><aside className="dailyquote"><div><span className="eyebrow">A THOUGHT FOR TODAY</span><small>{quoteDate}</small></div><blockquote>“{dailyQuote(quoteDate)}”</blockquote><span className="quotecredit">Sovereign · Original reflections</span></aside><details className="panel optionaltools dayplanner"><summary><span className="dayplannericon"><CalendarDays size={24} strokeWidth={1.5} aria-hidden="true"/></span><span className="dayplannercopy"><span className="dayplannertitle">Plan My Day</span><span className="dayplannerprompt">A little space for your priorities and appointments.</span></span><ChevronDown className="dayplannerchevron" size={22} aria-hidden="true"/></summary><LifeHub mode="today" p={p} change={change} navigate={navigate}/></details></>;
if(mode==='wellbeing')return <div className="sectionworkspace wellbeingspace"><SectionWelcome area="wellbeing" eyebrow="MY WELLBEING" title="Come as you are."><p>A space for your mind, heart and spirit. Start with how you feel, and take what you need.</p><button className="calmbutton" onClick={()=>navigate('calm')}><Leaf size={18}/> I need a moment of calm</button></SectionWelcome><section className="sectionstep">{checkinPanel(true)}</section><section className="sectionstep panel">{journal(true)}</section><section className="sectionstep panel"><SectionStepHeader step={3} title="Choose A Little Support">Open whichever tool feels useful today: clear your mind, care for your spirit, choose a goal or reflect on your week. Your support circle is here when you want connection.</SectionStepHeader><details className="panel optionaltools"><summary>Clear my mind · thoughts and tasks</summary>{tasks()}</details><details className="panel optionaltools"><summary>Spiritual care · my personal practices</summary><LifeHub mode="area" area="spiritual" p={p} change={change} navigate={navigate} practicesOnly/></details><details className="panel optionaltools"><summary>My Wellbeing goals and next steps</summary><LifeHub mode="goals" p={p} change={change} navigate={navigate}/></details><details className="panel optionaltools"><summary>Weekly reflection</summary><LifeHub mode="weekly" p={p} change={change} navigate={navigate}/></details><button className="secondary supportcirclebutton" onClick={()=>navigate('support')}>Open My Support Circle</button></section></div>;
if(mode==='today')return <><div className="sectionheading"><div><p className="eyebrow">TODAY · {today}</p><h2>A Manageable Day, On Your Terms.</h2></div><button className="calmbutton" onClick={()=>navigate('calm')}><Leaf size={18} aria-hidden="true"/>Take a moment of calm</button></div><div className="split"><section className="panel"><h2>Three Priorities Are Enough</h2><p>Leave space for life. Blank priorities are welcome.</p>{[0,1,2].map(i=>{const v=(life.priorities[today]||[])[i]||{text:'',done:false};return <div className="priority" key={i}><span>{String(i+1).padStart(2,'0')}</span><Checkbox aria-label={'Complete priority '+(i+1)} checked={v.done} onCheckedChange={done=>update((l:any)=>{l.priorities[today]??=[];l.priorities[today][i]={...v,done:done===true}})}/><input aria-label={'Priority '+(i+1)} className={'textinput '+(v.done?'finished':'')} value={v.text} placeholder="One thing that matters" onChange={e=>update((l:any)=>{l.priorities[today]??=[];l.priorities[today][i]={...v,text:e.target.value}})}/></div>})}<label className="field personalreminder"><span>A reminder to yourself</span><textarea rows={3} value={life.reminders[today]||''} placeholder="You can ask for help. You can change the plan." onChange={e=>update((l:any)=>l.reminders[today]=e.target.value)}/></label></section><section className="panel"><h2>Appointments & Commitments</h2>{life.appointments.filter((x:any)=>x.date>=today).sort((a:any,b:any)=>(a.date+a.time).localeCompare(b.date+b.time)).map((x:any)=><div className="commitment" key={x.id}><Checkbox aria-label={'Complete '+x.name} checked={x.done} onCheckedChange={v=>update((l:any)=>l.appointments.find((a:any)=>a.id===x.id).done=v===true)}/><div><b className={x.done?'finished':''}>{x.name}</b><small>{x.date} {x.time}</small></div></div>)}<form className="healthform" onSubmit={e=>{e.preventDefault();if(!appt.trim()||!apptDate)return;update((l:any)=>l.appointments.push({id:crypto.randomUUID(),name:appt.trim(),date:apptDate,time:apptTime,done:false}));setAppt('')}}><label className="field"><span>Commitment</span><input required className="textinput" value={appt} onChange={e=>setAppt(e.target.value)} placeholder="Appointment, family time, or personal time"/></label><div className="twofields"><label className="field"><span>Date</span><input required className="textinput" type="date" value={apptDate} onChange={e=>setApptDate(e.target.value)}/></label><label className="field"><span>Time (optional)</span><input className="textinput" type="time" value={apptTime} onChange={e=>setApptTime(e.target.value)}/></label></div><button className="primarybutton">Add commitment</button></form></section></div><section className="panel"><h2>Ready For Attention</h2>{life.tasks.filter((t:any)=>!t.done&&(t.action==='do'||t.action==='schedule'&&t.date&&t.date<=today)).map((t:any)=><div className="commitment" key={t.id}><Checkbox aria-label={'Complete '+t.title} checked={t.done} onCheckedChange={v=>update((l:any)=>l.tasks.find((x:any)=>x.id===t.id).done=v===true)}/><span>{t.title}</span></div>)}<button className="textbutton" onClick={()=>navigate('wellbeing')}>Open wellbeing</button></section></>;
if(mode==='calm')return <section className="panel calmspace"><Leaf size={32}/><p className="eyebrow">ONE THING AT A TIME</p><h1>You can pause here.</h1><p>You do not have to solve everything in this moment.</p><h2>Put Down What Is On Your Mind.</h2>{Capture}<h2>Choose One Small Next Step.</h2><label className="field"><span>What feels manageable right now?</span><input className="textinput" value={life.reminders[today+'-next']||''} onChange={e=>update((l:any)=>l.reminders[today+'-next']=e.target.value)} placeholder="A glass of water. One phone call. A short rest."/></label><h2>You Can Ask For Support.</h2><label className="field"><span>Who could help, and what do you need?</span><textarea rows={3} value={life.reminders[today+'-support']||''} onChange={e=>update((l:any)=>l.reminders[today+'-support']=e.target.value)} placeholder="Write the person and a specific request."/></label><button className="primarybutton" onClick={()=>navigate('today')}>Return to my day</button></section>;
if(mode==='journal'||mode==='weekly')return <><div className="journalnav" hidden={mode==='weekly'}><button className={reflectionTab==='journal'?'active':''} onClick={()=>setReflectionTab('journal')}>Reflections</button><button className={reflectionTab==='weekly'?'active':''} onClick={()=>setReflectionTab('weekly')}>Weekly review</button></div><section className="panel">{reflectionTab==='journal'?journal():<><div className="between"><div><p className="eyebrow">WEEK OF {week}</p><h2>A Gentle Look Back</h2></div><label className="field"><span>Choose a date in your week</span><input className="textinput" type="date" value={journalDate} onChange={e=>e.target.value&&setJournalDate(e.target.value)}/></label></div><div className="reviewfields">{[['wentwell','What went well?'],['heavy','What felt heavy?'],['change','What can change next week?'],['support','What support do you need?']].map(([k,label])=><label className="field" key={k}><span>{label}</span><textarea rows={3} value={review[k]||''} onChange={e=>update((l:any)=>{l.reviews[week]??={};l.reviews[week][k]=e.target.value})}/></label>)}</div><small>Saved as you write. No streaks. No catching up required.</small></>}</section></>;
if(mode==='goals')return <section className="panel"><p className="eyebrow">PURPOSEFUL PROGRESS</p><h2>My Wellbeing Goals</h2><p>Choose a meaningful next step, not a perfect version of yourself.</p>{life.goals.filter((g:any)=>wellbeingAreas.includes(g.area)).map((g:any)=><div className="healthgoal" key={g.id}><Checkbox aria-label={'Complete '+g.name} checked={g.done} onCheckedChange={v=>update((l:any)=>l.goals.find((x:any)=>x.id===g.id).done=v===true)}/><div><input className="inlineinput" aria-label="Life goal" value={g.name} onChange={e=>update((l:any)=>l.goals.find((x:any)=>x.id===g.id).name=e.target.value)}/><input className="inlineinput targettext" aria-label="Goal next step" value={g.target} onChange={e=>update((l:any)=>l.goals.find((x:any)=>x.id===g.id).target=e.target.value)}/><small>{aspects.find(a=>a.id===g.area)?.name}</small></div><input type="date" className="textinput" aria-label="Life goal date" value={g.date} onChange={e=>update((l:any)=>l.goals.find((x:any)=>x.id===g.id).date=e.target.value)}/></div>)}<form className="healthform" onSubmit={e=>{e.preventDefault();if(!goal.trim())return;update((l:any)=>l.goals.push({id:crypto.randomUUID(),name:goal.trim(),target,date:goalDate,area:goalArea,done:false}));setGoal('');setTarget('');setGoalDate('')}}><div className="twofields"><label className="field"><span>Your goal</span><input required className="textinput" value={goal} onChange={e=>setGoal(e.target.value)}/></label><label className="field"><span>Life area</span><Choice label="Goal life area" value={goalArea} options={areaOptions.filter(([id])=>!['finances','physical'].includes(id))} onChange={setGoalArea}/></label></div><div className="twofields"><label className="field"><span>One small next step</span><input className="textinput" value={target} onChange={e=>setTarget(e.target.value)}/></label><label className="field"><span>Target date (optional)</span><input className="textinput" type="date" value={goalDate} onChange={e=>setGoalDate(e.target.value)}/></label></div><button className="primarybutton">Add wellbeing goal</button></form></section>;
const aspect=aspects.find(x=>x.id===area)!;return <>{!practicesOnly&&<div className="sectionheading"><div><p className="eyebrow">MY LIFE</p><h2>{aspect.name}</h2></div><button className="textbutton" onClick={()=>navigate('home')}>Back to My Life</button></div>}{area==='mental'&&checkinPanel()}{area==='spiritual'&&<section className="panel"><h2>Your Spiritual Practices</h2><p>This space is optional. Choose what gives you meaning, whether you follow a faith or no religion.</p>{life.spiritualPractices.map((v:any,i:number)=><div className="commitment" key={v.id}><Checkbox aria-label={'Practised '+v.name+' today'} checked={(v.dates||[]).includes(today)} onCheckedChange={checked=>update((l:any)=>l.spiritualPractices[i].dates=checked?[...v.dates,today]:v.dates.filter((d:string)=>d!==today))}/><input className="inlineinput" aria-label="Spiritual practice" value={v.name} onChange={e=>update((l:any)=>l.spiritualPractices[i].name=e.target.value)}/></div>)}<form className="capture" onSubmit={e=>{e.preventDefault();if(!practice.trim())return;update((l:any)=>l.spiritualPractices.push({id:crypto.randomUUID(),name:practice.trim(),dates:[]}));setPractice('')}}><input aria-label="New spiritual practice" value={practice} onChange={e=>setPractice(e.target.value)} placeholder="Prayer, reflection, quiet time, gratitude…"/><button className="primarybutton">Add practice</button></form></section>}{area==='relationships'&&tasks()}{!practicesOnly&&<section className="panel">{journal()}</section>}</>;
}
