/* ==========================================================================
 * ADMIN NEXT — page-affiliatehist.jsx  (ประวัติคอมมิชชั่นพันธมิตร)
 * ========================================================================== */
const AFF_TXTYPE={ deposit:"ฝากเงิน", turnover:"เทิร์นโอเวอร์", register:"สมัครสมาชิก", affiliate_bonus:"โบนัสพันธมิตร" };
function AffiliateHistoryPage({ toast }) {
  const [rows,setRows]=useState([]),[loading,setLoading]=useState(true),[err,setErr]=useState(null);
  const [q,setQ]=useState(""),[range,setRange]=useState("30d"),[custom,setCustom]=useState({from:bkkDate(29),to:bkkDate(0)});
  const [page,setPage]=useState(1),[size,setSize]=useState(50);
  const debRef=useRef(null);
  const load=useCallback(async(query,rg,cust)=>{ setLoading(true); setErr(null);
    try{ const {from,to}=rangeToDates(rg,cust); const p=new URLSearchParams({limit:"300",from,to}); if(query)p.set("q",query);
      const d=await api("/affiliate/history?"+p.toString()); setRows((d&&d.rows)||(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(q.trim(),range,custom); },[range,load]);
  useEffect(()=>{ if(debRef.current)clearTimeout(debRef.current); debRef.current=setTimeout(()=>load(q.trim(),range,custom),350); return ()=>clearTimeout(debRef.current); },[q]);
  useEffect(()=>{ setPage(1); },[q,range,rows.length]);
  const paged=rows.slice((page-1)*size,page*size);
  const doExport=()=>{ csvDownload("affiliate-history-"+bkkDate(0)+".csv",[["เวลา","ผู้แนะนำ","ผู้ถูกแนะนำ","ชั้น","ประเภท","เครดิต(บาท)"],...rows.map(r=>[fmtDT(r.created_at),r.invitor_username,r.invitee_username,r.level,AFF_TXTYPE[r.source_tx_type]||r.source_tx_type||"",(Number(r.credit||0)/100).toFixed(2)])]); toast("ส่งออกแล้ว"); };
  return (<div className="space-y-3">
    <HistToolbar q={q} setQ={setQ} range={range} setRange={setRange} custom={custom} setCustom={setCustom} onReload={()=>load(q.trim(),range,custom)} onExport={doExport} loading={loading} count={rows.length} placeholder="ค้นหา ผู้แนะนำ / ผู้ถูกแนะนำ…"/>
    {err ? <HistErr msg={err} onRetry={()=>load(q.trim(),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-[780px] border-collapse text-sm">
      <thead className="border-b-2 border-accent/25 bg-accent-soft"><tr>{histTh("เวลา")}{histTh("ผู้แนะนำ")}{histTh("ผู้ถูกแนะนำ")}{histTh("ชั้น","text-center")}{histTh("ประเภท")}{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="6"><div className="skel h-5 w-full"/></td></tr>))
          : rows.length===0 ? (<tr><td colSpan="6" className="px-4 py-16 text-center text-sm font-medium text-fg-2">ไม่มีรายการ</td></tr>)
          : paged.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="whitespace-nowrap px-3 py-2.5 text-xs text-fg-2">{fmtDT(r.created_at)}</td>
            <td className="px-3"><div className="min-w-0"><div className="truncate font-medium text-fg">{r.invitor_username||"-"}</div><div className="truncate mono text-[11px] text-faint">{r.invitor_phone||""}</div></div></td>
            <td className="px-3"><div className="min-w-0"><div className="truncate text-fg-2">{r.invitee_username||"-"}</div><div className="truncate mono text-[11px] text-faint">{r.invitee_phone||""}</div></div></td>
            <td className="px-3 text-center"><Badge tone="info">ชั้น {r.level!=null?r.level:"-"}</Badge></td>
            <td className="px-3 text-xs text-fg-2">{AFF_TXTYPE[r.source_tx_type]||r.source_tx_type||"-"}</td>
            <td className="whitespace-nowrap px-3 text-right font-semibold tnum text-success pr-4">+{money2(r.credit)}</td>
          </tr>))}
      </tbody>
    </table></div>{!loading && !err && <Pager page={page} setPage={setPage} total={rows.length} size={size} setSize={setSize}/>}</div>)}
  </div>);
}
