/* ==========================================================================
 * ADMIN NEXT — page-providerlogos.jsx  (รูปเมนูค่ายเกม)
 * ========================================================================== */

const LOBBY_IMAGE_DEFS=[
  {key:"casino",label:"คาสิโน",kind:"lobby_casino",setting:"wl_lobby_img_casino"},
  {key:"slot",label:"สล็อต",kind:"lobby_slot",setting:"wl_lobby_img_slot"},
  {key:"sport",label:"กีฬา",kind:"lobby_sport",setting:"wl_lobby_img_sport"},
  {key:"fish",label:"ยิงปลา",kind:"lobby_fish",setting:"wl_lobby_img_fish"},
  {key:"card",label:"ไพ่",kind:"lobby_card",setting:"wl_lobby_img_card"},
  {key:"lotto",label:"หวย",kind:"lobby_lotto",setting:"wl_lobby_img_lotto"},
];

function LobbyImagesSection({toast}){
  const [cfg,setCfg]=useState({}),[loading,setLoading]=useState(true),[saving,setSaving]=useState(false),[uploading,setUploading]=useState(null);

  const load=useCallback(async()=>{ setLoading(true);
    try{ const d=await api("/settings"); setCfg(d||{}); }
    catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail?.();} }
    finally{ setLoading(false); } },[]);
  useEffect(()=>{ load(); },[load]);

  const set=(k,v)=>setCfg(c=>({...c,[k]:v}));

  const uploadImg=async(def,file)=>{
    if(file.size>10*1024*1024){ toast("ไฟล์รูปต้องไม่เกิน 10MB"); return; }
    setUploading(def.key);
    try{
      const dataUrl=await new Promise((res,rej)=>{ const r=new FileReader(); r.onload=()=>res(r.result); r.onerror=rej; r.readAsDataURL(file); });
      const r=await api("/branding/upload",{method:"POST",body:{kind:def.kind,fileName:file.name,mimeType:file.type,dataUrl,noSave:true}});
      if(r&&r.url){ set(def.setting,r.url); toast("อัพโหลดสำเร็จ"); }
    }catch(e){ toast(e.message||"อัพโหลดไม่สำเร็จ"); }
    finally{ setUploading(null); }
  };

  const save=async()=>{ setSaving(true);
    try{
      const body={};
      LOBBY_IMAGE_DEFS.forEach(d=>{ body[d.setting]=cfg[d.setting]||""; });
      await api("/settings",{method:"POST",body});
      toast("บันทึกรูปเมนูค่ายเกมแล้ว");
    }catch(e){ toast(e.message||"บันทึกไม่สำเร็จ"); }
    finally{ setSaving(false); }
  };

  if(loading) return <div className="flex items-center gap-2 py-8 justify-center text-sm text-muted"><Ic d={I.refresh} size={16} cls="animate-spin"/> กำลังโหลด…</div>;

  return (<div className="rounded-xl border border-line bg-surface p-5 shadow-sm space-y-4">
    <div>
      <h3 className="text-sm font-semibold text-fg flex items-center gap-2"><Ic d={I.grid} size={16}/> รูปเมนูค่ายเกม</h3>
      <p className="text-xs text-muted mt-1">อัพโหลดรูปสำหรับแต่ละหมวด — ถ้าว่างจะแสดง icon / มีรูปจะแสดงรูปเต็มการ์ดในหน้าเว็บลูกค้า</p>
    </div>
    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
      {LOBBY_IMAGE_DEFS.map(d=>{
        const url=cfg[d.setting]||"";
        return (<div key={d.key} className="space-y-2">
          <label className="text-xs font-semibold text-fg-2">{d.label}</label>
          <div className="flex gap-3">
            <div className="grid h-20 w-20 shrink-0 place-items-center rounded-lg bg-sunken overflow-hidden">
              {url?<img src={url} className="h-full w-full object-contain" onError={e=>{e.target.style.display='none'}}/>:<Ic d={I.grid} size={24} cls="text-faint"/>}
            </div>
            <div className="min-w-0 flex-1 space-y-1.5">
              <input type="text" value={url} onChange={e=>set(d.setting,e.target.value)} placeholder={"/uploads/branding/"+d.key+".webp"} className="w-full rounded-lg border border-line bg-surface px-3 py-1.5 text-xs"/>
              <div className="flex gap-2">
                <label className="cursor-pointer rounded-lg border border-line px-2.5 py-1 text-[11px] font-medium text-accent hover:bg-accent-soft">
                  {uploading===d.key?"กำลังอัพ…":"อัปโหลดรูป"}
                  <input type="file" accept="image/png,image/jpeg,image/webp,image/gif" className="hidden" onChange={e=>{if(e.target.files[0])uploadImg(d,e.target.files[0]);}}/>
                </label>
                {url&&<button onClick={()=>set(d.setting,"")} className="rounded-lg border border-line px-2.5 py-1 text-[11px] font-medium text-danger hover:bg-red-500/10">ล้างรูป</button>}
              </div>
            </div>
          </div>
        </div>);
      })}
    </div>
    <div className="flex gap-2 pt-2">
      <button disabled={saving} onClick={save} className="rounded-lg bg-accent px-4 py-2 text-sm font-medium text-accent-fg hover:bg-accent-h disabled:opacity-50">{saving?"กำลังบันทึก…":"บันทึกการตั้งค่า"}</button>
      <button onClick={load} className="rounded-lg border border-line px-4 py-2 text-sm font-medium text-fg-2 hover:bg-sunken">รีเฟรช</button>
    </div>
  </div>);
}

