/* ==========================================================================
 * ADMIN NEXT — page-activitylog.jsx  (Activity Log — ประวัติการทำงาน)
 * ========================================================================== */

const ACT_PATH_MAP=[
  [/^\/users\/[^/]+\/adjust$/,"ปรับเครดิตสมาชิก"],
  [/^\/users\/[^/]+\/sync-game-credit$/,"ซิงค์เครดิตเกม"],
  [/^\/users\/[^/]+\/reset-password$/,"รีเซ็ตรหัสผ่านสมาชิก"],
  [/^\/users\/[^/]+\/toggle-ban$/,"แบน/ปลดแบนสมาชิก"],
  [/^\/users\/[^/]+\/tags$/,"แก้ไขแท็กสมาชิก"],
  [/^\/users\/[^/]+$/,"แก้ไขข้อมูลสมาชิก"],
  [/^\/admins\/[^/]+\/permissions$/,"แก้ไขสิทธิ์ผู้ดูแล"],
  [/^\/admins\/[^/]+\/tx-limits$/,"ตั้งลิมิตฝากถอนทีมงาน"],
  [/^\/admins\/[^/]+\/status$/,"เปลี่ยนสถานะผู้ดูแล"],
  [/^\/admins\/[^/]+\/role$/,"เปลี่ยนยศผู้ดูแล"],
  [/^\/admins\/[^/]+\/time-restriction$/,"ตั้งเวลาใช้งานผู้ดูแล"],
  [/^\/admins\/[^/]+$/,"จัดการผู้ดูแล"],
  [/^\/admins$/,"สร้างผู้ดูแลใหม่"],
  [/^\/settings$/,"บันทึกตั้งค่าเว็บ"],
  [/^\/settings\/turnover/,"ตั้งค่าเคลียร์เทิร์น"],
  [/^\/checkin\/config$/,"ตั้งค่ารางวัลเช็คอิน"],
  [/^\/role-presets$/,"บันทึก Preset สิทธิ์"],
  [/^\/deposit-accounts/,"จัดการบัญชีฝาก"],
  [/^\/central-accounts/,"จัดการบัญชีกลาง"],
  [/^\/withdrawal-accounts/,"จัดการบัญชีถอน"],
  [/^\/payment-providers/,"จัดการผู้ให้บริการชำระเงิน"],
  [/^\/promotions/,"จัดการโปรโมชั่น"],
  [/^\/coupons/,"จัดการคูปอง"],
  [/^\/prediction/,"จัดการทายผล"],
  [/^\/wheel/,"จัดการวงล้อ"],
  [/^\/cashback/,"จัดการคืนยอดเสีย"],
  [/^\/games\/sort/,"จัดเรียงเกม"],
  [/^\/games\/featured/,"จัดการเกมแนะนำ"],
  [/^\/games/,"จัดการเกม"],
  [/^\/provider-logos/,"จัดการโลโก้ค่ายเกม"],
  [/^\/marketing\/orgs/,"จัดการสายการตลาด"],
  [/^\/marketing\/channels/,"จัดการช่องทางสมัคร"],
  [/^\/member-levels/,"จัดการระดับสมาชิก"],
  [/^\/notifications/,"จัดการการแจ้งเตือน"],
  [/^\/popup/,"จัดการ Popup"],
  [/^\/domains/,"จัดการโดเมน"],
  [/^\/turnover\/clear$/,"เคลียร์เทิร์นสมาชิก"],
  [/^\/leaderboard/,"จัดการ Leaderboard"],
  [/^\/whitelabel/,"ตั้งค่า White Label"],
  [/^\/abd/,"จัดการ ABD Console"],
  [/^\/line/,"จัดการ LINE Connect"],
];

