/* ==========================================================================
 * ADMIN NEXT — page-topdep.jsx  (แยกไฟล์ละหน้า; โหลดผ่าน <script type="text/babel">)
 * ========================================================================== */

/* ---------- 20 อันดับฝากสูงสุด — /reports/top-depositors ---------- */
function TopDepositorsPage({ toast }) {
  const [rows,setRows]=useState([]),[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); const d=await api("/reports/top-depositors?from="+from+"&to="+to); setRows(Array.isArray(d)?d:[]); }
    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 doExport=()=>{ csvDownload("top-depositors-"+bkkDate(0)+".csv",[["อันดับ","ยูส","ชื่อสมาชิก","เบอร์","ยอดฝากรวม(บาท)","จำนวนครั้ง"],...rows.map((r,i)=>[i+1,r.username,r.full_name,r.phone,(Number(r.total_amount||0)/100).toFixed(2),r.deposit_count])]); toast("ส่งออกแล้ว"); };
  return (<div className="space-y-3">
    <HistToolbar range={range} setRange={setRange} custom={custom} setCustom={setCustom} onReload={()=>load(range,custom)} onExport={doExport} loading={loading} count={rows.length}/>
    {err ? <HistErr msg={err} onRetry={()=>load(range,custom)}/>
    : (<div className="overflow-hidden rounded-xl border border-line bg-surface shadow-sm"><div className="overflow-x-auto"><table className="w-full min-w-[640px] border-collapse text-sm">
      <thead className="border-b-2 border-accent/25 bg-accent-soft"><tr>{histTh("อันดับ")}{histTh("สมาชิก")}{histTh("จำนวนครั้ง","text-right")}{histTh("ยอดฝากรวม","text-right pr-4")}</tr></thead>
      <tbody>
        {loading ? Array.from({length:8}).map((_,i)=>(<tr key={i} className="border-b border-line-soft"><td className="px-3 py-3" colSpan="4"><div className="skel h-5 w-full"/></td></tr>))
          : rows.length===0 ? (<tr><td colSpan="4" className="px-4 py-16 text-center text-sm font-medium text-fg-2">ไม่มีข้อมูล</td></tr>)
          : rows.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"><span className="grid h-6 w-6 place-items-center rounded-full text-[11px] font-bold" style={{background:i<3?"var(--warn-soft)":"var(--sunken)",color:i<3?"var(--warn)":"var(--muted)"}}>{i+1}</span></td>
            <td className="px-3"><div className="flex items-center gap-2.5"><div className="grid h-8 w-8 shrink-0 place-items-center rounded-full text-sm font-semibold text-white" style={{background:avc(r.username||r.full_name)}}>{initials(r.username||r.full_name)}</div><div className="min-w-0"><div className="truncate font-semibold text-accent">{r.username||r.full_name||"-"}</div><div className="truncate text-[11px] text-muted">{r.full_name&&r.full_name!==r.username?r.full_name+" · ":""}{r.phone||"-"}</div></div></div></td>
            <td className="px-3 text-right tnum text-muted">{Number(r.deposit_count||0).toLocaleString()}</td>
            <td className="pr-4 text-right font-semibold tnum text-success">{money2(r.total_amount)}</td>
          </tr>))}
      </tbody>
    </table></div></div>)}
  </div>);
}
