/* ==========================================================================
 * ADMIN NEXT — page-profitloss.jsx  (แยกไฟล์ละหน้า; โหลดผ่าน <script type="text/babel">)
 * ========================================================================== */
function NetProfitChart({ rows }) {
  let running=0;
  const data=(rows||[]).filter(r=>!r.is_future).map(r=>{
    running+=Number(r.net_profit||0)/100;
    return {date:r.date, total:running};
  });
  if(!data.length) return <div className="py-10 text-center text-sm text-muted">ไม่มีข้อมูล</div>;
  const rawMin=Math.min(...data.map(d=>d.total)),rawMax=Math.max(...data.map(d=>d.total));
  const padding=(rawMax-rawMin)*0.08||1;
  const min=Math.min(0,rawMin-padding),max=Math.max(0,rawMax+padding);
  const span=max-min,stepValue=span/4;
  const W=760,H=240,padL=58,padR=14,padT=16,padB=28,iw=W-padL-padR,ih=H-padT-padB,n=data.length;
  const gx=(i)=>padL+(i+0.5)*(iw/n);
  const y=(v)=>padT+((max-v)/span)*ih;
  const kfmt=(t)=>{const a=Math.abs(t); const s=t<0?"-":""; return s+(a>=1000000?(a/1000000).toFixed(1)+"M":a>=1000?Math.round(a/1000)+"k":a.toLocaleString("th-TH",{maximumFractionDigits:2}));};
  const dow=["อา","จ","อ","พ","พฤ","ศ","ส"];
  const lbl=(ds)=>{ try{const d=new Date(ds+"T00:00:00+07:00"); return dow[d.getDay()]+" "+ds.slice(8,10);}catch{return ds.slice(8,10);} };
  const ticks=Array.from({length:5},(_,i)=>max-stepValue*i);
  const step=Math.max(1,Math.ceil(n/12));
  const line=data.map((d,i)=>`${i===0?"M":"L"} ${gx(i)} ${y(d.total)}`).join(" ");
  const area=`${line} L ${gx(n-1)} ${y(0)} L ${gx(0)} ${y(0)} Z`;
  return (<div className="mx-auto w-full max-w-[1000px] overflow-x-auto"><svg viewBox={`0 0 ${W} ${H}`} className="mx-auto block w-full min-w-[560px]" role="img" aria-label="กำไรสะสมรายวัน">
    {ticks.map((t,i)=>(<g key={i}><line x1={padL} x2={W-padR} y1={y(t)} y2={y(t)} stroke={Math.abs(t)<1e-8?"var(--fg-2)":"var(--line)"} strokeWidth={Math.abs(t)<1e-8?1.4:1} strokeOpacity={Math.abs(t)<1e-8?0.5:1}/><text x={padL-8} y={y(t)+3} textAnchor="end" fontSize="9.5" fill="var(--faint)">{kfmt(t)}</text></g>))}
    <path d={area} fill="var(--accent)" fillOpacity=".1"/>
    <path d={line} fill="none" stroke="var(--accent)" strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round"/>
    {data.map((d,i)=>(<g key={i}>
      <circle cx={gx(i)} cy={y(d.total)} r="3" fill="var(--accent)" stroke="var(--surface)" strokeWidth="1.5"><title>{lbl(d.date)} · กำไรสะสม {d.total.toLocaleString("th-TH",{maximumFractionDigits:2})} บาท</title></circle>
      {i%step===0 && <text x={gx(i)} y={H-9} textAnchor="middle" fontSize="9" fill="var(--muted)">{lbl(d.date)}</text>}
    </g>))}
  </svg></div>);
}


