(() => {
  const {useState,useEffect}=React,api=(method,path,body)=>window.NGM.api(method,'/rich-life'+path,body);
  const money=n=>typeof n==='number'?n.toLocaleString('en-US',{style:'currency',currency:'USD'}):'Unavailable';
  function Bills(){
    const [bills,setBills]=useState([]),[accounts,setAccounts]=useState([]),[account,setAccount]=useState(''),[proposal,setProposal]=useState(null),[matches,setMatches]=useState(null),[checked,setChecked]=useState(false),[busy,setBusy]=useState(false),[message,setMessage]=useState('');
    const load=async()=>{try{const [bs,s]=await Promise.all([window.NGM.api('GET','/bills'),api('GET','/snapshot')]);setBills(bs);const ac=s.accounts.filter(a=>a.selected);setAccounts(ac);setAccount(a=>a||ac[0]?.id||'');}catch(e){setMessage(e.message);}};
    useEffect(()=>{load();},[]);
    const action=async fn=>{setBusy(true);setMessage('');try{await fn();}catch(e){setMessage(e.message);}finally{setBusy(false);}};
    return <div className="rich-life ngm-controls"><p>Review bills, prepare a payment plan, and match completed payments to bank records.</p><section className="rl-panel"><h2>Payment connection</h2><p>Direct payment submission is not configured. Pay through your bank or biller, then reconcile the posted transaction here. Check existing autopay before making any payment.</p><label>Funding account for proposals<select value={account} onChange={e=>setAccount(e.target.value)}><option value="">Choose a plan account</option>{accounts.map(a=><option key={a.id} value={a.id}>{a.name}</option>)}</select></label></section><p role="status">{busy?'Working…':message}</p>
    {proposal&&<section className="rl-panel"><h2>Review payment plan</h2><p>{proposal.payee} · {money(proposal.amount)} · due {proposal.dueDate}</p><p>From {proposal.accountName}. Fees and arrival time must be checked with your bank or biller.</p><label className="rl-check"><input type="checkbox" checked={checked} onChange={e=>setChecked(e.target.checked)}/>I checked existing autopay and want to approve this exact payment plan.</label><button disabled={busy||!checked} onClick={()=>action(async()=>{await api('POST',`/bills/${proposal.billId}/approve`,{proposalId:proposal.id,confirmed:true,checkedAutopay:true});setProposal(null);setMessage('Payment plan approved. Complete payment through your bank or biller. NoGuilt has not submitted a payment.');})}>Approve for bank/biller handoff</button> <button onClick={()=>setProposal(null)}>Cancel</button></section>}
    {matches&&<section className="rl-panel"><h2>Match a completed payment</h2><p>Confirmation is awaiting permission setup. You can inspect suggested matches below.</p><p>{matches.message}</p>{matches.matches.length?matches.matches.map(t=><div className="rl-row" key={t.id}><span>{t.merchant} · {t.date} · {money(t.amount)}</span><button disabled={true} title="Awaiting permission setup" onClick={()=>action(async()=>{await api('POST',`/bills/${matches.billId}/reconcile`,{txnId:t.id,confirmed:true});setMatches(null);setMessage('Posted payment matched. No new payment was made.');await load();})}>Confirm this paid the bill</button></div>):<p>No matching posted transaction found. Wait for your bank to post it or review the amount and date.</p>}<button onClick={()=>setMatches(null)}>Close</button></section>}
    {bills.map(b=><section className="rl-panel" key={b.instanceId||b.id}><div className="rl-row"><span><strong>{b.biller}</strong><small>{b.dueDate||'Due date needed'} · {b.state||'Needs review'}</small></span><strong>{money(b.amount)}</strong></div><button disabled={busy||!account} onClick={()=>action(async()=>{setChecked(false);setProposal(await api('POST',`/bills/${b.id}/proposal`,{accountId:account}));})}>Review payment plan</button> <button disabled={busy||!b.instanceId} onClick={()=>action(async()=>setMatches(await api('GET',`/bills/${b.id}/matches`)))}>Match bank payment</button></section>)}{!bills.length&&<p>No bills found. Upload a bill in Library to get started.</p>}</div>;
  }
  window.BillPayQueue=Bills;
})();
