/* ==========================================================================
 * ADMIN NEXT — page-promosummary.jsx  (รายงานสรุปโปรโมชั่น/โบนัส)
 * ========================================================================== */
function PromoSummaryPage({ toast }) {
  const [d,setD]=useState(null),[loading,setLoading]=useState(true),[err,setErr]=useState(null);
  const [range,setRange]=useState("30d"),[custom,setCustom]=useState({from:bkkDate(29),to:bkkDate(0)});
  const load=useCallback(async(rg,cust)=>{ setLoading(true); setErr(null);
    try{ const {from,to}=rangeToDates(rg,cust); setD(await api("/reports/promotion-summary?from="+from+"&to="+to)); }
    catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail&&window.__nxAuthFail();} setErr(e.status===403?"ไม่มีสิทธิ์ดูรายงานโปรโมชั่น":(e.message||"โหลดไม่สำเร็จ")); }
    finally{ setLoading(false); } },[]);
  useEffect(()=>{ load(range,custom); },[range,load]);
  const promos=(d&&d.promos)||[], t=(d&&d.totals)||{}, cb=(d&&d.cashback)||{}, rf=(d&&d.referral)||{};
  const doExport=()=>{ csvDownload("promo-summary-"+bkkDate(0)+".csv",[["โปรโมชั่น","โค้ด","จำนวนรับ","ยอดฝากรวม(บาท)","โบนัสรวม(บาท)","เคลียร์แล้ว","ถอนรวม(บาท)"],...promos.map(r=>[r.name,r.code,r.claims,(Number(r.deposit_total||0)/100).toFixed(2),(Number(r.bonus_total||0)/100).toFixed(2),r.cleared,(Number(r.withdraw_total||0)/100).toFixed(2)])]); toast("ส่งออกแล้ว"); };
  return (<div className="space-y-4">
    <HistToolbar range={range} setRange={setRange} custom={custom} setCustom={setCustom} onReload={()=>load(range,custom)} onExport={doExport} loading={loading} count={promos.length}/>
    {err ? <HistErr msg={err} onRetry={()=>load(range,custom)}/> : (<>
      <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
        <StatMini k="จำนวนรับโปร" v={loading?"…":Number(t.claims||0).toLocaleString()} sub={promos.length+" โปร"}/>
        <StatMini k="ยอดฝากรวม" v={loading?"…":money2(t.deposit_total)} color="var(--success)"/>
        <StatMini k="โบนัสรวม" v={loading?"…":money2(t.bonus_total)} color="var(--warn)"/>
        <StatMini k="ถอนรวม (โปร)" v={loading?"…":money2(t.withdraw_total)} color="var(--danger)"/>
      </div>
      <div className="grid grid-cols-2 gap-3">
        <StatMini k="คืนยอดเสียที่จ่าย" v={loading?"…":money2(cb.total)} sub={Number(cb.claims||0)+" เคลม"} color="var(--accent)"/>
        <StatMini k="คอมชวนเพื่อน" v={loading?"…":money2(rf.total)} sub={Number(rf.rewards||0)+" รายการ"} color="var(--info)"/>
      </div>
      <div className="overflow-hidden rounded-xl border border-line bg-surface shadow-sm"><div className="overflow-x-auto"><table className="w-full min-w-[820px] border-collapse text-sm">
        <thead className="border-b-2 border-accent/25 bg-accent-soft"><tr>{histTh("โปรโมชั่น")}{histTh("จำนวนรับ","text-right")}{histTh("ยอดฝากรวม","text-right")}{histTh("โบนัสรวม","text-right")}{histTh("เคลียร์แล้ว","text-right")}{histTh("ถอนรวม","text-right pr-4")}</tr></thead>
        <tbody>
          {loading ? Array.from({length:6}).map((_,i)=>(<tr key={i} className="border-b border-line-soft"><td className="px-3 py-3" colSpan="6"><div className="skel h-5 w-full"/></td></tr>))
            : promos.length===0 ? (<tr><td colSpan="6" className="px-4 py-16 text-center text-sm font-medium text-fg-2">ไม่มีข้อมูล</td></tr>)
            : promos.map((r,i)=>(<tr key={r.id||i} className="border-b border-line-soft transition-colors last:border-0 hover:bg-sunken/50">
              <td className="px-3 py-2.5"><div className="min-w-0"><div className="truncate font-medium text-fg">{r.name||"-"}</div>{r.code&&<div className="truncate mono text-[11px] text-faint">{r.code}</div>}</div></td>
              <td className="px-3 text-right tnum text-muted">{Number(r.claims||0).toLocaleString()}</td>
              <td className="whitespace-nowrap px-3 text-right tnum text-success">{money2(r.deposit_total)}</td>
              <td className="whitespace-nowrap px-3 text-right font-semibold tnum text-warn">{money2(r.bonus_total)}</td>
              <td className="px-3 text-right tnum text-muted">{Number(r.cleared||0).toLocaleString()}</td>
              <td className="whitespace-nowrap px-3 text-right tnum text-danger pr-4">{money2(r.withdraw_total)}</td>
            </tr>))}
        </tbody>
      </table></div></div>
    </>)}
  </div>);
}
