/* ==========================================================================
 * ADMIN NEXT — page-wheel.jsx  (กงล้อ — settings-based)
 * แท็บ "ตั้งค่ากงล้อ" ส่วนเงื่อนไขรางวัล ตั้งเทิร์น/ถอน/หมวดเกมครั้งเดียว ตอนบันทึกคัดลอกลงทุกรางวัลใน wheel_rewards_json
 * (รูปแบบข้อมูลเหมือนเดิม src/services/wheel.js ไม่ต้องแก้)
 * ========================================================================== */
const WHEEL_TURN=[["turnover","เทิร์นโอเวอร์"],["credit","เทิร์นเครดิต"],["none","ไม่มีเทิร์น"]];
function wheelRatio(r){ const amount=Number(r.amount||0), cap=Number(r.maxWithdraw||0); return amount>0&&cap>0?Math.round(cap/amount*100)/100:0; }
function wheelCats(r){ return Array.isArray(r.allowedCategories)?[...r.allowedCategories].sort().join(","):""; }

// เงื่อนไขร่วมอ่านจากรางวัลแรกที่มีเครดิต และบอกว่าค่าเดิมต่างกันรายรางวัลตรงไหน (บันทึกแล้วจะถูกทับ)
function wheelDeriveWallet(rewards){
  const list=rewards.filter(r=>r&&r.label);
  const base=list.find(r=>Number(r.amount||0)>0)||list[0]||{};
  const type=["credit","none"].includes(base.turnoverType)?base.turnoverType:"turnover";
  const wallet={ turnoverType:type, turnoverMultiplier:String(Number(base.turnoverMultiplier||0)), canWithdraw:base.canWithdraw!==false, capMult:String(wheelRatio(base)), allowedCategories:Array.isArray(base.allowedCategories)?base.allowedCategories:[] };
  const mixed=[];
  if(list.some(r=>(["credit","none"].includes(r.turnoverType)?r.turnoverType:"turnover")!==type)) mixed.push("รูปแบบเทิร์น");
  if(list.some(r=>Number(r.turnoverMultiplier||0)!==Number(base.turnoverMultiplier||0))) mixed.push("เทิร์น");
  if(list.some(r=>Number(r.amount||0)>0&&wheelRatio(r)!==wheelRatio(base))) mixed.push("ถอนสูงสุด");
  if(list.some(r=>wheelCats(r)!==wheelCats(base))) mixed.push("หมวดเกม");
  return {wallet,mixed};
}