function ProviderLogosPage({ toast }) {
  const [providers,setProviders]=useState([]),[loading,setLoading]=useState(true),[err,setErr]=useState(null);
  const [search,setSearch]=useState(""),[uploading,setUploading]=useState(null);

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

  const upload=async(provider,file,type)=>{
    setUploading(provider+"_"+type);
    try{
      const fd=new FormData(); fd.append("image",file);
      const t=getToken();
      const endpoint=type==="category"?"category-logo-upload":"logo-upload";
      const r=await fetch("/api/admin/providers/"+encodeURIComponent(provider)+"/"+endpoint,{method:"POST",headers:{"Authorization":"Bearer "+t},body:fd});
      if(!r.ok){ const d=await r.json().catch(()=>null); throw new Error(d?.error||"อัพโหลดไม่สำเร็จ"); }
      toast("อัพโหลดสำเร็จ"); load();
    }catch(e){ toast(e.message||"อัพโหลดไม่สำเร็จ"); } finally{ setUploading(null); } };

  const setLogoUrl=async(provider,url,type)=>{
    try{
      const endpoint=type==="category"?"category-logo-url":"logo-url";
      await api("/providers/"+encodeURIComponent(provider)+"/"+endpoint,{method:"POST",body:{url}});
      toast("บันทึกแล้ว"); load();
    }catch(e){ toast(e.message||"ไม่สำเร็จ"); } };

  const deleteLogo=async(provider,type)=>{
    if(!window.confirm("ลบโลโก้นี้?"))return;
    try{
      const endpoint=type==="category"?"category-logo":"logo";
      await api("/providers/"+encodeURIComponent(provider)+"/"+endpoint,{method:"DELETE"});
      toast("ลบแล้ว"); load();
    }catch(e){ toast(e.message||"ไม่สำเร็จ"); } };

  const filtered=search?providers.filter(p=>(p.name||p.provider||"").toLowerCase().includes(search.toLowerCase())):providers;

  return (<div className="space-y-6">
    <LobbyImagesSection toast={toast}/>

    <div className="rounded-xl border border-line bg-surface p-5 shadow-sm space-y-4">
      <div>
        <h3 className="text-sm font-semibold text-fg flex items-center gap-2"><Ic d={I.game} size={16}/> โลโก้ค่ายเกม</h3>
        <p className="text-xs text-muted mt-1">อัพโหลดโลโก้ของแต่ละค่ายเกม</p>
      </div>

      <div className="flex flex-wrap items-center gap-2">
        <div className="relative flex-1 max-w-xs"><Ic d={I.search} size={16} cls="absolute left-3 top-1/2 -translate-y-1/2 text-muted"/><input type="text" value={search} onChange={e=>setSearch(e.target.value)} placeholder="ค้นหาค่ายเกม…" className="w-full rounded-lg border border-line bg-surface py-2 pl-9 pr-3 text-sm"/></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} cls={loading?"animate-spin":""}/> รีเฟรช</button>
        <span className="ml-auto text-xs text-muted tnum">{filtered.length} ค่าย</span>
      </div>

      {loading ? <div className="flex items-center gap-2 py-8 justify-center text-sm text-muted"><Ic d={I.refresh} size={16} cls="animate-spin"/> กำลังโหลด…</div>
      : err ? <HistErr msg={err} onRetry={load}/>
      : <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {filtered.map(p=>{
          const key=p.provider||p.name||p.id;
          return (<div key={key} className="rounded-xl border border-line bg-sunken/30 p-4">
            <div className="mb-3 flex items-center gap-3">
              {p.logo_url?<img src={p.logo_url} className="h-12 w-12 rounded-lg bg-sunken object-contain" onError={e=>{e.target.style.display="none"}}/>:<div className="grid h-12 w-12 place-items-center rounded-lg bg-sunken text-xs font-bold text-muted">{(key||"?").slice(0,2).toUpperCase()}</div>}
              <div className="min-w-0 flex-1"><div className="font-medium text-sm text-fg truncate">{p.name||key}</div><div className="text-[11px] text-muted mono">{key}</div></div>
            </div>
            <div className="space-y-2">
              <div className="flex items-center gap-1">
                <label className="flex-1 text-[11px] font-semibold text-muted">โลโก้หลัก</label>
                <label className="cursor-pointer rounded px-2 py-0.5 text-[11px] font-medium text-accent hover:bg-accent-soft">{uploading===key+"_main"?"กำลังอัพ…":"อัพโหลด"}<input type="file" accept="image/*" className="hidden" onChange={e=>{if(e.target.files[0])upload(key,e.target.files[0],"main");}}/></label>
                {p.logo_url&&<button onClick={()=>deleteLogo(key,"main")} className="text-[11px] text-danger hover:underline">ลบ</button>}
              </div>
              <div className="flex items-center gap-1">
                <label className="flex-1 text-[11px] font-semibold text-muted">โลโก้หมวดหมู่</label>
                <label className="cursor-pointer rounded px-2 py-0.5 text-[11px] font-medium text-accent hover:bg-accent-soft">{uploading===key+"_category"?"กำลังอัพ…":"อัพโหลด"}<input type="file" accept="image/*" className="hidden" onChange={e=>{if(e.target.files[0])upload(key,e.target.files[0],"category");}}/></label>
                {p.category_logo_url&&<button onClick={()=>deleteLogo(key,"category")} className="text-[11px] text-danger hover:underline">ลบ</button>}
              </div>
            </div>
          </div>);
        })}
      </div>}
    </div>
  </div>);
}
