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

/* ---------- OTP Log — /reports/otp-log ---------- */
const OTP_PURPOSE={register:"สมัคร",forgot_password:"ลืมรหัสผ่าน"};

function OtpLogPage({ toast }) {
  const [rows,setRows]=useState([]),[loading,setLoading]=useState(true),[err,setErr]=useState(null);
  const [q,setQ]=useState(""),[purpose,setPurpose]=useState("auth");
  const debRef=useRef(null);
  const load=useCallback(async(query,pp)=>{ setLoading(true); setErr(null);
    try{ const p=new URLSearchParams({limit:"200",purpose:pp}); if(query)p.set("q",query); const d=await api("/reports/otp-log?"+p.toString()); setRows(Array.isArray(d)?d:[]); }
    catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail&&window.__nxAuthFail();} setErr(e.status===403?"ไม่มีสิทธิ์ดู OTP Log":(e.message||"โหลดไม่สำเร็จ")); }
    finally{ setLoading(false); } },[]);
  useEffect(()=>{ load(q.trim(),purpose); },[purpose,load]);
  useEffect(()=>{ if(debRef.current)clearTimeout(debRef.current); debRef.current=setTimeout(()=>load(q.trim(),purpose),350); return ()=>clearTimeout(debRef.current); },[q]);
  const st=(r)=> r.consumed_at ? {t:"ใช้แล้ว",c:"success"} : (r.expires_at && new Date(r.expires_at)<new Date() ? {t:"หมดอายุ",c:"danger"} : {t:"รอใช้",c:"warn"});
  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="ค้นหา เบอร์ / Ref / รหัส…" 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>
      <div className="flex flex-wrap items-center gap-1 rounded-lg border border-line bg-sunken p-0.5">
        {[["auth","ทั้งหมด"],["register","สมัคร"],["forgot_password","ลืมรหัสผ่าน"]].map(([k,l])=>(<button key={k} onClick={()=>setPurpose(k)} className={"rounded-md px-2.5 py-1 text-xs font-medium transition-colors "+(purpose===k?"bg-accent text-accent-fg shadow-sm":"text-fg-2 hover:text-fg")}>{l}</button>))}</div>
      <button onClick={()=>load(q.trim(),purpose)} 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 hidden text-xs text-muted sm:block tnum">{rows.length} รายการ</div>
    </div>
    {err ? <HistErr msg={err} onRetry={()=>load(q.trim(),purpose)}/>
    : (<div className="overflow-hidden rounded-xl border border-line bg-surface shadow-sm"><div className="overflow-x-auto"><table className="w-full min-w-[760px] border-collapse text-sm">
      <thead className="border-b-2 border-accent/25 bg-accent-soft"><tr>{histTh("เวลา")}{histTh("เบอร์")}{histTh("ประเภท")}{histTh("รหัส OTP")}{histTh("Ref")}{histTh("ครั้ง","text-right")}{histTh("สถานะ","pr-4")}</tr></thead>
      <tbody>
        {loading ? Array.from({length:8}).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)=>{ const s=st(r); return (<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 mono text-xs text-fg-2">{r.phone||"-"}</td>
            <td className="px-3 text-xs text-fg-2">{OTP_PURPOSE[r.purpose]||r.purpose||"-"}</td>
            <td className="px-3 mono text-xs font-semibold text-accent">{r.otp_code||"-"}</td>
            <td className="px-3 mono text-[11px] text-faint">{r.ref_code||"-"}</td>
            <td className="px-3 text-right tnum text-muted">{Number(r.attempts||0)}</td>
            <td className="pr-4"><Badge tone={s.c}>{s.t}</Badge></td>
          </tr>); })}
      </tbody>
    </table></div></div>)}
  </div>);
}
