/* ==========================================================================
 * ADMIN NEXT — page-home.jsx  (แยกจาก index.html เดิม; โหลดผ่าน <script type="text/babel">)
 * โหลดตามลำดับใน index.html — ทุกไฟล์แชร์ scope เดียวกัน (babel-standalone)
 * ========================================================================== */
function homeChannel(a) {
  const ch=String(a.channel||"").toLowerCase(), t=String(a.type||a.account_type||"").toLowerCase();
  const methods=(a.deposit_methods||[]).map(x=>String(x).toLowerCase());
  if (t==="wallet"||t==="whdepo"||a.wallet_phone||methods.includes("truewallet_webhook")||ch==="tmnone"||ch==="truemoney") return "truewallet";
  if (ch==="autopeer"||t==="autopeer") return "autopeer";
  return "bank";
}
// เปิดประวัติ SMS โดยกรองไว้ที่บัญชีนี้ (หน้าประวัติ SMS อ่านค่านี้ตอนเปิด)
function openSmsHistoryForAccount(accountId) {
  try { sessionStorage.setItem("nx_smshist_account", accountId); } catch {}
  location.hash = "#/smshist";
}

/* ยอดเข้าบัญชีวันนี้ตาม SMS ธนาคาร เทียบกับยอดที่ระบบเติมให้ลูกค้า (บัญชีฝากผ่าน SMS เท่านั้น)
   ระบบเติมมากกว่า SMS = อาจเติมซ้ำหรือเติมผิดบัญชี ควรเปิดดู */
function AccountSmsLine({ a }) {
  const methods=(a.deposit_methods||[]).map(x=>String(x).toLowerCase());
  const smsAccount=methods.includes("smsgateway")||methods.includes("bank_auto")||methods.includes("sms");
  if(!smsAccount && !Number(a.sms_in_count_today)) return null;
  const over=Number(a.deposit_total_today||0)-Number(a.sms_in_total_today||0);
  return (<div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-[11px] text-muted">
    <span>SMS เข้าวันนี้ <b className="font-semibold text-fg-2">{money2(a.sms_in_total_today)}</b> ({N(a.sms_in_count_today)})</span>
    {smsAccount && over>0 && <Badge tone="warn">เติมมากกว่า SMS {money2(over)}</Badge>}
    <button onClick={()=>openSmsHistoryForAccount(a.id)} className="text-accent hover:underline">ดู SMS →</button>
  </div>);
}

