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

/* ---------- รายชื่อมิจฉาชีพ — /fraud-list (GET/POST/DELETE) ---------- */
function FraudAddModal({ onClose, onDone, toast }) {
  const [f,setF]=useState({ phone:"", bank_code:"", bank_account_no:"", full_name:"", reason:"" });
  const [busy,setBusy]=useState(false);
  const set=(k,v)=>setF(o=>({...o,[k]:v}));
  const inp="mt-1 h-10 w-full rounded-lg border border-line bg-sunken px-3 text-sm text-fg placeholder:text-faint focus:border-accent focus:bg-surface focus:outline-none focus:ring-4 focus:ring-[var(--accent-ring)]";
  const submit=async()=>{
    if(!f.phone.trim() && !f.bank_account_no.trim() && !f.full_name.trim()){ toast("กรอกอย่างน้อย 1 ช่อง (เบอร์/เลขบัญชี/ชื่อ)"); return; }
    setBusy(true);
    try{ await api("/fraud-list",{method:"POST",body:{phone:f.phone.trim()||null,bank_code:f.bank_code||null,bank_account_no:f.bank_account_no.trim()||null,full_name:f.full_name.trim()||null,reason:f.reason.trim()||null}});
      toast("เพิ่มรายชื่อแล้ว"); onDone&&onDone(); onClose();
    }catch(e){ toast(e.message||"ไม่สำเร็จ"); }finally{ setBusy(false); }
  };
  return (<div className="fixed inset-0 z-[80] flex items-center justify-center p-4 fade-in" onMouseDown={()=>!busy&&onClose()}>
    <div className="absolute inset-0 bg-black/55"/>
    <div className="pop relative max-h-[92vh] w-full max-w-sm overflow-y-auto rounded-2xl border border-line bg-surface2 p-5 shadow-lg" onMouseDown={(e)=>e.stopPropagation()}>
      <div className="text-base font-semibold">เพิ่มรายชื่อมิจฉาชีพ</div>
      <p className="mt-0.5 text-xs text-muted">กรอกอย่างน้อย 1 ช่อง</p>
      <label className="mt-3 block"><span className="text-xs font-medium text-fg-2">เบอร์โทร</span><input className={inp+" mono"} value={f.phone} onChange={(e)=>set("phone",e.target.value)} placeholder="08xxxxxxxx"/></label>
      <label className="mt-3 block"><span className="text-xs font-medium text-fg-2">ธนาคาร</span>
        <select className={inp} value={f.bank_code} onChange={(e)=>set("bank_code",e.target.value)}><option value="">— เลือกธนาคาร —</option>{BANK_OPTIONS.map(([c,n])=><option key={c} value={c}>{n}</option>)}</select></label>
      <label className="mt-3 block"><span className="text-xs font-medium text-fg-2">เลขบัญชี</span><input className={inp+" mono"} value={f.bank_account_no} onChange={(e)=>set("bank_account_no",e.target.value)} placeholder="เลขบัญชี"/></label>
      <label className="mt-3 block"><span className="text-xs font-medium text-fg-2">ชื่อ–นามสกุล</span><input className={inp} value={f.full_name} onChange={(e)=>set("full_name",e.target.value)} placeholder="ชื่อบัญชี"/></label>
      <label className="mt-3 block"><span className="text-xs font-medium text-fg-2">เหตุผล</span><input className={inp} value={f.reason} onChange={(e)=>set("reason",e.target.value)} placeholder="เช่น โกงสลิป"/></label>
      <div className="mt-4 flex items-center justify-end gap-2">
        <button onClick={onClose} className="h-9 rounded-lg border border-line bg-surface px-3 text-sm font-medium text-fg-2 hover:bg-sunken">ยกเลิก</button>
        <button disabled={busy} onClick={submit} className="h-9 rounded-lg bg-danger px-4 text-sm font-semibold text-white disabled:opacity-50" style={{background:"var(--danger)"}}>{busy?"กำลังทำ…":"เพิ่ม"}</button>
      </div>
    </div>
  </div>);
}

