/* ==========================================================================
 * ADMIN NEXT — page-leaderboard.jsx  (Leaderboard / อันดับ)
 * ========================================================================== */

function LeaderboardPage({ toast }) {
  const [type,setType]=useState("score");
  const [lastWeek,setLastWeek]=useState(false);
  const [rows,setRows]=useState([]);
  const [loading,setLoading]=useState(true);
  const [err,setErr]=useState(null);
  const [pg,setPg]=useState(1);
  const [total,setTotal]=useState(0);
  const perPage=20;

  const load=useCallback(async()=>{ setLoading(true); setErr(null);
    try{
      const d=await api(`/reports/leaderboard?type=${type}&lastWeek=${lastWeek}&page=${pg}&perPage=${perPage}`);
      setRows(d.rows||[]); setTotal(d.total||0);
    }catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail?.();} setErr(e.message||"โหลดไม่สำเร็จ"); }
    finally{ setLoading(false); } },[type,lastWeek,pg]);
  useEffect(()=>{ load(); },[load]);

  const [detail,setDetail]=useState(null);
  const [detailLoading,setDetailLoading]=useState(false);
  const showDetail=async(row)=>{
    setDetailLoading(true);
    try{
      const body=type==="bigwin"?{ref1:row.ref1,timestamp:row.timestamp}:{username:row.username,source:row.source,lastWeek};
      const d=await api("/reports/leaderboard/detail",{method:"POST",body});
      setDetail(d);
    }catch(e){ toast(e.message||"โหลดรายละเอียดไม่สำเร็จ"); }
    finally{ setDetailLoading(false); }
  };

  if(err) return <HistErr msg={err} onRetry={load}/>;

  return (<div className="space-y-4">
    <div className="flex flex-wrap items-center gap-3">
      <select value={type} onChange={e=>{setType(e.target.value);setPg(1);}} className="rounded-lg border border-line bg-surface px-3 py-2 text-sm">
        <option value="score">Score</option><option value="bigwin">Big Win</option>
      </select>
      <label className="flex items-center gap-2 cursor-pointer"><input type="checkbox" checked={lastWeek} onChange={e=>{setLastWeek(e.target.checked);setPg(1);}} className="h-4 w-4 rounded border-line accent-accent"/><span className="text-sm text-fg-2">สัปดาห์ก่อน</span></label>
      <button onClick={load} className="flex h-9 items-center gap-1.5 rounded-lg border border-line bg-surface px-3 text-sm font-medium text-fg-2 hover:bg-sunken"><Ic d={I.refresh} size={16}/> รีเฟรช</button>
    </div>

    {loading ? <div className="flex items-center gap-2 py-16 justify-center text-sm text-muted"><Ic d={I.refresh} size={16} cls="animate-spin"/> กำลังโหลด…</div> : (
    <div className="overflow-x-auto rounded-xl border border-line bg-surface shadow-sm">
      <table className="w-full text-sm">
        <thead><tr className="border-b border-line bg-sunken/60 text-left text-xs font-semibold text-muted">
          <th className="px-4 py-3 w-12">#</th>
          <th className="px-4 py-3">Username</th>
          {type==="score"&&<th className="px-4 py-3 text-right">Score</th>}
          {type==="bigwin"&&<><th className="px-4 py-3 text-right">Win Amount</th><th className="px-4 py-3">Game</th></>}
          <th className="px-4 py-3 w-20"></th>
        </tr></thead>
        <tbody>{rows.length===0?(<tr><td colSpan={type==="score"?4:5} className="px-4 py-12 text-center text-muted">ไม่มีข้อมูล</td></tr>):rows.map((r,i)=>(
          <tr key={i} className="border-b border-line last:border-0 hover:bg-sunken/40">
            <td className="px-4 py-3 font-medium text-muted">{(pg-1)*perPage+i+1}</td>
            <td className="px-4 py-3 font-medium">{r.username||r.display_name||"-"}</td>
            {type==="score"&&<td className="px-4 py-3 text-right mono tnum">{baht(r.score||r.amount||0)}</td>}
            {type==="bigwin"&&<><td className="px-4 py-3 text-right mono tnum">{baht(r.amount||0)}</td><td className="px-4 py-3 text-muted">{r.game_name||r.game||"-"}</td></>}
            <td className="px-4 py-3"><button onClick={()=>showDetail(r)} className="text-xs text-accent hover:underline">ดูเพิ่ม</button></td>
          </tr>))}</tbody>
      </table>
    </div>)}
    <Pager page={pg} total={Math.ceil(total/perPage)} onPage={setPg}/>

    {detail&&(<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 fade-in" onClick={()=>setDetail(null)}>
      <div className="w-full max-w-lg rounded-xl bg-surface p-6 shadow-lg pop" onClick={e=>e.stopPropagation()}>
        <div className="mb-4 flex items-center justify-between"><h3 className="text-sm font-semibold">รายละเอียด</h3><IconBtn icon={I.x} onClick={()=>setDetail(null)}/></div>
        <pre className="max-h-80 overflow-auto rounded-lg bg-sunken p-4 text-xs mono whitespace-pre-wrap">{JSON.stringify(detail,null,2)}</pre>
      </div>
    </div>)}
  </div>);
}
