/* ==========================================================================
 * ADMIN NEXT — page-mktreport.jsx  (รายงานสายการตลาด)
 * ========================================================================== */

function MktMembersModal({ org, range, custom, onClose }) {
  const [data,setData]=useState(null),[loading,setLoading]=useState(true),[err,setErr]=useState(null);
  const [offset,setOffset]=useState(0);
  const limit=100;
  useEffect(()=>{
    let active=true;
    const load=async()=>{
      setLoading(true);setErr(null);
      try{
        const dates=rangeToDates(range,custom),q=new URLSearchParams({channel_id:String(org.id),limit:String(limit),offset:String(offset)});
        if(dates.from){q.set("register_from",dates.from);q.set("tx_from",dates.from);}
        if(dates.to){q.set("register_to",dates.to);q.set("tx_to",dates.to);}
        const result=await api("/marketing/members?"+q.toString());
        if(active)setData(result);
      }catch(e){
        if(e.status===401||e.status===403)window.__nxAuthFail?.();
        if(active)setErr(e.message||"โหลดสมาชิกไม่สำเร็จ");
      }finally{if(active)setLoading(false);}
    };
    load();
    return()=>{active=false;};
  },[org.id,range,custom,offset]);
  const summary=data?.summary||{};
  const rows=data?.rows||[];
  const total=Number(summary.totalMembers||0);
  const H=({children,extra=""})=><th className={"whitespace-nowrap px-3 py-2 text-left text-[13px] font-bold text-fg-2 "+extra}>{children}</th>;
  return (<div className="fixed inset-0 z-[80] flex items-center justify-center p-3 sm:p-5" onMouseDown={onClose}>
    <div className="absolute inset-0 bg-black/55"/>
    <div className="relative flex max-h-[92vh] w-full max-w-[1400px] flex-col overflow-hidden rounded-2xl border border-line bg-surface2 shadow-lg" onMouseDown={e=>e.stopPropagation()}>
      <div className="flex items-center justify-between gap-3 border-b border-line px-4 py-3">
        <div><div className="font-semibold text-fg">{org.name} · รายชื่อสมาชิก</div><div className="text-xs text-muted">ช่วงวันที่ตามรายงาน · {total.toLocaleString("th-TH")} คน</div></div>
        <button onClick={onClose} className="grid h-8 w-8 place-items-center rounded-lg border border-line text-fg-2 hover:bg-sunken"><Ic d={I.x} size={16}/></button>
      </div>
      <div className="grid grid-cols-2 gap-2 border-b border-line p-3 sm:grid-cols-4 lg:grid-cols-7">
        {[["ฝาก",baht(summary.totalDeposit)],["ถอน",baht(summary.totalWithdraw)],["ฝากคิดส่วนแบ่ง",baht(summary.commissionDeposit)],["ถอนคิดส่วนแบ่ง",baht(summary.commissionWithdraw)],["ยอดเล่น",baht(summary.totalBet)],["โบนัส",baht(summary.totalBonus)],["ยังไม่ฝาก",Number(summary.noDepositUsers||0).toLocaleString("th-TH")]].map(([label,value])=>
          <div key={label} className="rounded-lg border border-line bg-surface p-2"><div className="text-[10px] text-muted">{label}</div><div className="mt-0.5 text-xs font-semibold tnum">{value}</div></div>)}
      </div>
      {err?<div className="p-8 text-center text-sm text-danger">{err}</div>
      :<div className="min-h-0 flex-1 overflow-auto">
        <table className="w-full min-w-[1300px] border-collapse text-xs">
          <thead className="sticky top-0 border-b border-line bg-sunken"><tr>
            <H>ยูสเซอร์เนม</H><H>ชื่อสมาชิก</H><H>วันที่สมัคร</H><H extra="text-right">ยอดฝาก</H><H extra="text-right">ยอดถอน</H><H extra="text-right">ฝากคิดส่วนแบ่ง</H><H extra="text-right">ถอนคิดส่วนแบ่ง</H><H extra="text-right">ยอดเล่น</H><H extra="text-right">ชนะ/แพ้</H><H extra="text-right">โบนัส</H>
          </tr></thead>
          <tbody>{loading?Array.from({length:6}).map((_,i)=><tr key={i}><td colSpan="10" className="p-3"><div className="skel h-5 w-full"/></td></tr>)
            :rows.length===0?<tr><td colSpan="10" className="p-10 text-center text-fg-2">ไม่มีข้อมูลสมาชิก</td></tr>
            :rows.map(r=><tr key={r.id} className="border-b border-line-soft hover:bg-sunken/50">
              <td className="px-3 py-2 font-semibold text-accent">{r.username||"-"}</td><td className="px-3 py-2 text-fg-2">{r.full_name||"-"}</td><td className="px-3 py-2 whitespace-nowrap text-fg-2">{fmtDT(r.created_at)}</td>
              <td className="px-3 py-2 text-right tnum">{baht(r.total_deposit)}</td><td className="px-3 py-2 text-right tnum">{baht(r.total_withdraw)}</td><td className="px-3 py-2 text-right tnum">{baht(r.commission_deposit)}</td><td className="px-3 py-2 text-right tnum">{baht(r.commission_withdraw)}</td><td className="px-3 py-2 text-right tnum">{baht(r.total_bet)}</td><td className="px-3 py-2 text-right tnum">{baht(r.win_loss)}</td><td className="px-3 py-2 text-right tnum">{baht(r.total_bonus)}</td>
            </tr>)}
          </tbody>
        </table>
      </div>}
      <div className="flex items-center justify-between border-t border-line px-4 py-2.5 text-xs text-muted">
        <span>{total?`${offset+1}–${Math.min(offset+rows.length,total)} จาก ${total}`:"0 รายการ"}</span>
        <div className="flex gap-2"><button disabled={offset===0||loading} onClick={()=>setOffset(Math.max(0,offset-limit))} className="rounded-lg border border-line px-3 py-1.5 disabled:opacity-40">ก่อนหน้า</button><button disabled={offset+limit>=total||loading} onClick={()=>setOffset(offset+limit)} className="rounded-lg border border-line px-3 py-1.5 disabled:opacity-40">ถัดไป</button></div>
      </div>
    </div>
  </div>);
}

