/* ==========================================================================
 * ADMIN NEXT — page-affiliate.jsx  (ตั้งค่าพันธมิตร — อัตราค่าคอม 4 ชั้น + ตั้งค่าระบบ)
 * ========================================================================== */
const AFF_LV=[["A","ชั้น 1"],["B","ชั้น 2"],["C","ชั้น 3"],["D","ชั้น 4"]];
const AFF_SATANG_KEYS=["affiliate_min_withdraw","affiliate_credit_threshold"];
function AffiliatePage({ toast }) {
  const [cfg,setCfg]=useState({}),[rates,setRates]=useState({}),[stats,setStats]=useState({}),[board,setBoard]=useState([]);
  const [loading,setLoading]=useState(true),[err,setErr]=useState(null),[saving,setSaving]=useState(""),[batch,setBatch]=useState({date:bkkDate(0),force:false}),[batchOut,setBatchOut]=useState(null),[confirmBatch,setConfirmBatch]=useState(false);

  const load=useCallback(async()=>{ setLoading(true); setErr(null);
    try{ const [r,s,st,lb]=await Promise.all([api("/affiliate/config"),api("/affiliate/settings"),api("/affiliate/stats").catch(()=>({})),api("/affiliate/leaderboard?limit=20").catch(()=>[])]);
      const c={...s}; for(const k of AFF_SATANG_KEYS) c[k]=String(N(s[k])/100);
      setCfg(c); setRates(Object.fromEntries([1,2,3,4].map(l=>[l,String(r[l]??0)]))); setStats(st||{}); setBoard(Array.isArray(lb)?lb:[]); }
    catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail?.();} setErr(e.status===403?"ไม่มีสิทธิ์ตั้งค่าพันธมิตร":(e.message||"โหลดไม่สำเร็จ")); }
    finally{ setLoading(false); } },[]);
  useEffect(()=>{ load(); },[load]);

  const set=(k,v)=>setCfg(c=>({...c,[k]:v}));
  const saveSettings=async()=>{ setSaving("settings");
    try{ const body={...cfg}; for(const k of AFF_SATANG_KEYS) body[k]=String(Math.round(N(cfg[k])*100));
      await api("/affiliate/settings",{method:"PUT",body}); toast("บันทึกการตั้งค่าแล้ว"); }
    catch(e){ toast(e.message||"บันทึกไม่สำเร็จ"); } finally{ setSaving(""); } };
  const saveRates=async()=>{ setSaving("rates");
    try{ const body={}; for(const l of [1,2,3,4]) body["l"+l]=N(rates[l]);
      const d=await api("/affiliate/config",{method:"PUT",body}); if(d&&d.rates) setRates(Object.fromEntries([1,2,3,4].map(l=>[l,String(d.rates[l]??0)]))); toast("บันทึกอัตราค่าคอมแล้ว"); }
    catch(e){ toast(e.message||"บันทึกไม่สำเร็จ"); } finally{ setSaving(""); } };
  const runBatch=async()=>{ setSaving("batch"); setBatchOut(null);
    try{ const d=await api("/affiliate/batch",{method:"POST",body:{date:batch.date,force:batch.force}}); setBatchOut(d); toast("คำนวณเสร็จแล้ว"); }
    catch(e){ toast(e.message||"คำนวณไม่สำเร็จ"); } finally{ setSaving(""); setConfirmBatch(false); } };

  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 Hint=({children})=><div className="mt-1 text-[11px] text-faint">{children}</div>;
  const Nm=({k,ph="",step="1"})=><input type="number" min="0" step={step} value={cfg[k]??""} onChange={e=>set(k,e.target.value)} placeholder={ph} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/>;
  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,sub,children})=><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">{title}</h3>{sub&&<p className="mt-0.5 text-xs text-muted">{sub}</p>}</div>{children}</div>;
  const SaveBtn=({id,onClick,label})=><div className="flex justify-end"><button disabled={!!saving} onClick={onClick} 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===id?"กำลังบันทึก…":label}</button></div>;
  const Stat=({label,value,cls})=><div className="rounded-xl border border-line bg-surface p-4 shadow-sm"><div className="text-xs text-muted">{label}</div><div className={"mt-1 text-xl font-bold tnum "+(cls||"text-fg")}>{value}</div></div>;

  return (<div className="space-y-5">
    <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
      {Stat({label:"ผู้ใช้ที่มียอดค่าคอม",value:cashInt(stats.usersWithCredit||0),cls:"text-accent"})}
      {Stat({label:"ยอดค่าคอมคงค้างรวม",value:money2(stats.totalCreditSatang),cls:"text-success"})}
      {Stat({label:"ค่าคอมวันนี้",value:money2(stats.todayCreditSatang)})}
      {Stat({label:"รายการทั้งหมด",value:cashInt(stats.totalHistories||0)})}
    </div>

    {Section({title:"ตั้งค่าระบบพันธมิตร",sub:"ระบบพันธมิตร 4 ชั้น (A/B/C/D) — คิดค่าคอมเมื่อลูกทีมเล่นจนเครดิตหมด",children:<>
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
        <div><Lb>เปิดระบบพันธมิตร</Lb>{Sel({k:"affiliate_enabled",options:[["1","เปิด"],["0","ปิด"]]})}</div>
        <div><Lb>ขั้นต่ำถอนค่าคอม (บาท)</Lb>{Nm({k:"affiliate_min_withdraw",ph:"300"})}</div>
        <div><Lb>เครดิตคงเหลือที่ถือว่า "หมด" (บาท)</Lb>{Nm({k:"affiliate_credit_threshold",ph:"5",step:"0.01"})}<Hint>ค่าเริ่มต้น 5 บาท</Hint></div>
        <div><Lb>คิดค่าคอมซ้ำได้</Lb>{Sel({k:"affiliate_deposit_reusable",options:[["0","ครั้งแรกเท่านั้น"],["1","ทุกครั้งที่เครดิตหมด"]]})}</div>
        <div><Lb>ฝาก Manual (แอดมินเติม)</Lb>{Sel({k:"affiliate_skip_direct",options:[["1","ข้าม (ไม่คิดค่าคอม)"],["0","ไม่ข้าม (คิดค่าคอม)"]]})}</div>
        <div><Lb>โปรโมชั่นฟรี</Lb>{Sel({k:"affiliate_skip_free_promo",options:[["1","ข้าม (ไม่คิดค่าคอม)"],["0","ไม่ข้าม (คิดค่าคอม)"]]})}</div>
      </div>
      {SaveBtn({id:"settings",onClick:saveSettings,label:"บันทึกการตั้งค่า"})}
    </>})}

    {Section({title:"อัตราค่าคอมแต่ละชั้น (%)",sub:"เช่น 0.50 = 0.50% — ตั้งอัตราพิเศษรายคนได้ที่หน้าสมาชิก",children:<>
      <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
        {[1,2,3,4].map(l=><div key={l}><Lb>ชั้น {AFF_LV[l-1][0]} ({AFF_LV[l-1][1]})</Lb><input type="number" min="0" max="100" step="0.01" value={rates[l]??""} onChange={e=>setRates(r=>({...r,[l]:e.target.value}))} placeholder="0.50" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>)}
      </div>
      {SaveBtn({id:"rates",onClick:saveRates,label:"บันทึกอัตราค่าคอม"})}
    </>})}

    {Section({title:"คำนวณค่าคอมย้อนหลัง",sub:"คำนวณใหม่ให้ลูกทีมที่มีความเคลื่อนไหวในวันที่เลือก (บันทึกจริง)",children:<>
      <div className="flex flex-wrap items-end gap-3">
        <div><Lb>วันที่</Lb><input type="date" value={batch.date} onChange={e=>setBatch(b=>({...b,date:e.target.value}))} className="rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
        <label className="flex items-center gap-2 pb-2 text-sm text-fg-2"><input type="checkbox" checked={batch.force} onChange={e=>setBatch(b=>({...b,force:e.target.checked}))}/> บังคับคำนวณใหม่</label>
        <button disabled={!!saving||!batch.date} onClick={()=>setConfirmBatch(true)} className="ml-auto rounded-lg border border-line bg-surface px-5 py-2 text-sm font-medium text-fg hover:bg-sunken disabled:opacity-50">{saving==="batch"?"กำลังคำนวณ…":"เริ่มคำนวณ"}</button>
      </div>
      {batchOut&&<div className="grid grid-cols-3 gap-3 rounded-lg bg-sunken p-3 text-center text-sm">
        <div><div className="text-lg font-bold tnum">{cashInt(batchOut.scanned||0)}</div><div className="text-xs text-muted">ตรวจ</div></div>
        <div><div className="text-lg font-bold tnum text-success">{cashInt(batchOut.processed||0)}</div><div className="text-xs text-muted">คำนวณสำเร็จ</div></div>
        <div><div className="text-lg font-bold tnum text-muted">{cashInt(batchOut.skipped||0)}</div><div className="text-xs text-muted">ข้าม</div></div>
      </div>}
    </>})}

    {Section({title:"อันดับพันธมิตร",sub:"20 อันดับยอดค่าคอมคงค้างสูงสุด",children:
      <div className="overflow-x-auto -mx-5"><table className="w-full min-w-[640px] border-collapse text-sm">
        <thead className="border-b-2 border-accent/25 bg-accent-soft"><tr>{histTh("#","text-center")}{histTh("ผู้ใช้")}{histTh("ลูกทีม","text-center")}{histTh("ค่าคอมคงค้าง","text-right")}{histTh("ได้รับรวม","text-right pr-5")}</tr></thead>
        <tbody>{board.length===0 ? (<tr><td colSpan="5" className="px-4 py-10 text-center text-sm text-fg-2">ยังไม่มีพันธมิตร</td></tr>)
          : board.map((r,i)=>(<tr key={r.id||i} className="border-b border-line-soft last:border-0 hover:bg-sunken/50">
            <td className={"px-3 py-2.5 text-center font-bold tnum "+(i<3?"text-warn":"text-muted")}>{i+1}</td>
            <td className="px-3"><div className="truncate font-medium text-fg">{r.username||"-"}</div><div className="truncate mono text-[11px] text-faint">{r.phone||""}</div></td>
            <td className="px-3 text-center tnum">{cashInt(r.downline_count||0)}</td>
            <td className="whitespace-nowrap px-3 text-right font-semibold tnum text-success">{money2(r.affiliate_credit)}</td>
            <td className="whitespace-nowrap px-3 pr-5 text-right tnum text-fg-2">{money2(r.total_earned)}</td>
          </tr>))}</tbody>
      </table></div>})}

    {confirmBatch&&<SimpleConfirmModal title="คำนวณค่าคอมย้อนหลัง" msg={"คำนวณค่าคอมของวันที่ "+batch.date+(batch.force?" (บังคับคำนวณใหม่)":"")+" และบันทึกผลจริง ยืนยันหรือไม่?"} busy={saving==="batch"} onOk={runBatch} onCancel={()=>setConfirmBatch(false)}/>}
  </div>);
}
