/* ==========================================================================
 * ADMIN NEXT — page-wheel.jsx  (กงล้อ — settings-based)
 * ========================================================================== */

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

  const load=useCallback(async()=>{ setLoading(true); setErr(null);
    try{ const d=await api("/settings"); setCfg(d||{}); }
    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{ await api("/settings",{method:"POST",body:{...cfg,wheel_rewards_json:JSON.stringify(rewards)}}); toast("บันทึกแล้ว"); }
    catch(e){ toast(e.message||"บันทึกไม่สำเร็จ"); } finally{ setSaving(false); } };
  const set=(k,v)=>setCfg(c=>({...c,[k]:v}));

  let rewards=[]; try{ rewards=JSON.parse(cfg.wheel_rewards_json||"[]"); }catch{rewards=[];}
  if(!Array.isArray(rewards))rewards=[];
  const setRewards=(fn)=>set("wheel_rewards_json",JSON.stringify(fn(rewards)));
  const addReward=()=>setRewards(rs=>[...rs,{label:"",amount:0,weight:1,color:"#6366F1",turnoverType:"turnover",turnoverMultiplier:1,maxWithdraw:0,canWithdraw:true,imageUrl:""}]);
  const updateReward=(i,k,v)=>setRewards(rs=>rs.map((r,j)=>j===i?{...r,[k]:v}:r));
  const removeReward=(i)=>setRewards(rs=>rs.filter((_,j)=>j!==i));

  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 Sel=({k,options})=><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">{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>;

  return (<div className="space-y-5">
    {Section({title:"ตั้งค่ากงล้อ",children:<>
      <div><Lb>เปิดกงล้อ</Lb>{Sel({k:"wheel_enabled",options:[["1","เปิด"],["0","ปิด"]]})}</div>
      <div><Lb>วิธีนับยอดฝาก</Lb>{Sel({k:"wheel_deposit_mode",options:[["per_deposit","นับต่อรายการ (แต่ละรายการต้องถึงยอดเอง)"],["cumulative","ยอดฝากสะสม (รวมหลายรายการ เศษยกไปรอบถัดไป)"]]})}</div>
      <div className="grid grid-cols-3 gap-3">
        <div><Lb>{cfg.wheel_deposit_mode==="cumulative"?"ฝากสะสมครบทุกกี่บาท":"ฝากทุกกี่บาท"}</Lb><input type="number" value={cfg.wheel_deposit_baht_per_unit||""} onChange={e=>set("wheel_deposit_baht_per_unit",e.target.value)} placeholder="100" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
        <div><Lb>ได้กี่แต้ม</Lb><input type="number" value={cfg.wheel_points_per_unit||""} onChange={e=>set("wheel_points_per_unit",e.target.value)} placeholder="1" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
        <div><Lb>ใช้กี่แต้มต่อ 1 หมุน</Lb><input type="number" value={cfg.wheel_points_per_spin||""} onChange={e=>set("wheel_points_per_spin",e.target.value)} placeholder="10" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
      </div>
      <div><Lb>จำกัดหมุนต่อวัน (0 = ไม่จำกัด)</Lb><input type="number" value={cfg.wheel_daily_spin_limit||""} onChange={e=>set("wheel_daily_spin_limit",e.target.value)} placeholder="0" className="w-40 rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
    </>})}

    {Section({title:"รางวัลกงล้อ",children:<>
      <div className="space-y-3">
        {rewards.map((rw,i)=>(
          <div key={i} className="rounded-lg border border-line-soft p-3 space-y-2">
            <div className="flex items-center gap-2">
              <input type="color" value={rw.color||"#6366F1"} onChange={e=>updateReward(i,"color",e.target.value)} className="h-7 w-7 cursor-pointer rounded border-0"/>
              <input type="text" value={rw.label||""} onChange={e=>updateReward(i,"label",e.target.value)} placeholder="ชื่อรางวัล" className="flex-1 rounded-lg border border-line bg-surface px-2 py-1.5 text-sm"/>
              <input type="number" value={rw.amount||""} onChange={e=>updateReward(i,"amount",Number(e.target.value))} placeholder="จำนวน (สตางค์)" className="w-28 rounded-lg border border-line bg-surface px-2 py-1.5 text-sm" title="หน่วยสตางค์ เช่น 500 = 5 บาท"/>
              <input type="number" value={rw.weight||""} onChange={e=>updateReward(i,"weight",Number(e.target.value))} placeholder="น้ำหนัก" className="w-20 rounded-lg border border-line bg-surface px-2 py-1.5 text-sm" title="น้ำหนัก (ยิ่งมาก ยิ่งออกบ่อย)"/>
              <button onClick={()=>removeReward(i)} className="grid h-7 w-7 place-items-center rounded-lg border border-line text-danger hover:bg-sunken"><Ic d={I.trash} size={14}/></button>
            </div>
            <div className="grid grid-cols-4 gap-2">
              <div><label className="text-[10px] text-muted">เทิร์น</label><select value={rw.turnoverType||"turnover"} onChange={e=>updateReward(i,"turnoverType",e.target.value)} className="w-full rounded border border-line bg-surface px-2 py-1 text-xs"><option value="turnover">เทิร์นโอเวอร์</option><option value="credit">เทิร์นเครดิต</option><option value="none">ไม่มี</option></select></div>
              <div><label className="text-[10px] text-muted">ตัวคูณเทิร์น</label><input type="number" value={rw.turnoverMultiplier||""} onChange={e=>updateReward(i,"turnoverMultiplier",Number(e.target.value))} className="w-full rounded border border-line bg-surface px-2 py-1 text-xs" step="0.1"/></div>
              <div><label className="text-[10px] text-muted">ถอนสูงสุด (0=ไม่จำกัด)</label><input type="number" value={rw.maxWithdraw||""} onChange={e=>updateReward(i,"maxWithdraw",Number(e.target.value))} className="w-full rounded border border-line bg-surface px-2 py-1 text-xs"/></div>
              <div><label className="text-[10px] text-muted">ถอนได้</label><select value={rw.canWithdraw===false?"0":"1"} onChange={e=>updateReward(i,"canWithdraw",e.target.value==="1")} className="w-full rounded border border-line bg-surface px-2 py-1 text-xs"><option value="1">ถอนได้</option><option value="0">ถอนไม่ได้</option></select></div>
            </div>
            <div><label className="text-[10px] text-muted">URL รูปรางวัล</label><input type="text" value={rw.imageUrl||""} onChange={e=>updateReward(i,"imageUrl",e.target.value)} placeholder="https://..." className="w-full rounded border border-line bg-surface px-2 py-1 text-xs"/></div>
          </div>))}
        <button onClick={addReward} className="flex w-full items-center justify-center gap-1.5 rounded-lg border border-dashed border-line py-2.5 text-sm font-medium text-muted hover:border-accent hover:text-accent"><Ic d={I.plus} size={16}/> เพิ่มรางวัล</button>
      </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>);
}