function MktReportPage({ toast }) {
  const [range,setRange]=useState("7d"),[custom,setCustom]=useState({from:"",to:""});
  const [channel,setChannel]=useState("all"),[orgs,setOrgs]=useState([]);
  const [rows,setRows]=useState([]),[loading,setLoading]=useState(true),[err,setErr]=useState(null);
  const [membersOrg,setMembersOrg]=useState(null);

  const load=useCallback(async()=>{
    setLoading(true); setErr(null);
    try{
      const d=rangeToDates(range,custom);
      const q=new URLSearchParams();
      if(d.from)q.set("date_from",d.from);
      if(d.to)q.set("date_to",d.to);
      if(channel!=="all")q.set("channel_id",channel);
      const data=await api("/marketing/report?"+q.toString());
      const result=Array.isArray(data)?data:(data?.rows||[]);
      setRows(result);
      if(channel==="all")setOrgs(result.map(r=>({id:r.id,name:r.name})));
    }catch(e){
      if(e.status===401||e.status===403)window.__nxAuthFail?.();
      setErr(e.message||"โหลดรายงานการตลาดไม่สำเร็จ");
    }finally{setLoading(false);}
  },[range,custom,channel]);
  useEffect(()=>{load();},[load]);

  const tot=key=>rows.reduce((s,r)=>s+(Number(r[key])||0),0);
  const money=key=>baht(tot(key));
  const H=({children,extra=""})=>(<th className={"whitespace-nowrap px-3 py-3 text-left text-[13px] font-bold text-fg-2 "+extra}>{children}</th>);
  const exportRows=()=>{
    const headers=["สายการตลาด","สมาชิกใหม่","สมาชิกที่ฝาก","สมาชิกที่ไม่ฝาก","ยอดฝากรวม","ยอดถอนรวม","ฝากคิดส่วนแบ่ง","ถอนคิดส่วนแบ่ง","ฐานส่วนแบ่งสุทธิ","ส่วนแบ่ง","ยอดเล่น","ชนะ/แพ้","โบนัส"];
    csvDownload("mkt-report.csv",[headers,...rows.map(r=>[
      r.name,r.signup_count||0,r.deposit_users||0,r.no_deposit_users||0,
      baht(r.total_deposit),baht(r.total_withdraw),baht(r.commission_deposit),
      baht(r.commission_withdraw),baht(r.net_actual),baht(r.commission_amount),
      baht(r.total_bet),baht(r.win_loss),baht(r.total_bonus),
    ])]);
    toast("ส่งออกรายงานแล้ว");
  };

  return (<div className="space-y-4">
    <div className="flex flex-wrap items-center gap-2">
      <div className="flex gap-1 rounded-lg bg-sunken p-1">
        {RANGES.map(([k,l])=>(<button key={k} onClick={()=>setRange(k)} className={"rounded-md px-2.5 py-1 text-xs font-medium transition-colors "+(range===k?"bg-surface text-fg shadow-sm":"text-muted hover:text-fg")}>{l}</button>))}
      </div>
      {range==="custom"&&<div className="flex items-center gap-1 text-xs"><input type="date" value={custom.from} onChange={e=>setCustom(c=>({...c,from:e.target.value}))} className="rounded-lg border border-line bg-surface px-2 py-1 text-xs"/>—<input type="date" value={custom.to} onChange={e=>setCustom(c=>({...c,to:e.target.value}))} className="rounded-lg border border-line bg-surface px-2 py-1 text-xs"/></div>}
      <select value={channel} onChange={e=>setChannel(e.target.value)} className="h-8 rounded-lg border border-line bg-surface px-2 text-xs text-fg-2">
        <option value="all">ทุกสายการตลาด</option>{orgs.map(o=><option key={o.id} value={o.id}>{o.name}</option>)}
      </select>
      <button onClick={load} className="flex h-8 items-center gap-1 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={14} cls={loading?"animate-spin":""}/> รีเฟรช</button>
      <ExportBtn onClick={exportRows}/>
    </div>

    <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
      {[["สมาชิกใหม่",tot("signup_count"),"info",false],["สมาชิกที่ฝาก",tot("deposit_users"),"success",false],["สมาชิกที่ไม่ฝาก",tot("no_deposit_users"),"warn",false],["ยอดฝากรวม",tot("total_deposit"),"success",true],["ยอดถอนรวม",tot("total_withdraw"),"warn",true],["ส่วนแบ่ง",tot("commission_amount"),"accent",true]].map(([label,value,tone,isMoney])=>
        <div key={label} className="rounded-xl border p-4 shadow-sm" style={{borderColor:"color-mix(in srgb, var(--"+tone+") 32%, var(--line))", background:"color-mix(in srgb, var(--"+tone+") 9%, var(--surface))"}}>
          <div className="text-[13px] font-semibold" style={{color:"var(--"+tone+")"}}>{label}</div>
          <div className="mt-1 text-2xl font-bold tnum" style={{color:"var(--"+tone+")"}}>{isMoney?baht(value):Number(value).toLocaleString("th-TH")}</div>
        </div>)}
    </div>

    {err ? <HistErr msg={err} onRetry={load}/>
    : <div className="overflow-hidden rounded-xl border border-line bg-surface shadow-sm"><div className="overflow-x-auto"><table className="w-full min-w-[1500px] border-collapse text-sm">
      <thead className="border-b-2 border-accent/25 bg-accent-soft"><tr>
        <H>สายการตลาด</H><H extra="text-right">สมาชิกใหม่</H><H extra="text-right">สมาชิกที่ฝาก</H><H extra="text-right">สมาชิกที่ไม่ฝาก</H>
        <H extra="text-right">ยอดฝากรวม</H><H extra="text-right">ยอดถอนรวม</H><H extra="text-right">ฝากคิดส่วนแบ่ง</H><H extra="text-right">ถอนคิดส่วนแบ่ง</H>
        <H extra="text-right">ฐานส่วนแบ่งสุทธิ</H><H extra="text-right">ส่วนแบ่ง</H><H extra="text-right">ยอดเล่น</H><H extra="text-right">ชนะ/แพ้</H><H extra="text-right pr-4">โบนัส</H>
      </tr></thead>
      <tbody>
        {loading ? Array.from({length:5}).map((_,i)=>(<tr key={i} className="border-b border-line-soft"><td className="px-3 py-3" colSpan="13"><div className="skel h-5 w-full"/></td></tr>))
        : rows.length===0 ? <tr><td colSpan="13" 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 last:border-0 hover:bg-sunken/50">
            <td className="px-3 py-2.5"><button onClick={()=>setMembersOrg({id:r.id,name:r.name||"-"})} className="text-left"><div className="font-medium text-accent hover:underline">{r.name||"-"}</div><div className="text-[11px] text-faint">{r.slug||""} · ดูสมาชิก</div></button></td>
            <td className="px-3 text-right tnum text-fg-2">{Number(r.signup_count||0).toLocaleString("th-TH")}</td>
            <td className="px-3 text-right tnum text-success">{Number(r.deposit_users||0).toLocaleString("th-TH")}</td>
            <td className="px-3 text-right tnum text-warn">{Number(r.no_deposit_users||0).toLocaleString("th-TH")}</td>
            <td className="px-3 text-right tnum text-success">{baht(r.total_deposit)}</td>
            <td className="px-3 text-right tnum text-danger">{baht(r.total_withdraw)}</td>
            <td className="px-3 text-right tnum text-success">{baht(r.commission_deposit)}</td>
            <td className="px-3 text-right tnum text-danger">{baht(r.commission_withdraw)}</td>
            <td className={"px-3 text-right tnum "+(Number(r.net_actual||0)>=0?"text-success":"text-danger")}>{baht(r.net_actual)}</td>
            <td className="px-3 text-right tnum font-semibold text-accent">{baht(r.commission_amount)}</td>
            <td className="px-3 text-right tnum text-fg-2">{baht(r.total_bet)}</td>
            <td className={"px-3 text-right tnum "+(Number(r.win_loss||0)>=0?"text-success":"text-danger")}>{baht(r.win_loss)}</td>
            <td className="px-3 pr-4 text-right tnum text-warn">{baht(r.total_bonus)}</td>
          </tr>))}
          <tr className="bg-sunken/70 font-semibold">
            <td className="px-3 py-2.5">รวมทั้งหมด</td>
            <td className="px-3 text-right tnum">{tot("signup_count").toLocaleString("th-TH")}</td>
            <td className="px-3 text-right tnum text-success">{tot("deposit_users").toLocaleString("th-TH")}</td>
            <td className="px-3 text-right tnum text-warn">{tot("no_deposit_users").toLocaleString("th-TH")}</td>
            <td className="px-3 text-right tnum text-success">{money("total_deposit")}</td>
            <td className="px-3 text-right tnum text-danger">{money("total_withdraw")}</td>
            <td className="px-3 text-right tnum text-success">{money("commission_deposit")}</td>
            <td className="px-3 text-right tnum text-danger">{money("commission_withdraw")}</td>
            <td className="px-3 text-right tnum">{money("net_actual")}</td>
            <td className="px-3 text-right tnum text-accent">{money("commission_amount")}</td>
            <td className="px-3 text-right tnum">{money("total_bet")}</td>
            <td className="px-3 text-right tnum">{money("win_loss")}</td>
            <td className="px-3 pr-4 text-right tnum text-warn">{money("total_bonus")}</td>
          </tr>
        </>}
      </tbody>
    </table></div></div>}
    {membersOrg&&<MktMembersModal org={membersOrg} range={range} custom={custom} onClose={()=>setMembersOrg(null)}/>}
  </div>);
}