/* ---------- รายงานกำไร/ขาดทุน — /reports/profit-loss ---------- */
function ProfitLossPage({ toast }) {
  const [d,setD]=useState(null),[loading,setLoading]=useState(true),[err,setErr]=useState(null);
  const [range,setRange]=useState("30d"),[custom,setCustom]=useState({from:bkkDate(29),to:bkkDate(0)});
  const [exp,setExp]=useState([]),[expOpen,setExpOpen]=useState(false),[expBusyId,setExpBusyId]=useState(null);
  const load=useCallback(async(rg,cust)=>{ setLoading(true); setErr(null);
    try{ const {from,to}=rangeToDates(rg,cust);
      const [pl,ex]=await Promise.all([api("/reports/profit-loss?from="+from+"&to="+to), api("/reports/expenses?from="+from+"&to="+to).catch(()=>({rows:[]}))]);
      setD(pl); setExp((ex&&ex.rows)||[]); }
    catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail&&window.__nxAuthFail();} setErr(e.status===403?"ไม่มีสิทธิ์ดูรายงานกำไร/ขาดทุน":(e.message||"โหลดไม่สำเร็จ")); }
    finally{ setLoading(false); } },[]);
  useEffect(()=>{ load(range,custom); },[range,load]);
  const delExp=async(r)=>{ if(!window.confirm("ลบรายจ่ายนี้?"))return; setExpBusyId(r.id);
    try{ await api("/reports/expenses/"+r.id,{method:"DELETE"}); toast("ลบแล้ว"); load(range,custom); }catch(e){ toast(e.message||"ไม่สำเร็จ"); }finally{ setExpBusyId(null); } };
  const rows=(d&&d.rows)||[], t=(d&&d.totals)||{};
  const past=rows.filter(r=>!r.is_future);
  const doExport=()=>{ csvDownload("profit-loss-"+bkkDate(0)+".csv",[["วันที่","ฝาก(บาท)","ถอน(บาท)","รายจ่าย(บาท)","โบนัส(บาท)","กำไร(บาท)","กำไรสุทธิ(บาท)"],...past.map(r=>[r.date,(r.deposit/100).toFixed(2),(r.withdraw/100).toFixed(2),(r.expense/100).toFixed(2),(r.bonus/100).toFixed(2),(r.profit/100).toFixed(2),(r.net_profit/100).toFixed(2)])]); toast("ส่งออกแล้ว"); };
  const netColor=Number(t.net_profit||0)>=0?"var(--success)":"var(--danger)";
  return (<div className="space-y-4">
    <HistToolbar range={range} setRange={setRange} custom={custom} setCustom={setCustom} onReload={()=>load(range,custom)} onExport={doExport} loading={loading} count={past.length}/>
    {err ? <HistErr msg={err} onRetry={()=>load(range,custom)}/> : (<>
      <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
        <StatMini k="ยอดฝากรวม" v={loading?"…":money2(t.deposit)} color="var(--success)"/>
        <StatMini k="ยอดถอนรวม" v={loading?"…":money2(t.withdraw)} color="var(--danger)"/>
        <StatMini k="รายจ่าย (กรอกมือ)" v={loading?"…":money2(t.expense)} color="var(--warn)"/>
        <StatMini k="กำไรสุทธิ" v={loading?"…":money2(t.net_profit)} color={netColor} sub={"ก่อนหักรายจ่าย "+money2(t.profit)}/>
      </div>
      <div className="rounded-xl border border-line bg-surface p-4 shadow-sm">
        <div className="mb-3 flex items-center justify-between"><div className="text-sm font-semibold">กำไรสะสมรายวัน</div>
          <div className="flex items-center gap-1.5 text-xs text-muted"><span className="h-0.5 w-5 rounded" style={{background:"var(--accent)"}}/>ยอดกำไรสุทธิสะสม</div></div>
        {loading ? <div className="skel h-[220px] w-full"/> : <NetProfitChart rows={rows}/>}
      </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-warn" style={{background:"var(--warn-soft)"}}><Ic d={I.wdr} size={15}/></span>
          <div className="text-sm font-semibold">รายจ่ายรายวัน (กรอกมือ)</div>
          <span className="text-xs text-muted tnum">รวม {money2(exp.reduce((a,r)=>a+Number(r.amount||0),0))}</span>
          <button onClick={()=>setExpOpen(true)} className="ml-auto flex h-8 items-center gap-1.5 rounded-lg px-2.5 text-xs font-semibold text-white shadow-sm" style={{background:"var(--warn)"}}><Ic d={I.plus} size={15} sw={2}/> เพิ่มรายจ่าย</button>
        </div>
        <div className="max-h-64 divide-y divide-line-soft overflow-y-auto">
          {exp.length===0 ? <div className="py-6 text-center text-sm text-muted">ยังไม่มีรายจ่ายในช่วงนี้</div>
            : exp.map((r,i)=>(<div key={r.id||i} className="flex items-center gap-3 px-4 py-2.5 text-sm">
              <div className="min-w-0 flex-1"><div className="truncate font-medium text-fg-2">{r.note||"รายจ่าย"}</div><div className="text-[11px] text-faint">{r.date} · โดย {r.created_by_username||"-"}</div></div>
              <span className="tnum font-semibold text-warn">-{money2(r.amount)}</span>
              <button disabled={expBusyId===r.id} title="ลบ" onClick={()=>delExp(r)} className="grid h-7 w-7 place-items-center rounded-lg border hover:bg-sunken disabled:opacity-50" style={{borderColor:"var(--danger)",color:"var(--danger)"}}><Ic d={I.trash} size={13}/></button>
            </div>))}
        </div>
      </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>{histTh("วันที่")}{histTh("ฝาก","text-right")}{histTh("ถอน","text-right")}{histTh("รายจ่าย","text-right")}{histTh("โบนัส","text-right")}{histTh("กำไรสุทธิ","text-right 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="6"><div className="skel h-5 w-full"/></td></tr>))
            : past.length===0 ? (<tr><td colSpan="6" className="px-4 py-16 text-center text-sm font-medium text-fg-2">ไม่มีข้อมูล</td></tr>)
            : past.slice().reverse().map((r,i)=>{ const neg=Number(r.net_profit)<0; return (<tr key={r.date||i} className={"border-b border-line-soft transition-colors last:border-0 hover:bg-sunken/50 "+(r.is_today?"bg-accent-soft/40":"")}>
              <td className="whitespace-nowrap px-3 py-2.5 text-xs text-fg-2">{r.date}{r.is_today?" (วันนี้)":""}</td>
              <td className="whitespace-nowrap px-3 text-right tnum text-success">{money2(r.deposit)}</td>
              <td className="whitespace-nowrap px-3 text-right tnum text-danger">{money2(r.withdraw)}</td>
              <td className="whitespace-nowrap px-3 text-right tnum text-warn">{money2(r.expense)}</td>
              <td className="whitespace-nowrap px-3 text-right tnum text-muted">{money2(r.bonus)}</td>
              <td className="whitespace-nowrap px-3 text-right font-semibold tnum pr-4" style={{color:neg?"var(--danger)":"var(--success)"}}>{neg?"":"+"}{money2(r.net_profit)}</td>
            </tr>); })}
        </tbody>
      </table></div></div>
    </>)}
    {expOpen && <ExpenseAddModal onClose={()=>setExpOpen(false)} onDone={()=>load(range,custom)} toast={toast}/>}
  </div>);
}

