/* ==========================================================================
 * ADMIN NEXT — page-featured.jsx  (ค่ายเกมยอดนิยม / เกมยอดนิยม)
 * ========================================================================== */

function FeaturedPage({ toast }) {
  const [tab,setTab]=useState("providers");
  const [providers,setProviders]=useState([]),[games,setGames]=useState([]);
  const [loading,setLoading]=useState(true),[err,setErr]=useState(null);

  const load=useCallback(async()=>{ setLoading(true); setErr(null);
    try{
      const [prov,pinned]=await Promise.all([api("/games/providers"),api("/games/pinned").catch(()=>[])]);
      setProviders(Array.isArray(prov)?prov:[]);
      setGames(Array.isArray(pinned)?pinned:[]);
    }catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail?.();} setErr(e.message||"โหลดไม่สำเร็จ"); }
    finally{ setLoading(false); } },[]);
  useEffect(()=>{ load(); },[load]);

  const toggleGame=async(id,pinned)=>{
    try{ await api("/games/bulk-toggle",{method:"POST",body:{ids:[id],enabled:!pinned,field:"pinned"}}); toast(pinned?"ยกเลิกปักหมุด":"ปักหมุดแล้ว"); load(); }
    catch(e){ toast(e.message||"ไม่สำเร็จ"); } };

  if(loading) return <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>;
  if(err) return <HistErr msg={err} onRetry={load}/>;

  return (<div className="space-y-4">
    <div className="flex flex-wrap items-center gap-2">
      <div className="flex gap-1 rounded-lg bg-sunken p-1">
        {[["providers","ค่ายเกมยอดนิยม"],["games","เกมยอดนิยม"]].map(([k,l])=><button key={k} onClick={()=>setTab(k)} className={"rounded-md px-3 py-1.5 text-sm font-medium transition-colors "+(tab===k?"bg-surface text-fg shadow-sm":"text-muted hover:text-fg")}>{l}</button>)}
      </div>
      <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>

    {tab==="providers"&&<div className="space-y-3">
      <p className="text-xs text-muted">ค่ายเกมที่มียอดนิยมสูง แสดงตามจำนวนเกม</p>
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
        {providers.map(p=>(
          <div key={p.provider||p.name} className="flex items-center gap-3 rounded-xl border border-line bg-surface p-4 shadow-sm">
            {p.logo_url?<img src={p.logo_url} className="h-10 w-10 rounded-lg bg-sunken object-contain"/>:<div className="grid h-10 w-10 place-items-center rounded-lg bg-sunken text-xs font-bold text-muted">{(p.provider||p.name||"?").slice(0,2).toUpperCase()}</div>}
            <div className="min-w-0 flex-1">
              <div className="font-medium text-sm text-fg">{p.name||p.provider}</div>
              <div className="text-[11px] text-muted">{p.game_count||0} เกม · {p.enabled?"เปิด":"ปิด"}</div>
            </div>
            <Badge tone={p.enabled?"success":"danger"}>{p.enabled?"เปิด":"ปิด"}</Badge>
          </div>))}
      </div>
    </div>}

    {tab==="games"&&<div className="space-y-3">
      <p className="text-xs text-muted">เกมที่ปักหมุด (แสดงบนหน้าเว็บไซต์)</p>
      {games.length===0?<div className="rounded-xl border border-dashed border-line bg-surface px-4 py-16 text-center shadow-sm"><div className="text-sm font-medium text-fg-2">ยังไม่มีเกมปักหมุด</div><p className="mt-1 text-xs text-muted">ไปที่ "ตั้งค่าค่ายเกม" เพื่อเลือกเกมปักหมุด</p></div>
      :<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
        {games.map(g=>(
          <div key={g.id} className="group rounded-xl border border-line bg-surface p-3 shadow-sm transition-colors hover:border-accent/30">
            {g.cover_url?<img src={g.cover_url} className="mx-auto mb-2 h-16 w-full rounded-lg bg-sunken object-cover"/>:<div className="mx-auto mb-2 grid h-16 w-full place-items-center rounded-lg bg-sunken text-xs text-muted">ไม่มีรูป</div>}
            <div className="text-xs font-medium text-fg truncate">{g.name||g.game_code||"-"}</div>
            <div className="text-[10px] text-muted">{g.provider||"-"}</div>
            {canAny(["games","provider-logos"])&&<button onClick={()=>toggleGame(g.id,true)} className="mt-2 w-full rounded-lg border border-line px-2 py-1 text-[11px] font-medium text-danger hover:bg-sunken">ยกเลิกปักหมุด</button>}
          </div>))}
      </div>}
    </div>}
  </div>);
}