function FraudListPage({ toast }) {
  const [rows,setRows]=useState([]);
  const [loading,setLoading]=useState(true);
  const [err,setErr]=useState(null);
  const [q,setQ]=useState("");
  const [addOpen,setAddOpen]=useState(false);
  const [busyId,setBusyId]=useState(null);
  const debRef=useRef(null);
  const canManage=canAny(["tool_fraud_list","users"]);
  const load=useCallback(async(query)=>{
    setLoading(true); setErr(null);
    try{ const d=await api("/fraud-list"+(query?"?q="+encodeURIComponent(query):"")); 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]);
  useEffect(()=>{ if(debRef.current)clearTimeout(debRef.current); debRef.current=setTimeout(()=>load(q.trim()),350); return ()=>clearTimeout(debRef.current); },[q,load]);
  const del=async(r)=>{ if(!window.confirm("ลบรายชื่อนี้ออกจากบัญชีดำ?"))return; setBusyId(r.id);
    try{ await api("/fraud-list/"+r.id,{method:"DELETE"}); toast("ลบแล้ว"); load(q.trim()); }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">
      <div className="relative flex-1 sm:max-w-xs">
        <span className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted"><Ic d={I.search} size={16}/></span>
        <input value={q} onChange={(e)=>setQ(e.target.value)} placeholder="ค้นหา เบอร์ / เลขบัญชี / ชื่อ…" className="h-9 w-full rounded-lg border border-line bg-surface pl-9 pr-3 text-sm text-fg placeholder:text-faint focus:border-accent focus:outline-none focus:ring-4 focus:ring-[var(--accent-ring)]"/>
      </div>
      <button onClick={()=>load(q.trim())} 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>
      {canManage && <button onClick={()=>setAddOpen(true)} className="flex h-9 items-center gap-1.5 rounded-lg px-3.5 text-sm font-semibold text-white shadow-sm" style={{background:"var(--danger)"}}><Ic d={I.plus} size={17} sw={2}/> เพิ่มรายชื่อ</button>}
      <div className="ml-auto hidden text-xs text-muted sm:block tnum">{rows.length} รายการ</div>
    </div>
    {err ? (<div className="rounded-xl border border-line bg-surface px-4 py-16 text-center shadow-sm"><div className="mx-auto mb-2 grid h-10 w-10 place-items-center rounded-full text-danger" style={{background:"var(--danger-soft)"}}><Ic d={I.warn2} size={20}/></div><div className="text-sm font-medium text-fg-2">{err}</div><button onClick={()=>load(q.trim())} className="mt-3 rounded-lg border border-line px-3 py-1.5 text-xs font-medium text-fg-2 hover:bg-sunken">ลองใหม่</button></div>)
    : (<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>เพิ่มเมื่อ</H><H>ชื่อ</H><H>เบอร์</H><H>บัญชี</H><H>เหตุผล</H><H>เพิ่มโดย</H><H extra="text-right pr-4">จัดการ</H></tr></thead>
      <tbody>
        {loading ? Array.from({length:6}).map((_,i)=>(<tr key={i} className="border-b border-line-soft"><td className="px-3 py-3" colSpan="7"><div className="skel h-5 w-full"/></td></tr>))
          : rows.length===0 ? (<tr><td colSpan="7" 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 font-medium text-fg">{r.full_name||"-"}</td>
            <td className="px-3 mono text-xs text-fg-2">{r.phone||"-"}</td>
            <td className="px-3"><div className="flex items-center gap-1.5"><BankLogo code={r.bank_code} size={22}/><span className="mono text-xs text-fg-2">{r.bank_account_no||"-"}</span></div></td>
            <td className="px-3 text-xs text-muted"><span className="truncate">{r.reason||"-"}</span></td>
            <td className="px-3 text-xs text-faint">{r.added_by_username||"-"}</td>
            <td className="pr-4"><div className="flex items-center justify-end">
              {canManage && <button disabled={busyId===r.id} title="ลบ" onClick={()=>del(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.trash} size={14}/></button>}
            </div></td>
          </tr>))}
      </tbody>
    </table></div></div>)}
    {addOpen && <FraudAddModal onClose={()=>setAddOpen(false)} onDone={()=>load(q.trim())} toast={toast}/>}
  </div>);
}