function actLogSummary(r){
  const d=r.details||{};
  const body=d.body||{};
  const path=String(r.path||"").replace(/^\/api\/admin/,"").split("?")[0];
  const method=r.method||"";
  const member=actLogMember(r);
  const amount=actLogAmount(d.amount??body.amount);

  if(["อนุมัติยอดฝาก","อนุมัติยอดถอน"].includes(r.action))
    return {title:r.action,detail:[member,amount?`${amount}`:null].filter(Boolean).join(" · "),tone:r.action.includes("ฝาก")?"success":"info"};

  if(/^\/withdrawals\/[^/]+\/payout-account$/.test(path))
    return {title:"แก้บัญชีที่ใช้จ่าย (รายการถอน)",detail:member||r.target_id||"",tone:"warn"};

  if(/เครดิต|โบนัส|เทิร์น/.test(r.action||"")||/^\/users\/[^/]+\/adjust$/.test(path)){
    const type=body.adjustType||body.creditType||"";
    let title="ปรับเครดิตสมาชิก";
    if(r.action?.includes("ตัดเครดิต")||type==="deduct"||Number(body.amount||0)<0) title="หักเครดิต";
    else if(r.action?.includes("เพิ่มเครดิต")||type==="add"||Number(body.amount||0)>0) title="เพิ่มเครดิต";
    else if(r.action?.includes("เคลียร์เทิร์น")||type==="clear_turnover") title="เคลียร์เทิร์น";
    const reason=d.reason||body.reason||"";
    return {title,detail:[member,amount?`${amount}`:null,reason?`"${reason}"`:null].filter(Boolean).join(" · "),tone:title==="หักเครดิต"?"danger":"success"};
  }

  if(/สร้างยูส/.test(r.action||"")||path==="/admins"&&method==="POST"){
    const username=d.username||body.username||r.target_id||"-";
    return {title:"สร้างผู้ดูแลใหม่",detail:username,tone:"info"};
  }

  if(method==="DELETE"){
    for(const [re,label] of ACT_PATH_MAP){ if(re.test(path)) return {title:"ลบ"+label.replace(/^จัดการ/,""),detail:member||r.target_id||"",tone:"danger"}; }
    return {title:"ลบข้อมูล",detail:path,tone:"danger"};
  }

  if(/^\/admins\/[^/]+\/permissions$/.test(path)){
    const perms=body.permissions||d.permissions||[];
    return {title:"แก้ไขสิทธิ์ผู้ดูแล",detail:`${perms.length} สิทธิ์`,tone:"warn"};
  }
  if(/^\/admins\/[^/]+\/status$/.test(path))
    return {title:body.status==="suspended"?"ระงับผู้ดูแล":"เปิดใช้งานผู้ดูแล",detail:r.target_id||"",tone:body.status==="suspended"?"danger":"success"};
  if(/^\/admins\/[^/]+\/role$/.test(path))
    return {title:"เปลี่ยนยศผู้ดูแล",detail:`ยศใหม่ ${body.role||"-"}`,tone:"warn"};
  if(path==="/settings")
    return {title:"บันทึกตั้งค่าเว็บ",detail:`แก้ไข ${Object.keys(body||{}).length} ค่า`,tone:"info"};

  for(const [re,label] of ACT_PATH_MAP){
    if(re.test(path)){
      // เติมคำนำหน้า (เพิ่ม/แก้ไข) เฉพาะชื่อที่ขึ้นต้นด้วย "จัดการ"; ชื่อที่เป็นประโยคเต็มอยู่แล้วใช้ตามเดิม
      if(label.startsWith("จัดการ")){
        const verb=method==="POST"?"เพิ่ม":method==="PATCH"||method==="PUT"?"แก้ไข":"";
        return {title:verb?`${verb}${label.replace(/^จัดการ/,"")}`:label,detail:member||r.target_id||"",tone:"info"};
      }
      return {title:label,detail:member||r.target_id||"",tone:"info"};
    }
  }

  return {title:r.action||`${method} ${path}`||"-",detail:member||r.target_id||"",tone:"muted"};
}

