/* ===== Premium billing (ชำระเบี้ย): per-policy + expand per person + paid ===== */
const { useState:useStatePB } = React;

const PremiumBilling = ({back, go, toast}) => {
  const [mode,setMode]=useStatePB('policy'); // 'policy' | 'person'
  const [paid,setPaid]=useStatePB({});       // id → true
  const [exp,setExp]=useStatePB({});          // customer name → open
  // only near-due / due (within 30 days or overdue), reuse RENEWALS
  const items=RENEWALS.filter(r=>r.days<=30);
  const togglePaid=(id)=>{ setPaid(p=>({...p,[id]:!p[id]})); toast(paid[id]?'ยกเลิกการชำระ':'ทำเครื่องหมายชำระแล้ว'); };
  const totalDue=items.filter(r=>!paid[r.id]).reduce((a,r)=>a+r.prem,0);
  const paidSum=items.filter(r=>paid[r.id]).reduce((a,r)=>a+r.prem,0);

  // group by person
  const byPerson={}; items.forEach(r=>{ (byPerson[r.cust]=byPerson[r.cust]||[]).push(r); });

  const PaidCheck=({r})=>(
    <button className={"paidbox"+(paid[r.id]?" on":"")} onClick={()=>togglePaid(r.id)}>
      {paid[r.id]?<><Icon name="check" size={15}/> ชำระแล้ว</>:'ทำเครื่องหมายชำระ'}
    </button>
  );

  const policyRow=(r,showCust=true)=>{
    const co=COMPANIES.find(c=>c.id===r.co); const overdue=r.days<0; const isPaid=paid[r.id];
    return (
      <div key={r.id} className="card" style={{padding:15,display:'flex',gap:13,alignItems:'center',opacity:isPaid?.62:1,borderLeft:`4px solid ${isPaid?'var(--ok)':overdue?'var(--danger)':'var(--warn)'}`}}>
        <CompanyBadge co={co}/>
        <div style={{flex:1,minWidth:0}}>
          <div style={{fontSize:14.5,fontWeight:700}}>{r.plan}{showCust&&` · ${r.cust}`}</div>
          <div style={{fontSize:12.5,color:'var(--muted)',marginTop:2}}>{co.name} · {maskPolicy(r.no)} · ครบกำหนด {r.due} {overdue?`(เกิน ${-r.days} วัน)`:`(อีก ${r.days} วัน)`}</div>
        </div>
        <div style={{textAlign:'right'}}>
          <div style={{fontSize:15.5,fontWeight:800}}>{THB(r.prem)}</div>
          <div style={{fontSize:11,color:'var(--muted)'}}>{r.freq}</div>
        </div>
        <PaidCheck r={r}/>
      </div>
    );
  };

  return (
    <div className="screen">
      <StatusBar/>
      <AppBar onBack={back} title="ชำระเบี้ย" sub="ติดตามการชำระเบี้ยใกล้ครบกำหนด"
        right={<button className="iconbtn" onClick={()=>go('notifications')} style={{position:'relative'}}><Icon name="bell" size={23}/><span style={{position:'absolute',top:9,right:10,width:9,height:9,borderRadius:9,background:'var(--gold)',border:'2px solid #fff'}}/></button>}/>
      <div className="scroll">
        <div className="pad maxw" style={{paddingTop:4}}>
          <div className="grid2 stagger" style={{gridTemplateColumns:'repeat(3,1fr)'}}>
            <KPI icon="wallet" val={THBshort(totalDue)} label="ยังไม่ชำระ" color="#f59e0b" bg="var(--warn-50)"/>
            <KPI icon="checkCircle" val={THBshort(paidSum)} label="ชำระแล้ว" color="#16a34a" bg="var(--ok-50)"/>
            <KPI icon="doc" val={items.length} label="กรมธรรม์ครบกำหนด" color="#1e40af" bg="var(--navy-50)"/>
          </div>

          <div className="flexrow" style={{margin:'16px 0 14px'}}>
            <div className="seg" style={{width:280}}>
              <button className={"opt"+(mode==='policy'?" active":"")} onClick={()=>setMode('policy')}>รายกรมธรรม์</button>
              <button className={"opt"+(mode==='person'?" active":"")} onClick={()=>setMode('person')}>รายลูกค้า</button>
            </div>
            <div className="spacer"/>
            <span className="chip gray">รวม {THBshort(totalDue+paidSum)}</span>
          </div>

          {mode==='policy' ? (
            <div className="stack" style={{gap:12}}>
              {items.map(r=>policyRow(r,true))}
            </div>
          ) : (
            <div className="stack" style={{gap:12}}>
              {Object.entries(byPerson).map(([cust,arr])=>{
                const open=exp[cust]; const sum=arr.reduce((a,r)=>a+r.prem,0);
                const unpaid=arr.filter(r=>!paid[r.id]).length;
                const c=CUSTOMERS.find(x=>x.name===cust);
                return (
                  <div key={cust} className="card" style={{padding:0,overflow:'hidden'}}>
                    <button className="flexrow" style={{width:'100%',gap:13,padding:16,textAlign:'left'}} onClick={()=>setExp(e=>({...e,[cust]:!e[cust]}))}>
                      <Avatar name={cust} color={c?c.avatar:'#1e40af'} size="sm"/>
                      <div style={{flex:1,minWidth:0}}>
                        <div style={{fontSize:15,fontWeight:700}}>{cust}</div>
                        <div style={{fontSize:12.5,color:'var(--muted)'}}>{arr.length} กรมธรรม์ · {unpaid>0?`ค้างชำระ ${unpaid}`:'ชำระครบแล้ว'}</div>
                      </div>
                      <b style={{fontSize:15}}>{THB(sum)}</b>
                      <Icon name="chevD" size={20} c="var(--muted-2)" style={{transform:open?'rotate(180deg)':'none',transition:'.2s'}}/>
                    </button>
                    {open && (
                      <div style={{padding:'0 16px 16px',borderTop:'1px solid var(--line-2)'}}>
                        <div className="stack" style={{gap:10,marginTop:12}}>
                          {arr.map(r=>policyRow(r,false))}
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          )}
          <div style={{height:10}}/>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { PremiumBilling });