function AccountCard({ a }) {
  const wallet = homeChannel(a)==="truewallet";
  const number = a.account_no || a.wallet_phone || "-";
  const name = a.account_name || a.wallet_name || "-";
  const cnt = Number(a.deposit_count_today||0);
  const yest = a.deposit_total_yesterday!=null ? a.deposit_total_yesterday : a.deposit_yesterday_total;
  return (<div className="rounded-xl border border-line bg-surface p-3 shadow-sm">
    <div className="flex items-center gap-2.5">
      <BankLogo code={wallet?"truewallet":a.bank_code} size={30}/>
      <div className="min-w-0 flex-1"><div className="truncate text-sm font-semibold">{name}</div><div className="truncate mono text-[11px] text-faint">{number}</div></div>
      <button onClick={()=>{try{navigator.clipboard.writeText(number);}catch{}}} title="คัดลอกเลขบัญชี" className="grid h-7 w-7 shrink-0 place-items-center rounded-lg border border-line text-muted hover:bg-sunken hover:text-accent"><Ic d={I.copy} size={14}/></button>
    </div>
    <div className="mt-2.5 text-2xl font-semibold tracking-tight tnum">{money2(a.deposit_total_today)}</div>
    <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px] text-muted">
      <span className="inline-flex items-center gap-1"><Ic d={I.clock} size={12}/> วันนี้ <b className="font-semibold text-fg-2">{money2(a.deposit_total_today)}</b> ({cnt})</span>
      {yest!=null && <span>· เมื่อวาน {money2(yest)}</span>}
    </div>
    {!wallet && <AccountSmsLine a={a}/>}
    {a.sms_last_balance!=null && <div className="mt-1 text-[11px] text-info">ยอดคงเหลือ (SMS) {money2(a.sms_last_balance)}{a.sms_last_device?<span className="text-faint"> · {a.sms_last_device}</span>:null}</div>}
  </div>);
}
/* การ์ดผู้ให้บริการ (AskMePay / Autopeer): เครดิตคงเหลือเป็นบาทจากผู้ให้บริการ, ยอดฝาก/ถอนวันนี้เป็นสตางค์จากระบบเรา */
const bahtText = (n)=>Number(n).toLocaleString("th-TH",{minimumFractionDigits:2,maximumFractionDigits:2})+" บาท";
function ProviderCard({ p }) {
  const credit = p.credit!=null && Number.isFinite(Number(p.credit)) ? Number(p.credit) : null;
  return (<div className="rounded-xl border border-line bg-surface p-3 shadow-sm">
    <div className="text-sm font-semibold">{p.name||p.label||p.provider||p.key||"ช่องทาง"}</div>
    <div className="mt-2 text-[11px] font-semibold text-muted">เครดิตคงเหลือ</div>
    {credit!=null ? <div className="text-xl font-semibold tnum" style={{color:credit>0?"var(--success)":"var(--danger)"}}>{bahtText(credit)}</div>
      : <div className="text-sm text-muted">ไม่มีข้อมูลยอด</div>}
    <div className="mt-3 grid grid-cols-2 gap-2 border-t border-line-soft pt-2.5">
      <div><div className="text-[11px] text-muted">ยอดฝากวันนี้</div><div className="text-sm font-semibold tnum text-success">{money2(p.deposit_total_today)}</div><div className="text-[10px] text-faint">{N(p.deposit_count_today)} รายการ</div></div>
      <div><div className="text-[11px] text-muted">ยอดถอนวันนี้</div><div className="text-sm font-semibold tnum text-danger">{money2(p.withdraw_total_today)}</div><div className="text-[10px] text-faint">{N(p.withdraw_count_today)} รายการ</div></div>
    </div>
  </div>);
}
function DepRow({ r, onSlip }) {
  const st = depStatus(r.status);
  const nm = r.username || r.full_name || "-";
  const slip = slipUrl(r);
  return (<div className="flex items-center gap-3 px-3 py-2.5">
    <div className="grid h-8 w-8 shrink-0 place-items-center rounded-full text-sm font-semibold text-white" style={{background:avc(nm)}}>{initials(nm)}</div>
    <div className="min-w-0 flex-1"><div className="truncate text-sm font-semibold text-accent">{nm}</div><div className="truncate text-[11px] text-faint">{r.full_name&&r.full_name!==r.username?<>{r.full_name} · </>:null}{(CHANNEL_LABEL[r.channel]||r.channel||"-")} · {fmtDT(r.created_at)}</div></div>
    {slip && onSlip && <button title="ดูสลิป" onClick={()=>onSlip(slip)} className="grid h-7 w-7 shrink-0 place-items-center rounded-lg border border-line bg-surface hover:bg-sunken" style={{color:"#0EA5E9"}}><Ic d={I.eye} size={14}/></button>}
    <div className="text-right"><div className="text-sm font-semibold tnum">{money2(r.display_amount!=null?r.display_amount:r.amount)}</div><div className="mt-0.5"><Badge tone={st.c}>{st.t}</Badge></div></div>
  </div>);
}
function PendingCard({ r, onSlip, onApprove, onReject, busy }) {
  const nm = r.username || r.full_name || "-";
  const bankLine = [bankName(r.bank_code), r.account_no, r.account_name].filter(Boolean).join(" · ");
  const slip = slipUrl(r);
  const st = depStatus(r.status);
  return (<div className="px-3 py-3">
    <div className="flex items-start gap-3">
      <div className="grid h-9 w-9 shrink-0 place-items-center rounded-full text-sm font-semibold text-white" style={{background:avc(nm)}}>{initials(nm)}</div>
      <div className="min-w-0 flex-1">
        <div className="flex items-start gap-2">
          <div className="min-w-0 flex-1"><div className="truncate text-sm font-semibold text-accent">{nm}</div><div className="truncate text-[11px] text-faint">{r.full_name&&r.full_name!==r.username?<>{r.full_name} · </>:null}{r.channel||"-"} · {fmtDT(r.created_at)}</div></div>
          <div className="text-right"><div className="text-sm font-semibold tnum">{money2(r.display_amount!=null?r.display_amount:r.amount)}</div><div className="mt-0.5"><Badge tone={st.c}>{st.t}</Badge></div></div>
        </div>
        {bankLine && <div className="mt-1 truncate text-[11px] text-muted">บัญชีรับ: {bankLine}</div>}
        {r.ref_id && <div className="truncate mono text-[11px] text-faint">Ref: {r.ref_id}</div>}
        <div className="mt-2 flex flex-wrap items-center gap-1.5">
          {slip && <button onClick={()=>onSlip(slip)} className="flex h-7 items-center gap-1 rounded-lg border border-line bg-surface px-2 text-xs font-medium text-fg-2 hover:bg-sunken"><Ic d={I.eye} size={13}/> ดูสลิป</button>}
          {canAny(["deposits","tool_slip_approve"]) && <>
          <button disabled={busy} onClick={()=>onReject(r)} className="flex h-7 items-center gap-1 rounded-lg border px-2 text-xs font-medium disabled:opacity-50" style={{borderColor:"var(--danger)",color:"var(--danger)",background:"var(--danger-soft)"}}><Ic d={I.x} size={13}/> ยกเลิก</button>
          <button disabled={busy} onClick={()=>onApprove(r)} className="flex h-7 items-center gap-1 rounded-lg px-2.5 text-xs font-semibold text-white disabled:opacity-50" style={{background:"var(--success)"}}><Ic d={I.check} size={13} sw={3}/> เติมเงิน</button></>}
        </div>
      </div>
    </div>
  </div>);
}
function HomePage({ toast }) {
  const [data,setData]=useState(null);
  const [loading,setLoading]=useState(true);
  const [err,setErr]=useState(null);
  const [tab,setTab]=useState("auto");
  const [modal,setModal]=useState(null); // {type:'slip'|'approve'|'reject', row, img}
  const [busy,setBusy]=useState(false);
  const load=useCallback(async()=>{
    setLoading(true); setErr(null);
    try { setData(await api("/home")); }
    catch(e){ if(e.status===401){window.__nxAuthFail&&window.__nxAuthFail();} setErr(e.status===403?"บัญชีนี้ไม่มีสิทธิ์ดูหน้าหลัก":(e.message||"โหลดไม่สำเร็จ")); }
    finally { setLoading(false); }
  },[]);
  useEffect(()=>{ load(); },[load]);
  const doApprove=async(username)=>{
    if(!modal||!modal.row) return; setBusy(true);
    try {
      const body = (username && username.toLowerCase()!==String(modal.row.username||"").toLowerCase()) ? {username} : {};
      await api("/deposits/"+modal.row.id+"/approve", {method:"POST", body});
      toast("อนุมัติรายการฝากแล้ว"); setModal(null); load();
    } catch(e){ toast(e.message||"อนุมัติไม่สำเร็จ"); } finally { setBusy(false); }
  };
  const doReject=async(reason)=>{
    if(!modal||!modal.row) return; setBusy(true);
    try { await api("/deposits/"+modal.row.id+"/reject", {method:"POST", body:{reason:reason||"rejected"}});
      toast("ปฏิเสธรายการฝากแล้ว"); setModal(null); load();
    } catch(e){ toast(e.message||"ปฏิเสธไม่สำเร็จ"); } finally { setBusy(false); }
  };

  const accts = (data && data.balances && data.balances.depositAccounts) || [];
  const providers = (data && data.balances && data.balances.paymentProviders) || [];
  const groups = { bank:[], truewallet:[], autopeer:[] };
  accts.forEach(a=>{ (groups[homeChannel(a)]||groups.bank).push(a); });
  const TABS = [["auto","Auto",groups.bank],["truewallet","True Wallet",groups.truewallet],["payments","Payments",providers],["autopeer","AutoPeer",groups.autopeer]];
  const pending = (data && data.pending) || [];
  const latest = (data && data.latest) || [];
  const pendingTotal = pending.reduce((s,r)=>s+Number(r.display_amount!=null?r.display_amount:r.amount||0),0);
  const active = TABS.find(t=>t[0]===tab) || TABS[0];

  if (err) return (<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} 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>);

  return (<div className="space-y-5">
    {/* สรุปยอด */}
    <div className="rounded-xl border border-line bg-surface shadow-sm">
      <div className="flex items-center gap-2 border-b border-line px-4 py-3">
        <span className="grid h-7 w-7 place-items-center rounded-lg bg-accent-soft text-accent"><Duo name="money" size={18}/></span>
        <div className="text-sm font-semibold">สรุปยอด</div>
        <button onClick={load} className="ml-auto flex h-8 items-center gap-1.5 rounded-lg border border-line bg-surface px-2.5 text-xs font-medium text-fg-2 hover:bg-sunken"><Ic d={I.refresh} size={15} cls={loading?"animate-spin":""}/> รีเฟรช</button>
      </div>
      <div className="flex flex-wrap gap-1 border-b border-line px-3 pt-3">
        {TABS.map(([k,l,arr])=>(<button key={k} onClick={()=>setTab(k)} className={"rounded-t-lg px-3 py-2 text-sm font-medium transition-colors "+(tab===k?"bg-accent text-accent-fg":"text-fg-2 hover:bg-sunken")}>{l}<span className={"ml-1.5 rounded-full px-1.5 text-[10px] "+(tab===k?"bg-white/25":"bg-sunken text-muted")}>{arr.length}</span></button>))}
      </div>
      <div className="p-4">
        {loading ? <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">{Array.from({length:3}).map((_,i)=><div key={i} className="skel h-28 w-full"/>)}</div>
          : active[2].length===0 ? <div className="py-10 text-center text-sm text-muted">ไม่มีบัญชีในช่องทางนี้</div>
          : tab==="payments" ? <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">{providers.map((p,i)=><ProviderCard key={i} p={p}/>)}</div>
          : <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-3">{active[2].map((a,i)=><AccountCard key={a.id||i} a={a}/>)}</div>}
      </div>
    </div>

    <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
      {/* รอดำเนินการ */}
      <div className="rounded-xl border border-line bg-surface shadow-sm">
        <div className="flex items-center gap-2 border-b border-line px-4 py-3">
          <span className="grid h-6 w-6 place-items-center rounded-lg text-warn" style={{background:"var(--warn-soft)"}}><Ic d={I.clock} size={15}/></span>
          <div className="text-sm font-semibold">รายการฝากที่รอดำเนินการ (ตกค้าง)</div>
          <span className="ml-auto rounded-full bg-warn-soft px-2 py-0.5 text-xs font-semibold text-warn tnum">{money2(pendingTotal)}</span>
        </div>
        <div className="divide-y divide-line-soft">
          {loading ? Array.from({length:3}).map((_,i)=><div key={i} className="px-3 py-3"><div className="skel h-6 w-full"/></div>)
            : pending.length===0 ? <div className="py-8 text-center text-sm text-muted">ไม่มีรายการตกค้าง</div>
            : pending.map((r,i)=><PendingCard key={r.id||i} r={r} busy={busy} onSlip={(img)=>setModal({type:"slip",img})} onApprove={(row)=>setModal({type:"approve",row})} onReject={(row)=>setModal({type:"reject",row})}/>)}
        </div>
      </div>
      {/* ล่าสุด */}
      <div className="rounded-xl border border-line bg-surface shadow-sm">
        <div className="flex items-center gap-2 border-b border-line px-4 py-3">
          <span className="grid h-6 w-6 place-items-center rounded-lg text-accent" style={{background:"var(--accent-soft)"}}><Ic d={I.dep} size={15}/></span>
          <div className="text-sm font-semibold">รายการล่าสุด</div>
          <span className="ml-auto text-xs text-muted tnum">{latest.length} รายการ</span>
        </div>
        <div className="max-h-[420px] divide-y divide-line-soft overflow-y-auto">
          {loading ? Array.from({length:5}).map((_,i)=><div key={i} className="px-3 py-3"><div className="skel h-6 w-full"/></div>)
            : latest.length===0 ? <div className="py-8 text-center text-sm text-muted">ยังไม่มีรายการ</div>
            : latest.map((r,i)=><DepRow key={r.id||i} r={r} onSlip={(img)=>setModal({type:"slip",img})}/>)}
        </div>
      </div>
    </div>

    {modal && modal.type==="slip" && <SlipModal img={modal.img} onClose={()=>setModal(null)}/>}
    {modal && modal.type==="approve" && <ConfirmModal kind="approve" row={modal.row} busy={busy} onClose={()=>!busy&&setModal(null)} onConfirm={doApprove}/>}
    {modal && modal.type==="reject" && <ConfirmModal kind="reject" row={modal.row} busy={busy} onClose={()=>!busy&&setModal(null)} onConfirm={doReject}/>}
  </div>);
}