function actLogMember(r){
  const u=r.target_user||r.targetUser||null;
  if(!u) return null;
  const main=u.phone||u.username||u.full_name||u.id;
  const sub=u.full_name&&u.full_name!==main?u.full_name:null;
  return sub?`${main} (${sub})`:main;
}
function actLogAmount(v){
  if(v===null||v===undefined||v==="") return null;
  return baht(v);
}
// แยกข้อมูลเป็นส่วนๆ: ให้ใคร / เท่าไหร่ / หมายเหตุ — เพื่อแสดงเป็นคอลัมน์ให้อ่านง่าย
function actLogParts(r){
  const d=r.details||{}; const body=d.body||{};
  const path=String(r.path||"").replace(/^\/api\/admin/,"").split("?")[0];
  let who=actLogMember(r)||r.target_id||null;
  // รายการแก้บัญชีจ่าย: ให้ช่อง "ให้ใคร/เป้าหมาย" โชว์เป็นบัญชีที่ปรับ
  if(/^\/withdrawals\/[^/]+\/payout-account$/.test(path)) who=d.account||body.account||who;
  let amt=d.amount; if(amt===null||amt===undefined||amt==="") amt=body.amount;
  const hasAmt=!(amt===null||amt===undefined||amt==="");
  const note=d.reason||body.reason||d.note||body.note||null;
  return { who, amount:hasAmt?baht(amt):null, amtNum:hasAmt?Number(amt):0, note };
}

