/* ==========================================================================
 * ADMIN NEXT — page-cashback.jsx  (คืนยอดเสีย — settings-based)
 * ========================================================================== */

function CashbackPage({ toast }) {
  const [cfg,setCfg]=useState({}),[loading,setLoading]=useState(true),[saving,setSaving]=useState(false),[err,setErr]=useState(null);
  const [catRates,setCatRates]=useState({});

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

  const save=async()=>{ setSaving(true);
    try{ const body={...cfg}; if(cfg.cashback_calc_mode==="category") body.__cashback_cat_rates=JSON.stringify(catRates);
      await api("/settings",{method:"POST",body}); toast("บันทึกแล้ว"); }
    catch(e){ toast(e.message||"บันทึกไม่สำเร็จ"); } finally{ setSaving(false); } };
  const set=(k,v)=>setCfg(c=>({...c,[k]:v}));

  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}/>;

  const Lb=({children})=><label className="mb-1 block text-xs font-semibold text-fg-2">{children}</label>;
  const Nm=({k,ph="",w=""})=><input type="number" value={cfg[k]||""} onChange={e=>set(k,e.target.value)} placeholder={ph} className={(w||"w-full")+" rounded-lg border border-line bg-surface px-3 py-2 text-sm"}/>;
  const Sel=({k,options,ph})=><select value={cfg[k]||""} onChange={e=>set(k,e.target.value)} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm">{ph&&<option value="">{ph}</option>}{options.map(([v,l])=><option key={v} value={v}>{l}</option>)}</select>;
  const Section=({title,children})=><div className="rounded-xl border border-line bg-surface p-5 shadow-sm space-y-4"><h3 className="text-sm font-semibold text-fg">{title}</h3>{children}</div>;

  const hideTurnover=cfg.cashback_turnover_type==="none";
  const cats=["slot","casino","sport","fish","lotto","poker","esport","keno"];

  return (<div className="space-y-5">
    {Section({title:"ตั้งค่าคืนยอดเสีย",children:<>
      <div><Lb>เปิดระบบคืนยอดเสีย</Lb>{Sel({k:"cashback_enabled",options:[["true","เปิด"],["false","ปิด"]]})}</div>
      <div><Lb>วิธีคิดยอดเสีย</Lb>{Sel({k:"cashback_calc_mode",options:[["category","แยกตามหมวดเกม"],["deposit","ก้อนเดียวตามยอดฝาก (แบบเดิม)"]]})}</div>
      <div className="grid grid-cols-2 gap-3">
        <div><Lb>เรตตั้งต้น (%)</Lb>{Nm({k:"cashback_percent",ph:"5"})}</div>
        <div><Lb>ยอดเสียขั้นต่ำที่จะได้รับ (บาท)</Lb>{Nm({k:"cashback_min_loss",ph:"10000"})}</div>
      </div>
      <div className="grid grid-cols-2 gap-3">
        <div><Lb>ยอดคืนขั้นต่ำที่จ่าย (บาท)</Lb>{Nm({k:"cashback_min_payout",ph:"10000"})}</div>
        <div><Lb>ยอดคืนสูงสุดต่อครั้ง (บาท, 0 = ไม่จำกัด)</Lb>{Nm({k:"cashback_max_payout",ph:"100000000"})}</div>
      </div>
    </>})}

    {Section({title:"เทิร์นเครดิตคืน",children:<>
      <div><Lb>รูปแบบเทิร์น</Lb>{Sel({k:"cashback_turnover_type",options:[["turnover","เทิร์นโอเวอร์"],["credit","เทิร์นเครดิต"],["none","ไม่มีเทิร์น (รับแล้วถอนได้เลย)"]]})}</div>
      {!hideTurnover&&<>
        <div><Lb>วิธีตั้งยอดเทิร์น</Lb>{Sel({k:"cashback_turnover_mode",options:[["factor","คำนวณเป็นเท่า"],["fixed","เทิร์นระบุจำนวน"]]})}</div>
        <div><Lb>ตัวคูณเทิร์น (เท่า/บาท, 0 = ถอนได้เลย)</Lb>{Nm({k:"cashback_turnover_multiplier",ph:"1"})}</div>
        <div><Lb>อนุญาตให้ถอนเครดิตคืน</Lb>{Sel({k:"cashback_can_withdraw",options:[["1","ถอนได้"],["0","ถอนไม่ได้"]]})}</div>
      </>}
    </>})}

    {Section({title:"รอบการรับยอดคืน",children:<>
      <div><Lb>รอบการรับ</Lb>{Sel({k:"cashback_period_mode",options:[["realtime","เรียลไทม์ (จบเกมรับได้ทันที, 1 ครั้ง/วัน)"],["daily","รายวัน (วันใหม่รับได้เลย, 1 ครั้ง/วัน)"],["weekly","รายสัปดาห์ (รับได้ในวันที่กำหนด, 1 ครั้ง/สัปดาห์)"]]})}</div>
      {cfg.cashback_period_mode==="weekly"&&<div><Lb>วันที่รับ</Lb>{Sel({k:"cashback_weekly_day",options:[["1","จันทร์"],["2","อังคาร"],["3","พุธ"],["4","พฤหัสบดี"],["5","ศุกร์"],["6","เสาร์"],["7","อาทิตย์"]]})}</div>}
    </>})}

    {cfg.cashback_calc_mode==="category"&&Section({title:"เรตแยกตามหมวดเกม (%)",children:<>
      <div className="grid grid-cols-2 gap-3">
        {cats.map(c=><div key={c}><Lb>{c}</Lb><input type="number" value={catRates[c]||""} onChange={e=>setCatRates(r=>({...r,[c]:e.target.value}))} placeholder="ใช้เรตตั้งต้น" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>)}
      </div>
    </>})}

    {Section({title:"ริบยอดเสียที่ไม่ได้กดรับ",children:<>
      <div><Lb>ริบยอดเสียเมื่อเลยกำหนด</Lb>{Sel({k:"cashback_forfeit_enabled",options:[["0","ไม่ริบ (สะสมต่อไปเรื่อย ๆ)"],["1","ริบทั้งหมดเมื่อเลยกำหนด"]]})}</div>
      {cfg.cashback_forfeit_enabled==="1"&&<>
        <div><Lb>ริบเมื่อเลยกี่วัน (0 = ริบทุกวัน)</Lb>{Nm({k:"cashback_forfeit_days",ph:"0"})}</div>
        <div><Lb>ริบตอนกี่โมง (เวลาไทย)</Lb><input type="time" value={cfg.cashback_forfeit_time||"00:00"} onChange={e=>set("cashback_forfeit_time",e.target.value)} className="w-40 rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
      </>}
    </>})}

    <div className="flex justify-end">
      <button disabled={saving} onClick={save} className="rounded-lg bg-accent px-6 py-2.5 text-sm font-medium text-accent-fg hover:bg-accent-h disabled:opacity-50">{saving?"กำลังบันทึก…":"บันทึกทั้งหมด"}</button>
    </div>
  </div>);
}
