/* ==========================================================================
 * ADMIN NEXT — page-depositchannels.jsx  (จัดการช่องทางฝาก เปิด/ปิด)
 * ========================================================================== */

function DepositChannelsPage({ toast }) {
  const [settings,setSettings]=useState({});
  const [stats,setStats]=useState({});
  const [loading,setLoading]=useState(true);
  const [err,setErr]=useState(null);
  const [labelEdit,setLabelEdit]=useState(null); // {ch, values:{methodKey:ชื่อ}}
  const gridRef=useRef(null);
  const lastDragAt=useRef(0);

  const CHANNELS=[
    {key:"askmepay_enabled",label:"ฝากเงิน",methods:[["smsgateway","ฝากเงิน"],["sms","ฝากทศนิยม"]],channel:"askmepay",color:"#00e7ff",
     icon:"M3 7v10a2 2 0 002 2h14a2 2 0 002-2V7M3 7l9-4 9 4M3 7l9 4 9-4",enabledWhen:"1"},
    {key:"deposit_bank_enabled",label:"อัพโหลดสลิป",methods:[["bank","อัพโหลดสลิป"]],channel:"slip",color:"#2bb673",
     icon:"M3 21h18M3 10h18M3 7l9-4 9 4M5 10v11M19 10v11M9 14v3M15 14v3"},
    {key:"tmnone_enabled",label:"TrueWallet",methods:[["tmnone","TMNOne"],["truewallet_webhook","TrueMoney"]],channel:"tmnone",color:"#ff9baa",
     logo:TRUEWALLET_LOGO_URL,enabledWhen:"1"},
    {key:"deposit_truemoney_enabled",label:"TrueWallet (ซองของขวัญ)",methods:[["wallet","TrueWallet"]],channel:"truemoney",color:"#ff6b2b",
     logo:TRUEWALLET_LOGO_URL},
    {key:"deposit_code_enabled",label:"โค้ดเติมเงิน",methods:[["code","โค้ดเติมเงิน"]],channel:"code",color:"#9b7fff",
     icon:"M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 010 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 010-4V7a2 2 0 00-2-2H5z"},
    /* Payment รวม AskMePay API + Autopeer ไว้การ์ดเดียว — เปิด/ปิดการ์ดนี้ = เปิด/ปิดทั้งสอง (keys) */
    {key:"askmepay_api_deposit_enabled",keys:["askmepay_api_deposit_enabled","autopeer_enabled"],label:"Payment",methods:[["askmepay","Payment"],["autopeer","Autopeer"]],channels:["askmepay","autopeer"],color:"#3b82f6",
     icon:"M3 10h18V7a2 2 0 00-2-2H5a2 2 0 00-2 2v3zm0 0v7a2 2 0 002 2h14a2 2 0 002-2v-7",enabledWhen:"1"},
    {key:"crypto_deposit_enabled",label:"คริปโต USDT",methods:[["crypto","USDT"]],channel:"crypto",color:"#26a17b",
     icon:"M12 2a10 10 0 100 20 10 10 0 000-20zm-1 5h2v2h3v2h-3v2.2c2 .3 3 1.1 3 2.3 0 1.5-1.6 2.5-4 2.5s-4-1-4-2.5c0-1.2 1-2 3-2.3V11H8V9h3V7z",enabledWhen:"1"},
    {key:"deposit_lineconnect_enabled",label:"LINE Connect",methods:[["lineconnect","ฝากผ่าน LINE"],["line_abd","TEST222"]],channel:"line_auto",color:"#06c755",
     icon:"M21 11.5a8.38 8.38 0 01-.9 3.8 8.5 8.5 0 01-7.6 4.7 8.38 8.38 0 01-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 01-.9-3.8 8.5 8.5 0 014.7-7.6 8.38 8.38 0 013.8-.9h.5a8.48 8.48 0 018 8v.5z"},
  ];

  const load=useCallback(async()=>{
    setLoading(true); setErr(null);
    try{
      const [s,deps]=await Promise.all([
        api("/settings"),
        api("/deposits?limit=500").catch(()=>[])
      ]);
      setSettings(s||{});
      const byChannel=(Array.isArray(deps)?deps:deps.rows||[])
        .filter(r=>r.status==="success")
        .reduce((acc,r)=>{
          const ch=r.channel||"other";
          if(!acc[ch]) acc[ch]={count:0,total:0};
          acc[ch].count+=1;
          acc[ch].total+=Number(r.amount||0);
          return acc;
        },{});
      setStats(byChannel);
    }catch(e){
      if(e.status===401||e.status===403) window.__nxAuthFail?.();
      setErr(e.message||"โหลดไม่สำเร็จ");
    }finally{ setLoading(false); }
  },[]);

  useEffect(()=>{ load(); },[load]);

  const toggle=async(ch)=>{
    const cur=isEnabled(ch);
    const val=cur?"0":"1";
    const patch=Object.fromEntries((ch.keys||[ch.key]).map(k=>[k,val]));
    try{
      await api("/settings",{method:"POST",body:patch});
      setSettings(p=>({...p,...patch}));
      toast(cur?"ปิดช่องทางแล้ว":"เปิดช่องทางแล้ว");
    }catch(e){ toast(e.message||"บันทึกไม่สำเร็จ"); }
  };

  const isEnabled=(ch)=>(ch.keys||[ch.key]).some(k=>{
    const v=settings[k];
    if(ch.enabledWhen==="1") return v==="1";
    return v!=="0";
  });
  // ยอดสำเร็จของการ์ด — การ์ดที่รวมหลายช่องทาง (channels) เอายอดมารวมกัน
  const statOf=(ch)=>(ch.channels||[ch.channel]).reduce((a,c)=>{ const x=stats[c]; return x?{count:a.count+x.count,total:a.total+x.total}:a; },{count:0,total:0});

  /* ลำดับ/ป้ายแนะนำเก็บเป็น JSON array ของ key การ์ด — หน้าลูกค้าแปลงเป็นปุ่มฝากที่ /deposit/config */
  const parseList=(raw)=>{ try{ const v=JSON.parse(raw||"[]"); return Array.isArray(v)?v.map(String):[]; }catch{ return []; } };
  const order=parseList(settings.deposit_channel_order);
  const rank=(k)=>{ const i=order.indexOf(k); return i===-1?order.length:i; };
  const ordered=CHANNELS.map((ch,i)=>({ch,i})).sort((a,b)=>(rank(a.ch.key)-rank(b.ch.key))||(a.i-b.i)).map(x=>x.ch);
  const recommended=new Set(parseList(settings.deposit_channel_recommended));
  const orderSig=ordered.map(c=>c.key).join(",");
  // ชื่อปุ่มที่ลูกค้าเห็น เก็บเป็น JSON { methodKey: ชื่อ } (key ปุ่มฝั่งลูกค้า ไม่ใช่ key การ์ด)
  const labels=(()=>{ try{ const v=JSON.parse(settings.deposit_method_labels||"{}"); return v&&typeof v==="object"&&!Array.isArray(v)?v:{}; }catch{ return {}; } })();
  const shownName=(m)=>String(labels[m[0]]||"").trim()||m[1];

  const saveSetting=async(patch,okMsg)=>{
    const prev=settings;
    setSettings(p=>({...p,...patch}));
    try{ await api("/settings",{method:"POST",body:patch}); if(okMsg) toast(okMsg); return true; }
    catch(e){ setSettings(prev); toast(e.message||"บันทึกไม่สำเร็จ"); return false; }
  };

  // ลากสลับการ์ด (กดค้าง/ลาก) — ใช้ตัวลากเดียวกับหน้าเรียงลำดับเกม ปล่อยแล้วบันทึกทันที
  useEffect(()=>{
    if(loading||err) return;
    return gsMakeDraggable(gridRef.current,".dc-card","card",(keys)=>{
      lastDragAt.current=Date.now();
      if(keys.join(",")===orderSig) return;
      saveSetting({deposit_channel_order:JSON.stringify(keys)},"บันทึกลำดับแล้ว — หน้าลูกค้าเรียงตามนี้");
    });
  },[loading,err,orderSig]);

  const onCardClick=(ch)=>{ if(Date.now()-lastDragAt.current<400) return; toggle(ch); };
  const toggleRecommended=(ch)=>{
    const next=new Set(recommended); const on=!next.has(ch.key);
    if(on) next.add(ch.key); else next.delete(ch.key);
    saveSetting({deposit_channel_recommended:JSON.stringify(CHANNELS.map(c=>c.key).filter(k=>next.has(k)))},on?"ติดป้าย \"ช่องทางแนะนำ\" แล้ว":"เอาป้ายแนะนำออกแล้ว");
  };
  const openLabelEdit=(ch)=>setLabelEdit({ch,values:Object.fromEntries(ch.methods.map(m=>[m[0],String(labels[m[0]]||"")]))});
  const saveLabel=async()=>{
    if(!labelEdit) return;
    const next={...labels};
    for(const [k,v] of Object.entries(labelEdit.values)){ const t=String(v||"").trim().slice(0,40); if(t) next[k]=t; else delete next[k]; }
    if(await saveSetting({deposit_method_labels:JSON.stringify(next)},"บันทึกชื่อเมนูแล้ว")) setLabelEdit(null);
  };

  if(loading) return <div className="flex items-center gap-2 py-16 justify-center text-sm text-muted"><Ic d={I.refresh} size={16} cls="animate-spin"/> กำลังโหลด…</div>;
  if(err) return <HistErr msg={err} onRetry={load}/>;

  return (<div className="space-y-5">
    <div className="flex items-center justify-between">
      <div>
        <h2 className="text-base font-semibold">ช่องทางฝาก เปิด/ปิด</h2>
        <p className="text-xs text-muted mt-0.5">เปิด/ปิดช่องทางฝากเงิน และดูยอดสำเร็จของแต่ละช่องทาง</p>
      </div>
      <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}/> รีเฟรช</button>
    </div>

    {(()=>{ const on=settings.system_deposit_enabled!=="0"; return (
      <label className="flex items-center justify-between gap-3 rounded-xl border border-line bg-surface px-4 py-3 shadow-sm cursor-pointer hover:bg-sunken/40">
        <div><span className="text-sm font-semibold text-fg">ระบบฝาก</span><div className="text-[11px] text-muted">เปิด/ปิดรับฝากทั้งหมด — ปิดแล้วลูกค้าฝากไม่ได้ทุกช่องทาง</div></div>
        <button type="button" role="switch" aria-checked={on} onClick={()=>saveSetting({system_deposit_enabled:on?"0":"1"},on?"ปิดระบบฝากแล้ว":"เปิดระบบฝากแล้ว")}
          className={"relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors "+(on?"bg-accent":"bg-line")}>
          <span className={"inline-block h-5 w-5 rounded-full bg-white shadow transition-transform "+(on?"translate-x-5":"translate-x-0.5")}/>
        </button>
      </label>); })()}

    <div ref={gridRef} className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
      {ordered.map((ch,idx)=>{
        const on=isEnabled(ch);
        const rec=recommended.has(ch.key);
        const st=statOf(ch);
        return (
          <div key={ch.key} data-card={ch.key} role="button" tabIndex={0} onClick={()=>onCardClick(ch)}
            onKeyDown={e=>{ if(e.key==="Enter"||e.key===" "){ e.preventDefault(); toggle(ch); } }}
            className={"dc-card group relative flex cursor-pointer touch-none select-none flex-col items-center gap-3 rounded-xl border p-5 text-center transition-all "
              +(on?"border-line bg-surface shadow-sm hover:shadow-md":"border-line/60 bg-sunken/50 opacity-70 hover:opacity-100")}>
            <span className="gs-pos absolute left-2 top-2 grid h-5 min-w-[20px] place-items-center rounded-md bg-sunken px-1 text-[10px] font-semibold text-muted tnum">{idx+1}</span>
            <button type="button" onClick={e=>{e.stopPropagation(); toggleRecommended(ch);}} title="แสดงป้าย ช่องทางแนะนำ ในหน้าลูกค้า"
              className={"absolute right-2 top-2 rounded-full px-2 py-0.5 text-[10px] font-semibold transition-colors "+(rec?"bg-[#e11d48] text-white":"border border-line text-muted hover:text-fg")}>
              {rec?"★ แนะนำ":"☆ แนะนำ"}
            </button>
            <div className="mt-2 flex h-12 w-12 items-center justify-center rounded-xl" style={{background:on?ch.color+"18":"var(--sunken)"}}>
              {ch.logo
                ? <img src={ch.logo} alt={ch.label} draggable={false} className="h-8 w-8 rounded-lg object-contain" style={{background:"#fff",padding:"2px"}}/>
                : <span style={{color:on?ch.color:"var(--muted)"}}><Ic d={ch.icon} size={24} sw={1.8} cls={on?"":"opacity-50"}/></span>}
            </div>
            <div>
              <div className="text-sm font-semibold">{ch.label}</div>
              <div className="mt-0.5 text-[11px] text-fg-2">ลูกค้าเห็น: <b>{ch.methods.map(shownName).join(" / ")}</b></div>
              <div className="mt-0.5 text-[11px] text-muted mono tnum">สำเร็จ {N(st.count)} รายการ / {baht(st.total)}</div>
            </div>
            <div className="flex flex-wrap items-center justify-center gap-2">
              <Badge tone={on?"success":"danger"}>{on?"เปิด":"ปิด"}</Badge>
              <button type="button" onClick={e=>{e.stopPropagation(); openLabelEdit(ch);}}
                className="inline-flex items-center gap-1 rounded-lg border border-line px-2 py-0.5 text-[11px] font-medium text-fg-2 hover:bg-sunken"><Ic d={I.edit} size={12}/> แก้ชื่อเมนู</button>
            </div>
          </div>
        );
      })}
    </div>

    <p className="text-xs text-muted"><Ic d={["M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18","M12 8v4","M12 16h.01"]} size={14} cls="inline -mt-0.5 mr-1"/> กดค้างแล้วลากเพื่อเรียงลำดับ (หน้าลูกค้าเรียงตามนี้ ใบแรก = บนสุด) · คลิกการ์ดเพื่อเปิด/ปิด · กด ☆ แนะนำ เพื่อขึ้นป้าย "ช่องทางแนะนำ" ในหน้าลูกค้า · บันทึกอัตโนมัติทันที</p>

    {labelEdit&&(<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4 fade-in" onClick={()=>setLabelEdit(null)}>
      <div className="w-full max-w-sm rounded-xl bg-surface p-6 shadow-lg pop" onClick={e=>e.stopPropagation()}>
        <h3 className="text-sm font-semibold">แก้ชื่อเมนูฝาก — {labelEdit.ch.label}</h3>
        <p className="mb-3 mt-1 text-xs text-muted">ชื่อปุ่มที่ลูกค้าเห็นในหน้าฝากเงิน เว้นว่าง = ใช้ชื่อเดิม</p>
        {labelEdit.ch.methods.map(([k,def],i)=>(<div key={k} className="mb-3">
          {labelEdit.ch.methods.length>1&&<label className="mb-1 block text-xs font-semibold text-fg-2">ปุ่ม "{def}"</label>}
          <input autoFocus={i===0} maxLength={40} value={labelEdit.values[k]||""} onChange={e=>{ const v=e.target.value; setLabelEdit(l=>({...l,values:{...l.values,[k]:v}})); }}
            onKeyDown={e=>{ if(e.key==="Enter") saveLabel(); }} placeholder={def}
            className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/>
        </div>))}
        <div className="mt-4 flex justify-end gap-2">
          <button onClick={()=>setLabelEdit(null)} className="rounded-lg border border-line px-4 py-2 text-sm text-fg-2 hover:bg-sunken">ยกเลิก</button>
          <button onClick={saveLabel} className="rounded-lg bg-accent px-4 py-2 text-sm font-medium text-accent-fg hover:bg-accent-h">บันทึก</button>
        </div>
      </div>
    </div>)}

    <div className="rounded-xl border border-line bg-surface shadow-sm">
      <div className="border-b border-line px-4 py-3">
        <h3 className="text-sm font-semibold">รายงานแยกช่องทาง (500 รายการล่าสุด)</h3>
      </div>
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead><tr className="border-b border-line bg-sunken/60 text-left text-xs font-semibold text-muted">
            <th className="px-4 py-3">ช่องทาง</th><th className="px-4 py-3 text-right">รายการสำเร็จ</th><th className="px-4 py-3 text-right">ยอดรวม</th>
          </tr></thead>
          <tbody>{ordered.map(ch=>{
            const st=statOf(ch);
            return (<tr key={ch.key+"_tbl"} className="border-b border-line last:border-0 hover:bg-sunken/40">
              <td className="px-4 py-3"><div className="flex items-center gap-2">
                {ch.logo
                  ? <img src={ch.logo} alt="" className="h-5 w-5 rounded object-contain" style={{background:"#fff",padding:"1px"}}/>
                  : <span style={{color:ch.color}}><Ic d={ch.icon} size={16} sw={1.8}/></span>}
                <span className="font-medium">{ch.label}</span>
              </div></td>
              <td className="px-4 py-3 text-right mono tnum">{N(st.count)}</td>
              <td className="px-4 py-3 text-right mono tnum font-semibold">{baht(st.total)}</td>
            </tr>);
          })}</tbody>
        </table>
      </div>
    </div>
  </div>);
}