// ----- จัดหมวดหมู่รายการ เพื่อใช้กรอง -----
const ACT_CATS=[
  ["","ทุกประเภท"],
  ["finance_tx","อนุมัติฝาก/ถอน"],
  ["credit","เครดิต/เทิร์น/โบนัส"],
  ["member","สมาชิก"],
  ["admin","ผู้ดูแลระบบ"],
  ["bank","บัญชีธนาคาร"],
  ["marketing","การตลาด/โปรโมชั่น"],
  ["game","เกม"],
  ["system","ตั้งค่า/ระบบ"],
  ["other","อื่นๆ"],
];
// ซ่อนรายการที่ไม่จำเป็นออกจาก Activity Log (เช่น ซิงค์เครดิตเกม ที่ขึ้นรัวๆ)
function actLogHidden(r){
  const path=String(r.path||"").replace(/^\/api\/admin/,"").split("?")[0];
  return /^\/users\/[^/]+\/sync-game-credit$/.test(path);
}
function actLogCategory(r){
  const path=String(r.path||"").replace(/^\/api\/admin/,"").split("?")[0];
  const a=r.action||"";
  if(["อนุมัติยอดฝาก","อนุมัติยอดถอน"].includes(a)||/^\/(deposits|withdrawals)\//.test(path)) return "finance_tx";
  if(/เครดิต|โบนัส|เทิร์น/.test(a)||/^\/users\/[^/]+\/adjust$/.test(path)||/turnover/.test(path)) return "credit";
  if(/^\/users(\/|$)/.test(path)) return "member";
  if(/^\/admins(\/|$)/.test(path)||/^\/role-presets/.test(path)) return "admin";
  if(/(deposit-accounts|central-accounts|withdrawal-accounts|payment-providers)/.test(path)) return "bank";
  if(/(promotions|coupons|prediction|wheel|cashback|marketing|member-levels|leaderboard|checkin)/.test(path)) return "marketing";
  if(/(games|provider-logos)/.test(path)) return "game";
  if(/(settings|notifications|popup|domains|whitelabel|abd|line)/.test(path)) return "system";
  return "other";
}

function ActivityLogPage({ toast }) {
  const [rows,setRows]=useState([]);
  const [loading,setLoading]=useState(true);
  const [err,setErr]=useState(null);
  const [q,setQ]=useState("");
  const [cat,setCat]=useState("");
  const [page,setPage]=useState(1);
  const [size,setSize]=useState(50);
  const debRef=useRef(null);
  const load=useCallback(async(query)=>{
    setLoading(true); setErr(null);
    try{ const d=await api("/activity-logs?limit=300"+(query?"&q="+encodeURIComponent(query):"")); setRows((d&&d.rows)||[]); }
    catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail&&window.__nxAuthFail();} setErr(e.status===403?"บัญชีนี้ไม่มีสิทธิ์ดู Activity Log":(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]);
  useEffect(()=>{ setPage(1); },[q,cat,rows.length]);
  const visibleRows=rows.filter(r=>!actLogHidden(r));
  const filtered=cat?visibleRows.filter(r=>actLogCategory(r)===cat):visibleRows;
  const paged=filtered.slice((page-1)*size,page*size);

  const TONE_CLS={success:"bg-green-500/10 text-green-400",danger:"bg-red-500/10 text-red-400",warn:"bg-yellow-500/10 text-yellow-400",info:"bg-blue-500/10 text-blue-400",muted:"bg-sunken text-muted"};

  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>
      <select value={cat} onChange={(e)=>setCat(e.target.value)} className="h-9 rounded-lg border border-line bg-surface px-2.5 text-sm text-fg-2 focus:border-accent focus:outline-none">
        {ACT_CATS.map(([k,l])=><option key={k||"all"} value={k}>{l}</option>)}
      </select>
      <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>
      <div className="ml-auto hidden text-xs text-muted sm:block tnum">{filtered.length}{cat?" / "+visibleRows.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>
        <th className="whitespace-nowrap px-3 py-2.5 text-left text-[13px] font-bold text-fg-2">เวลาไหน</th>
        <th className="whitespace-nowrap px-3 py-2.5 text-left text-[13px] font-bold text-fg-2">ทำอะไร</th>
        <th className="whitespace-nowrap px-3 py-2.5 text-left text-[13px] font-bold text-fg-2">ทำโดย</th>
        <th className="whitespace-nowrap px-3 py-2.5 text-left text-[13px] font-bold text-fg-2">ให้ใคร / เป้าหมาย</th>
        <th className="whitespace-nowrap px-3 py-2.5 text-right text-[13px] font-bold text-fg-2">เท่าไหร่</th>
        <th className="whitespace-nowrap px-3 py-2.5 text-left text-[13px] font-bold text-fg-2">หมายเหตุ</th>
        <th className="whitespace-nowrap px-3 py-2.5 text-left text-[13px] font-bold text-fg-2">IP</th>
      </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>))
          : filtered.length===0 ? (<tr><td colSpan="7" className="px-4 py-16 text-center text-sm font-medium text-fg-2">ไม่มีรายการ</td></tr>)
          : paged.map((r,i)=>{
            const s=actLogSummary(r); const p=actLogParts(r);
            const extra=p.note||((!p.who&&!p.amount)?s.detail:null);
            const amtCls=(p.amtNum<0||s.tone==="danger")?"text-red-400":"text-green-400";
            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"><span className={"inline-block rounded-md px-2 py-0.5 text-xs font-semibold "+(TONE_CLS[s.tone]||TONE_CLS.muted)}>{s.title}</span></td>
              <td className="px-3"><div className="min-w-0"><div className="truncate font-medium text-fg">{r.username||"-"}</div><div className="truncate text-[11px] text-faint">{r.role||""}</div></div></td>
              <td className="px-3 text-xs text-fg-2 max-w-[220px]"><span className="line-clamp-2">{p.who||"-"}</span></td>
              <td className={"whitespace-nowrap px-3 text-right tnum font-semibold "+(p.amount?amtCls:"text-faint")}>{p.amount||"-"}</td>
              <td className="px-3 text-xs text-fg-2 max-w-[240px]"><span className="line-clamp-2">{extra||"-"}</span></td>
              <td className="px-3 mono text-[11px] text-faint">{r.ip||"-"}</td>
            </tr>);})}
      </tbody>
    </table></div>{!loading && !err && <Pager page={page} setPage={setPage} total={filtered.length} size={size} setSize={setSize}/>}</div>)}
  </div>);
}
