'use client';
import {SectionStepHeader} from '@/components/section-step-header';
import {SectionWelcome} from '@/components/section-welcome';
import {Checkbox} from '@/components/ui/checkbox';
import {SimpleIncome} from '@/components/simple-income';
import {BudgetImport} from '@/components/budget-import';
import {FinancialGoals} from '@/components/financial-goals';
import {MonthlyRoadmap} from '@/components/finance-summary';
import {FinancialProgress} from '@/components/financial-progress';
import {FinanceExport} from '@/components/finance-export';
import {FinanceStory} from '@/components/finance-story';
import {financialPurpose} from '@/lib/financial-goals';
const money=(v:number)=>new Intl.NumberFormat('en-ZA',{style:'currency',currency:'ZAR',maximumFractionDigits:0}).format(v);
function Amount({label,value,onChange}:any){return <label className="field"><span>{label}</span><div className="number"><span>R</span><input aria-label={label} type="number" min={0} value={value} onChange={e=>{const n=Number(e.target.value);if(Number.isFinite(n)&&n>=0)onChange(n);}}/></div></label>}
export function FinanceWorkspace({p,state,change,scenario,onScenarioChange,saveNow,saveStatus}:any){const total=p.budget.reduce((s:number,b:any)=>s+b.amount,0);
function scrollTo(id:string){const section=document.getElementById(id);if(section instanceof HTMLDetailsElement)section.open=true;section?.scrollIntoView({behavior:'smooth',block:'start'});section?.focus({preventScroll:true});}
function navigate(section:string){if(section==='budget')scrollTo('finance-budget');else if(section==='monthly')scrollTo('finance-monthly');else scrollTo('finance-goals');}
return <div className="sectionworkspace financeworkspace"><SectionWelcome area="finances" eyebrow="MY FINANCES" title="Your dreams deserve a little room."><p>Start with what you have. Shape a plan around the life you want, one small step at a time.</p><p className="note">{financialPurpose}</p></SectionWelcome><FinanceStory state={state} overviewOnly/><section id="finance-budget" tabIndex={-1} className="financesection"><div className="panel"><SectionStepHeader step={1} title="Your Money Each Month">Upload a simple budget spreadsheet, or enter your income and expenses in Edit My Budget below. Check the amounts before moving to your goals.</SectionStepHeader><button className="secondary" onClick={()=>scrollTo('finance-budget-editor')}>Enter Or Edit My Budget</button></div><BudgetImport p={p} change={change} inputId="finance-excel-file" onApplied={()=>scrollTo('finance-budget')}/><details id="finance-budget-editor" tabIndex={-1} className="panel budgeteditor"><summary>Edit My Budget</summary><div className="split"><SimpleIncome p={p} change={change}/><section className="panel"><h2>Monthly Expenses</h2><p>Include your current loan payments in Debt repayments, then add your other costs.</p>{p.budget.map((b:any,i:number)=><div className="budgetrow" key={i}><input className="name" disabled={i===0} aria-label={'Expense name '+(i+1)} value={b.name} onChange={e=>change((x:any)=>x.budget[i].name=e.target.value)}/><Amount label={b.name+' amount'} value={b.amount} onChange={(v:number)=>change((x:any)=>x.budget[i].amount=v)}/><label className="billdue"><span>Due day (optional)</span><input aria-label={b.name+' bill due day'} type="number" min={1} max={31} value={b.dueDay??''} placeholder="—" onChange={e=>{const v=e.target.value;if(v===''||Number.isInteger(Number(v))&&Number(v)>=1&&Number(v)<=31)change((x:any)=>{if(v==='')delete x.budget[i].dueDay;else x.budget[i].dueDay=Number(v);});}}/></label>{i>0&&<button className="remove" aria-label={'Remove '+b.name} onClick={()=>change((x:any)=>x.budget.splice(i,1))}>×</button>}</div>)}<button className="secondary" onClick={()=>change((x:any)=>x.budget.push({name:'New expense',amount:0}))}>+ Add expense</button><div className="total"><b>Total monthly expenses</b><strong>{money(total)}</strong></div></section></div></details><details className="panel"><summary>Optional monthly set-asides</summary><p>Choose your own names for the things you want to put money aside for. The examples are only suggestions. Monthly amounts are included before funding your goals.</p><div className="debtgrid">{p.funds.map((f:any,i:number)=><div className="debt" key={i}><label className="field"><span>What Are You Putting Money Aside For?</span><input className="textinput fundname" aria-label={"Set-aside name "+(i+1)} maxLength={120} value={f.name} placeholder={["e.g. A holiday","e.g. Home improvements","e.g. Personal care","e.g. Hobbies or days out","e.g. Unexpected costs","e.g. Growing my business"][i%6]} onChange={e=>change((x:any)=>x.funds[i].name=e.target.value)}/></label>{[['amount','Monthly amount'],['balance','Current balance'],['spent','Spent this year']].map(([key,label])=><Amount key={key} label={label} value={f[key]} onChange={(v:number)=>change((x:any)=>x.funds[i][key]=v)}/>)}</div>)}</div></details></section><div className="financesavebar"><button className="primarybutton" disabled={saveStatus==='Saving…'} onClick={saveNow}>Save My Budget</button><span role="status">{saveStatus}</span></div><FinancialGoals p={p} change={change} navigate={navigate} scenario={scenario} onScenarioChange={onScenarioChange} compact/>{!state.errors.length&&<details id="finance-monthly" tabIndex={-1} className="panel"><summary>See or update the monthly roadmap</summary><MonthlyRoadmap p={p} state={state} change={change} navigate={navigate}/></details>}<details className="panel"><summary>Other financial milestones (optional)</summary><section className="panel"><h2>Other Financial Milestones (Optional)</h2><p>Track other reminders here. The calculated route above uses the debts and savings goals you entered.</p>{p.goals.map((g:any,i:number)=><div className={'goal '+(g.done?'done':'')} key={i}><Checkbox aria-label={'Complete '+g.name} checked={g.done} onCheckedChange={v=>change((x:any)=>x.goals[i].done=v===true)}/><div className="goaltext"><input aria-label={'Goal '+(i+1)} value={g.name} onChange={e=>change((x:any)=>x.goals[i].name=e.target.value)}/><small>{g.notes}</small></div><input aria-label={g.name+' target date'} type="date" value={g.date} onChange={e=>change((x:any)=>x.goals[i].date=e.target.value)}/><Amount label={g.name+' target amount'} value={g.amount} onChange={(v:number)=>change((x:any)=>x.goals[i].amount=v)}/></div>)}</section><button className="primarybutton" onClick={()=>change((x:any)=>x.goals.push({name:"New life goal",date:"",amount:0,done:false,notes:""}))}>+ Add financial milestone</button></details><FinancialProgress p={p} state={state} change={change} navigate={navigate}/><FinanceStory state={state}/><div className="financesavebar"><button className="primarybutton" disabled={saveStatus==='Saving…'} onClick={saveNow}>Save My Financial Roadmap</button><span role="status">{saveStatus}</span></div><FinanceExport p={p} scenario={scenario}/></div>;
}
