/* ==========================================================================
 * ADMIN NEXT — page-promoreq.jsx  (แยกไฟล์ละหน้า; โหลดผ่าน <script type="text/babel">)
 * ========================================================================== */

/* ---------- โปรฟรีรออนุมัติ — /promo-requests (approve/reject) ---------- */
function PromoRequestsPage({ toast }) {
  const [rows,setRows]=useState([]),[loading,setLoading]=useState(true),[err,setErr]=useState(null);
  const [busyId,setBusyId]=useState(null);
  const load=useCallback(async()=>{ setLoading(true); setErr(null);
    try{ const d=await api("/promo-requests"); setRows(Array.isArray(d)?d:[]); }
    catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail&&window.__nxAuthFail();} setErr(e.status===403?"ไม่มีสิทธิ์ดูโปรฟรีรออนุมัติ":(e.message||"โหลดไม่สำเร็จ")); }
    finally{ setLoading(false); } },[]);
  useEffect(()=>{ load(); },[load]);
  const approve=async(r)=>{ if(!window.confirm("อนุมัติโปรฟรีให้ "+(r.username||"")+"?"))return; setBusyId(r.id);
    try{ await api("/promo-requests/"+r.id+"/approve",{method:"POST",body:{}}); toast("อนุมัติแล้ว"); load(); }catch(e){ toast(e.message||"ไม่สำเร็จ"); }finally{ setBusyId(null); } };
  const reject=async(r)=>{ const reason=window.prompt("เหตุผลการปฏิเสธ:",""); if(reason===null)return; setBusyId(r.id);
    try{ await api("/promo-requests/"+r.id+"/reject",{method:"POST",body:{reason}}); toast("ปฏิเสธแล้ว"); load(); }catch(e){ toast(e.message||"ไม่สำเร็จ"); }finally{ setBusyId(null); } };
  const H=({children,extra=""})=>(<th className={"whitespace-nowrap px-3 py-2.5 text-left text-[13px] font-bold text-fg-2 "+extra}>{children}</th>);
  return (<div className="space-y-3">
    <div className="flex flex-wrap items-center gap-2">
      <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>
      <div className="ml-auto text-xs text-muted tnum">รออนุมัติ {rows.length} รายการ</div>
    </div>
    {err ? <HistErr msg={err} onRetry={load}/>
    : (<div className="overflow-hidden rounded-xl border border-line bg-surface shadow-sm"><div className="overflow-x-auto"><table className="w-full min-w-[820px] border-collapse text-sm">
      <thead className="border-b-2 border-accent/25 bg-accent-soft"><tr>{H({children:"เวลา"})}{H({children:"สมาชิก"})}{H({children:"โปรโมชั่น"})}{H({children:"โบนัส",extra:"text-right"})}{H({children:"เทิร์น",extra:"text-right"})}{H({children:"จัดการ",extra:"text-right pr-4"})}</tr></thead>
      <tbody>
        {loading ? Array.from({length:5}).map((_,i)=>(<tr key={i} className="border-b border-line-soft"><td className="px-3 py-3" colSpan="6"><div className="skel h-5 w-full"/></td></tr>))
          : rows.length===0 ? (<tr><td colSpan="6" className="px-4 py-16 text-center text-sm font-medium text-fg-2">ไม่มีคำขอรออนุมัติ</td></tr>)
          : rows.map((r,i)=>(<tr key={r.id||i} className="border-b border-line-soft transition-colors last:border-0 hover:bg-sunken/50">
            <td className="whitespace-nowrap px-3 py-2.5 text-xs text-fg-2">{fmtDT(r.created_at)}</td>
            <td className="px-3"><div className="min-w-0"><div className="truncate font-semibold text-accent">{r.username||r.full_name||"-"}</div><div className="truncate text-[11px] text-muted">{r.full_name&&r.full_name!==r.username?r.full_name+" · ":""}{r.phone||""}</div></div></td>
            <td className="px-3 text-xs text-fg-2">{r.promo_name||r.promo_code||"-"}</td>
            <td className="whitespace-nowrap px-3 text-right font-semibold tnum text-warn">{money2(r.bonus_amount)}</td>
            <td className="whitespace-nowrap px-3 text-right tnum text-muted">{money2(r.turnover_needed)}</td>
            <td className="pr-4"><div className="flex items-center justify-end gap-1">
              <button disabled={busyId===r.id} title="ปฏิเสธ" onClick={()=>reject(r)} className="grid h-7 w-7 place-items-center rounded-lg border hover:bg-sunken disabled:opacity-50" style={{borderColor:"var(--danger)",color:"var(--danger)"}}><Ic d={I.x} size={14}/></button>
              <button disabled={busyId===r.id} title="อนุมัติ" onClick={()=>approve(r)} className="grid h-7 w-7 place-items-center rounded-lg text-white disabled:opacity-50" style={{background:"var(--success)"}}><Ic d={I.check} size={14} sw={3}/></button>
            </div></td>
          </tr>))}
      </tbody>
    </table></div></div>)}
  </div>);
}