function ExpenseAddModal({ onClose, onDone, toast }) {
  const [date,setDate]=useState(bkkDate(0));
  const [amt,setAmt]=useState("");
  const [note,setNote]=useState("");
  const [busy,setBusy]=useState(false);
  const inp="mt-1 h-10 w-full rounded-lg border border-line bg-sunken px-3 text-sm text-fg placeholder:text-faint focus:border-accent focus:bg-surface focus:outline-none focus:ring-4 focus:ring-[var(--accent-ring)]";
  const submit=async()=>{
    const b=parseFloat(amt); if(!b||b<=0){ toast("กรอกจำนวนเงินให้ถูกต้อง"); return; }
    if(!/^\d{4}-\d{2}-\d{2}$/.test(date)){ toast("เลือกวันที่ให้ถูกต้อง"); return; }
    setBusy(true);
    try{ await api("/reports/expenses",{method:"POST",body:{date,amount:Math.round(b*100),note:note.trim()||null}});
      toast("เพิ่มรายจ่าย "+b.toLocaleString("th-TH")+" บาท แล้ว"); onDone&&onDone(); onClose();
    }catch(e){ toast(e.message||"ไม่สำเร็จ"); }finally{ setBusy(false); }
  };
  return (<div className="fixed inset-0 z-[80] flex items-center justify-center p-4 fade-in" onMouseDown={()=>!busy&&onClose()}>
    <div className="absolute inset-0 bg-black/55"/>
    <div className="pop relative w-full max-w-sm rounded-2xl border border-line bg-surface2 p-5 shadow-lg" onMouseDown={(e)=>e.stopPropagation()}>
      <div className="text-base font-semibold">เพิ่มรายจ่ายรายวัน</div>
      <p className="mt-0.5 text-xs text-muted">รายจ่ายกรอกมือ จะถูกหักออกจากกำไรสุทธิของวันนั้น</p>
      <label className="mt-3 block"><span className="text-xs font-medium text-fg-2">วันที่</span><input type="date" className={inp} value={date} onChange={(e)=>setDate(e.target.value)}/></label>
      <label className="mt-3 block"><span className="text-xs font-medium text-fg-2">จำนวนเงิน (บาท)</span><input type="number" inputMode="decimal" className={inp+" tnum"} value={amt} onChange={(e)=>setAmt(e.target.value)} placeholder="0.00"/></label>
      <label className="mt-3 block"><span className="text-xs font-medium text-fg-2">หมายเหตุ</span><input className={inp} value={note} onChange={(e)=>setNote(e.target.value)} placeholder="เช่น ค่าโฆษณา, ค่าพนักงาน"/></label>
      <div className="mt-4 flex items-center justify-end gap-2">
        <button onClick={onClose} className="h-9 rounded-lg border border-line bg-surface px-3 text-sm font-medium text-fg-2 hover:bg-sunken">ยกเลิก</button>
        <button disabled={busy} onClick={submit} className="h-9 rounded-lg px-4 text-sm font-semibold text-white disabled:opacity-50" style={{background:"var(--warn)"}}>{busy?"กำลังทำ…":"เพิ่ม"}</button>
      </div>
    </div>
  </div>);
}
