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

/* ---------- ประวัติทายผล — /prediction-history ---------- */
function PredictionHistoryPage({ toast }) {
  const [rows,setRows]=useState([]),[loading,setLoading]=useState(true),[err,setErr]=useState(null);
  const [q,setQ]=useState(""),[filter,setFilter]=useState("");
  const [page,setPage]=useState(1),[size,setSize]=useState(50);
  const debRef=useRef(null);
  const load=useCallback(async(query,fl)=>{ setLoading(true); setErr(null);
    try{ const p=new URLSearchParams({limit:"300"}); if(query)p.set("search",query); if(fl)p.set("filter",fl);
      const d=await api("/prediction-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(),filter); },[filter,load]);
  useEffect(()=>{ if(debRef.current)clearTimeout(debRef.current); debRef.current=setTimeout(()=>load(q.trim(),filter),350); return ()=>clearTimeout(debRef.current); },[q]);
  useEffect(()=>{ setPage(1); },[q,filter,rows.length]);
  const paged=rows.slice((page-1)*size,page*size);
  const ans=(r)=> r.answer_text || (Array.isArray(r.choices)&&r.choices[r.choice_index]!=null?r.choices[r.choice_index]:("#"+(r.choice_index!=null?r.choice_index:"-")));
  const H=({children,extra=""})=>(<th className={"whitespace-nowrap px-3 py-2.5 text-left text-[13px] font-bold text-fg-2 "+extra}>{children}</th>);
  return (<div className="space-y-3">
    <div className="flex flex-wrap items-center gap-2">
      <div className="relative flex-1 sm:max-w-xs"><span className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted"><Ic d={I.search} size={16}/></span>
        <input value={q} onChange={(e)=>setQ(e.target.value)} placeholder="ค้นหา ชื่อ / ยูส / เบอร์…" className="h-9 w-full rounded-lg border border-line bg-surface pl-9 pr-3 text-sm text-fg placeholder:text-faint focus:border-accent focus:outline-none focus:ring-4 focus:ring-[var(--accent-ring)]"/></div>
      <div className="flex flex-wrap items-center gap-1 rounded-lg border border-line bg-sunken p-0.5">
        {[["","ทั้งหมด"],["correct","ถูก"],["incorrect","ผิด"],["pending","รอผล"]].map(([k,l])=>(<button key={k||"all"} onClick={()=>setFilter(k)} className={"rounded-md px-2.5 py-1 text-xs font-medium transition-colors "+(filter===k?"bg-accent text-accent-fg shadow-sm":"text-fg-2 hover:text-fg")}>{l}</button>))}</div>
      <button onClick={()=>load(q.trim(),filter)} 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} cls={loading?"animate-spin":""}/> รีเฟรช</button>
      <div className="ml-auto hidden text-xs text-muted sm:block tnum">{rows.length} รายการ</div>
    </div>
    {err ? <HistErr msg={err} onRetry={()=>load(q.trim(),filter)}/>
    : (<div className="overflow-hidden rounded-xl border border-line bg-surface shadow-sm"><div className="overflow-x-auto"><table className="w-full min-w-[860px] border-collapse text-sm">
      <thead className="border-b-2 border-accent/25 bg-accent-soft"><tr>{H({children:"เวลา"})}{H({children:"สมาชิก"})}{H({children:"หัวข้อ"})}{H({children:"คำตอบ"})}{H({children:"ผล",extra:"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="5"><div className="skel h-5 w-full"/></td></tr>))
          : rows.length===0 ? (<tr><td colSpan="5" className="px-4 py-16 text-center text-sm font-medium text-fg-2">ไม่มีรายการ</td></tr>)
          : paged.map((r,i)=>{ const res=r.is_correct===true?{t:"ถูก",c:"success"}:r.is_correct===false?{t:"ผิด",c:"danger"}:{t:"รอผล",c:"warn"}; return (<tr key={r.entry_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.entry_at)}</td>
            <td className="px-3"><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:""}</div></div></td>
            <td className="px-3 text-xs text-fg-2"><span className="line-clamp-1">{r.title||"-"}</span></td>
            <td className="px-3 text-xs text-fg-2">{ans(r)}</td>
            <td className="pr-4"><Badge tone={res.c}>{res.t}</Badge></td>
          </tr>); })}
      </tbody>
    </table></div>{!loading && !err && <Pager page={page} setPage={setPage} total={rows.length} size={size} setSize={setSize}/>}</div>)}
  </div>);
}