function WheelPage({ toast }) {
  const [cfg,setCfg]=useState({}),[loading,setLoading]=useState(true),[saving,setSaving]=useState(false),[err,setErr]=useState(null);
  const [tab,setTab]=useState("settings");
  const [wallet,setWallet]=useState({turnoverType:"turnover",turnoverMultiplier:"0",canWithdraw:true,capMult:"0",allowedCategories:[]});
  const [mixed,setMixed]=useState([]);

  const load=useCallback(async()=>{ setLoading(true); setErr(null);
    try{ const d=await api("/settings"); setCfg(d||{});
      let saved=[]; try{ saved=JSON.parse((d&&d.wheel_rewards_json)||"[]"); }catch{ saved=[]; }
      const derived=wheelDeriveWallet(Array.isArray(saved)?saved:[]); setWallet(derived.wallet); setMixed(derived.mixed); }
    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(applyWallet(rewards))}}); toast("บันทึกแล้ว"); setMixed([]); }
    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));
  const setW=(k,v)=>setWallet(o=>({...o,[k]:v}));
  const capMult=Math.max(0,Number(wallet.capMult)||0);
  const noTurnover=wallet.turnoverType==="none";
  const capOf=(amount)=>capMult>0?Math.round(Number(amount||0)*capMult):0;
  const applyWallet=(list)=>list.map(r=>({...r, turnoverType:wallet.turnoverType, turnoverMultiplier:noTurnover?0:Math.max(0,Number(wallet.turnoverMultiplier)||0),
    canWithdraw:true, maxWithdraw:capOf(r.amount), allowedCategories:wallet.allowedCategories&&wallet.allowedCategories.length?wallet.allowedCategories:null}));
  // ระบบเก็บจำนวนรางวัล/ถอนสูงสุดเป็นสตางค์ หน้านี้ให้กรอกเป็นบาทเหมือนเช็คอิน/คูปอง แล้วแปลงตอนพิมพ์
  const bahtOf=(satang)=>Number(satang||0)>0?Number(satang)/100:"";
  const satangOf=(baht)=>Math.max(0,Math.round(Number(baht||0)*100));

  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 inp="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm";
  const Fl=({children,hint})=><label className="mb-1 flex items-baseline justify-between gap-2 text-[11px] font-semibold text-fg-2"><span>{children}</span>{hint&&<span className="font-normal text-muted">{hint}</span>}</label>;
  // น้ำหนักรวมนับเฉพาะรางวัลที่มีชื่อ ตรงกับที่ src/services/wheel.js ใช้สุ่ม
  const totalWeight=rewards.reduce((sum,r)=>sum+(r&&r.label?Math.max(0,Number(r.weight)||0):0),0);
  const chanceOf=(r)=>{ const w=Math.max(0,Number(r.weight)||0); if(!r.label||!totalWeight) return ""; return "≈ "+(w*100/totalWeight).toFixed(w*100/totalWeight<1?2:1)+"%"; };

  // ค่าที่ว่าง/0 แสดงค่าเริ่มต้นเดียวกับ intSetting ใน src/services/wheel.js
  const num=(k,fallback)=>{ const n=parseInt(String(cfg[k]??""),10); return Number.isFinite(n)&&n>0?n:fallback; };
  const cumulative=cfg.wheel_deposit_mode==="cumulative";
  const perUnit=num("wheel_deposit_baht_per_unit",100), ptsPerUnit=num("wheel_points_per_unit",1), ptsPerSpin=num("wheel_points_per_spin",10), dailyLimit=num("wheel_daily_spin_limit",0);
  const TabBtn=({id,children})=><button type="button" onClick={()=>setTab(id)} className={"-mb-px border-b-2 px-1 pb-2.5 text-sm font-medium transition-colors "+(tab===id?"border-accent text-accent":"border-transparent text-muted hover:text-fg")}>{children}</button>;

  return (<div className="space-y-5">
    <div className="rounded-xl border border-line bg-surface shadow-sm">
      <div className="flex flex-wrap items-end justify-between gap-3 border-b border-line px-5 pt-4">
        <div className="flex gap-6">
          <TabBtn id="settings">ตั้งค่ากงล้อ</TabBtn>
          <TabBtn id="rewards">รางวัล <span className="ml-1 rounded-full bg-sunken px-1.5 text-[11px] text-muted">{rewards.length}</span></TabBtn>
        </div>
      </div>

      {tab==="settings"&&<div className="space-y-6 p-5">
        <section className="space-y-4">
        <div><h4 className="text-sm font-semibold text-fg">การหมุน</h4></div>
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
          <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>
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
          <div><Lb>{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={inp}/></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={inp}/></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={inp}/></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={inp}/></div>
        </div>
        </section>
        <section className="space-y-4 border-t border-line pt-5">
        <div><h4 className="text-sm font-semibold text-fg">เงื่อนไขรางวัล (ใช้ทุกรางวัล)</h4><p className="mt-0.5 text-xs text-muted">ตั้งครั้งเดียว กด "บันทึกทั้งหมด" แล้วระบบคัดลอกค่าลงทุกรางวัล</p></div>
        {mixed.length>0&&<p className="rounded-lg border px-3 py-2 text-[12px] leading-relaxed" style={{borderColor:"var(--warn)",color:"var(--warn)"}}>ค่าเดิมตั้งไม่เท่ากันรายรางวัล ({mixed.join(", ")}) หน้านี้แสดงค่าของรางวัลแรกที่มีเครดิต กดบันทึกแล้วทุกรางวัลจะใช้ค่านี้</p>}
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">
          <div><Fl>รูปแบบเทิร์น</Fl><select value={wallet.turnoverType} onChange={e=>setW("turnoverType",e.target.value)} className={inp}>{WHEEL_TURN.map(([k,l])=><option key={k} value={k}>{l}</option>)}</select></div>
          <div><Fl hint="เท่าของรางวัล">ทำเทิร์น</Fl><input type="number" min="0" step="1" value={noTurnover?"":wallet.turnoverMultiplier} disabled={noTurnover} onChange={e=>setW("turnoverMultiplier",e.target.value)} placeholder="0" className={inp+" disabled:opacity-40"}/></div>
          <div><Fl hint="เท่าของรางวัล, 0 = ไม่จำกัด">อั้นถอน</Fl><input type="number" min="0" step="0.5" value={wallet.capMult} onChange={e=>setW("capMult",e.target.value)} placeholder="0" className={inp}/></div>
        </div>
        <div className="rounded-xl border border-line bg-sunken p-4"><RewardCatPicker value={wallet.allowedCategories} onChange={(v)=>setW("allowedCategories",v)}/></div>
        </section>
        <section className="space-y-2 border-t border-line pt-5">
        <div><h4 className="text-sm font-semibold text-fg">กฎของกิจกรรม</h4></div>
          <div className="rounded-xl border border-line bg-sunken p-4 text-sm leading-relaxed text-fg-2">
            <p>1. {cumulative?"ฝากสะสมครบทุก":"ฝากต่อรายการทุก"} {perUnit.toLocaleString()} บาท ได้ {ptsPerUnit.toLocaleString()} แต้ม</p>
            <p>2. ใช้ {ptsPerSpin.toLocaleString()} แต้ม หมุนได้ 1 ครั้ง</p>
            <p>3. {dailyLimit>0?"หมุนได้ "+dailyLimit.toLocaleString()+" ครั้งต่อวัน":"หมุนได้ไม่จำกัดครั้งต่อวัน"}</p>
            <p>4. {noTurnover?"รางวัลไม่ต้องทำเทิร์น":"รางวัลต้องทำเทิร์น"+(wallet.turnoverType==="credit"?"เครดิต ":"โอเวอร์ ")+(Number(wallet.turnoverMultiplier)||0)+" เท่า"}{capMult>0?" ถอนได้สูงสุด "+capMult+" เท่าของรางวัล":""}</p>
          </div>
        </section>
      </div>}

      {tab==="rewards"&&<div className="space-y-4 p-5">
      <p className="text-xs text-muted">โอกาสออก = น้ำหนักของรางวัล ÷ น้ำหนักรวมทุกรางวัล (ตอนนี้รวม {totalWeight.toLocaleString()})</p>
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
        {rewards.map((rw,i)=>{
          return (<div key={i} className="flex flex-col gap-3 rounded-xl border border-line bg-sunken p-4">
            <div className="flex items-center gap-2">
              <span className="grid h-7 min-w-[28px] place-items-center rounded-full bg-accent px-2 text-xs font-bold text-accent-fg">#{i+1}</span>
              <span className="flex-1 truncate text-sm font-semibold text-fg">{rw.label||"รางวัลใหม่"}</span>
              <label className="relative h-7 w-7 cursor-pointer overflow-hidden rounded-lg border border-line" title="สีช่องบนกงล้อ" style={{background:rw.color||"#6366F1"}}>
                <input type="color" value={rw.color||"#6366F1"} onChange={e=>updateReward(i,"color",e.target.value)} className="absolute inset-0 h-full w-full cursor-pointer opacity-0"/>
              </label>
              <button type="button" onClick={()=>removeReward(i)} title="ลบรางวัลนี้" className="grid h-7 w-7 place-items-center rounded-lg border border-line text-danger transition-colors hover:bg-danger-soft"><Ic d={I.trash} size={14}/></button>
            </div>
            <div><Fl>ชื่อรางวัล</Fl><input type="text" value={rw.label||""} onChange={e=>updateReward(i,"label",e.target.value)} placeholder="เช่น 10 เครดิต" className={inp}/></div>
            <div className="grid grid-cols-2 gap-2">
              <div><Fl hint={chanceOf(rw)}>น้ำหนัก</Fl><input type="number" min="0" step="1" value={rw.weight||""} onChange={e=>updateReward(i,"weight",Number(e.target.value))} placeholder="0" className={inp}/></div>
              <div><Fl>เครดิตที่ได้ (บาท)</Fl><input type="number" min="0" step="1" value={bahtOf(rw.amount)} onChange={e=>updateReward(i,"amount",satangOf(e.target.value))} placeholder="0" className={inp}/></div>
            </div>
            <p className="text-[11px] text-muted">{Number(rw.amount||0)>0?"ถอนสูงสุด "+(capMult>0?(capOf(rw.amount)/100).toLocaleString()+" บาท":"ไม่จำกัด"):"ไม่มีเครดิต"} · {noTurnover?"ไม่มีเทิร์น":"เทิร์น "+(Number(wallet.turnoverMultiplier)||0)+" เท่า"} (ตั้งที่แท็บตั้งค่ากงล้อ)</p>
            <div><Fl>URL รูปรางวัล</Fl><input type="text" value={rw.imageUrl||""} onChange={e=>updateReward(i,"imageUrl",e.target.value)} placeholder="https://..." className={inp}/></div>
          </div>);})}
        <button type="button" onClick={addReward} className="flex min-h-[160px] flex-col items-center justify-center gap-1.5 rounded-xl border border-dashed border-line text-sm font-medium text-muted transition-colors hover:border-accent hover:text-accent"><Ic d={I.plus} size={20}/> เพิ่มรางวัล</button>
      </div>
      </div>}

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