/* ==========================================================================
 * ADMIN NEXT — page-whitelabel.jsx  (White Label + Server Health)
 * ========================================================================== */

function WhiteLabelPage({ toast }) {
  const [cfg,setCfg]=useState({}),[loading,setLoading]=useState(true),[saving,setSaving]=useState(false),[err,setErr]=useState(null);
  const [uploading,setUploading]=useState(null);

  const load=useCallback(async()=>{ setLoading(true); setErr(null);
    try{ const d=await api("/settings"); setCfg(d||{}); }
    catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail?.();} setErr(e.message||"โหลดไม่สำเร็จ"); }
    finally{ setLoading(false); } },[]);
  useEffect(()=>{ load(); },[load]);

  const save=async()=>{ setSaving(true);
    try{
      const keys=["wl_copyright","wl_line_url","wl_telegram_url","wl_live_url","wl_partners","wl_certs","wl_responsible","wl_security","wl_loading_logo2_url","wl_loading_logo2_link","wl_loading_logo2_width","wl_loading_logo2_height","wl_footer_logo2_url","wl_footer_logo2_link","wl_footer_logo2_width","wl_footer_logo2_height","wl_reg_phone_hint","wl_reg_age_label","wl_reg_age_error","wl_reg_terms_link_label","wl_reg_terms_title","wl_reg_terms_intro","wl_reg_terms_content","wl_reg_terms_footer_title","wl_reg_terms_footer_text"];
      const body={};
      keys.forEach(k=>{ body[k]=cfg[k]||""; });
      await api("/settings",{method:"POST",body});
      toast("บันทึกแล้ว");
    }catch(e){ toast(e.message||"บันทึกไม่สำเร็จ"); } finally{ setSaving(false); } };
  const set=(k,v)=>setCfg(c=>({...c,[k]:v}));

  const uploadImg=async(settingKey,kind)=>{
    const input=document.createElement("input"); input.type="file"; input.accept="image/png,image/jpeg,image/webp,image/gif";
    input.onchange=async()=>{
      const file=input.files[0]; if(!file)return;
      if(file.size>10*1024*1024){ toast("ไฟล์รูปต้องไม่เกิน 10MB"); return; }
      setUploading(settingKey);
      try{
        const dataUrl=await new Promise((res,rej)=>{ const r=new FileReader(); r.onload=()=>res(r.result); r.onerror=rej; r.readAsDataURL(file); });
        const r=await api("/branding/upload",{method:"POST",body:{kind,fileName:file.name,mimeType:file.type,dataUrl,noSave:true}});
        if(r&&r.url){ set(settingKey,r.url); toast("อัพโหลดสำเร็จ"); }
      }catch(e){ toast(e.message||"อัพโหลดไม่สำเร็จ"); }
      finally{ setUploading(null); }
    };
    input.click();
  };

  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}/>;

  const Lb=({children})=><label className="mb-1 block text-xs font-semibold text-fg-2">{children}</label>;
  const In=({k,ph=""})=><input type="text" value={cfg[k]||""} onChange={e=>set(k,e.target.value)} placeholder={ph} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/>;
  const NumIn=({k,ph=""})=><input type="number" value={cfg[k]||""} onChange={e=>set(k,e.target.value)} placeholder={ph} className="w-32 rounded-lg border border-line bg-surface px-3 py-2 text-sm"/>;
  const Section=({title,children})=><div className="rounded-xl border border-line bg-surface p-5 shadow-sm space-y-4"><h3 className="text-sm font-semibold text-fg">{title}</h3>{children}</div>;

  const LogoRow=({settingKey,kind,label})=>{
    const url=cfg[settingKey]||"";
    return (<div className="space-y-2">
      <Lb>{label}</Lb>
      <div className="flex gap-3">
        <div className="grid h-16 w-16 shrink-0 place-items-center rounded-lg bg-sunken overflow-hidden">
          {url?<img src={url} className="h-full w-full object-contain" onError={e=>{e.target.style.display="none"}}/>:<Ic d={I.grid} size={20} cls="text-faint"/>}
        </div>
        <div className="min-w-0 flex-1 space-y-1.5">
          <input type="text" value={url} onChange={e=>set(settingKey,e.target.value)} placeholder={"/uploads/branding/"+kind+".png หรือ https://..."} className="w-full rounded-lg border border-line bg-surface px-3 py-1.5 text-xs"/>
          <div className="flex gap-2">
            <button onClick={()=>uploadImg(settingKey,kind)} disabled={uploading===settingKey} className="rounded-lg border border-line px-2.5 py-1 text-[11px] font-medium text-accent hover:bg-accent-soft disabled:opacity-50">{uploading===settingKey?"กำลังอัพ…":"อัปโหลดรูป"}</button>
            {url&&<button onClick={()=>set(settingKey,"")} className="rounded-lg border border-line px-2.5 py-1 text-[11px] font-medium text-danger hover:bg-red-500/10">ล้างรูป</button>}
          </div>
        </div>
      </div>
    </div>);
  };

  return (<div className="space-y-5">
    <div className="rounded-xl border border-accent/30 bg-accent-soft/30 p-4">
      <p className="text-xs text-fg-2"><b>หมายเหตุ:</b> ตั้งค่าธีม/โลโก้/สี/พื้นหลัง/Hero Banner ย้ายไปอยู่ที่ <b>ตั้งค่าเว็บไซต์</b> แล้ว — หน้านี้ตั้งค่าเฉพาะ White Label (โลโก้ที่ 2 + Footer)</p>
    </div>

    {Section({title:"โลโก้ที่ 2 (หน้า Loading)",children:<>
      <p className="text-xs text-muted">โลโก้ที่แสดงในกรอบด้านล่างหน้าจอ Loading เมื่อเปิดเกม</p>
      {LogoRow({settingKey:"wl_loading_logo2_url",kind:"loading_logo2",label:"URL รูปโลโก้ Loading"})}
      <div><Lb>ลิงก์เมื่อคลิกโลโก้ Loading</Lb>{In({k:"wl_loading_logo2_link",ph:"https://example.com (ว่างไว้ = ไม่มีลิงก์)"})}</div>
      <div className="grid grid-cols-2 gap-3">
        <div><Lb>ความกว้าง (px)</Lb>{NumIn({k:"wl_loading_logo2_width",ph:"150"})}</div>
        <div><Lb>ความสูง (px)</Lb>{NumIn({k:"wl_loading_logo2_height",ph:"50"})}</div>
      </div>
    </>})}

    {Section({title:"โลโก้ที่ 2 (Footer ด้านล่างเว็บ)",children:<>
      <p className="text-xs text-muted">โลโก้ที่แสดงใน Footer ด้านล่างสุดของเว็บไซต์</p>
      {LogoRow({settingKey:"wl_footer_logo2_url",kind:"footer_logo2",label:"URL รูปโลโก้ Footer"})}
      <div><Lb>ลิงก์เมื่อคลิกโลโก้ Footer</Lb>{In({k:"wl_footer_logo2_link",ph:"https://example.com (ว่างไว้ = ไม่มีลิงก์)"})}</div>
      <div className="grid grid-cols-2 gap-3">
        <div><Lb>ความกว้าง (px)</Lb>{NumIn({k:"wl_footer_logo2_width",ph:"200"})}</div>
        <div><Lb>ความสูง (px)</Lb>{NumIn({k:"wl_footer_logo2_height",ph:"60"})}</div>
      </div>
    </>})}

    {Section({title:"เงื่อนไขสมัครสมาชิก (หน้าบ้าน)",children:<>
      <p className="text-xs text-muted">ข้อความทั้งหมดจะแสดงในหน้าสมัครสมาชิกของหน้าบ้าน ใช้การขึ้นบรรทัดใหม่เพื่อแยกแต่ละข้อ และรูปแบบ “หัวข้อ|รายละเอียด” เพื่อทำเป็นการ์ดหัวข้อ</p>
      <div><Lb>คำอธิบายช่องเบอร์โทรศัพท์</Lb><textarea value={cfg.wl_reg_phone_hint||""} onChange={e=>set("wl_reg_phone_hint",e.target.value)} rows={2} placeholder="ใส่หมายเลขโทรศัพท์ 10 หลัก ใช้สำหรับเข้าสู่ระบบ" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
      <div><Lb>ข้อความยืนยันอายุและเงื่อนไข</Lb><textarea value={cfg.wl_reg_age_label||""} onChange={e=>set("wl_reg_age_label",e.target.value)} rows={2} placeholder="ฉันยืนยันว่ามีอายุ 18 ปีขึ้นไปและยอมรับเงื่อนไขการใช้งาน" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
      <div><Lb>ข้อความแจ้งเตือนเมื่อไม่ยืนยัน</Lb><textarea value={cfg.wl_reg_age_error||""} onChange={e=>set("wl_reg_age_error",e.target.value)} rows={2} placeholder="กรุณายืนยันอายุและยอมรับเงื่อนไขการใช้งาน" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
      <div><Lb>ข้อความลิงก์เปิดเงื่อนไข</Lb>{In({k:"wl_reg_terms_link_label",ph:"อ่านเงื่อนไขการใช้งาน"})}</div>
      <div><Lb>หัวข้อหน้าต่างเงื่อนไข</Lb>{In({k:"wl_reg_terms_title",ph:"เงื่อนไขการใช้งาน"})}</div>
      <div><Lb>ข้อความเกริ่นนำ</Lb><textarea value={cfg.wl_reg_terms_intro||""} onChange={e=>set("wl_reg_terms_intro",e.target.value)} rows={2} placeholder="โปรดอ่านข้อกำหนดก่อนสมัครสมาชิกและใช้บริการ" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
      <div><Lb>เนื้อหาเงื่อนไข (หนึ่งข้อต่อหนึ่งบรรทัด รูปแบบ หัวข้อ|รายละเอียด)</Lb><textarea value={cfg.wl_reg_terms_content||""} onChange={e=>set("wl_reg_terms_content",e.target.value)} rows={10} placeholder={"คุณสมบัติผู้ใช้บริการ|ผู้ใช้บริการต้องมีอายุถึงเกณฑ์ตามกฎหมาย\\nบัญชีสมาชิก|ใช้ข้อมูลจริงและเก็บรักษารหัสผ่าน\\nความเป็นส่วนตัว|ข้อมูลจะถูกใช้ตามนโยบายความเป็นส่วนตัว"} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm font-mono"/></div>
      <div><Lb>หัวข้อข้อความส่วนท้าย</Lb>{In({k:"wl_reg_terms_footer_title",ph:"ใช้บริการอย่างมีความรับผิดชอบ"})}</div>
      <div><Lb>ข้อความส่วนท้าย / คำเตือน</Lb><textarea value={cfg.wl_reg_terms_footer_text||""} onChange={e=>set("wl_reg_terms_footer_text",e.target.value)} rows={3} placeholder="โปรดใช้งานอย่างมีสติและศึกษาความเสี่ยงก่อนตัดสินใจ" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
    </>})}

    {Section({title:"ข้อความและช่องทางติดต่อ Footer",children:<>
      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
        <div><Lb>Copyright</Lb>{In({k:"wl_copyright",ph:"Copyright © GameHub. All Rights Reserved."})}</div>
        <div><Lb>LINE URL</Lb>{In({k:"wl_line_url",ph:"https://line.me/ti/p/~@yourline"})}</div>
        <div><Lb>Telegram URL</Lb>{In({k:"wl_telegram_url",ph:"https://t.me/yourusername"})}</div>
        <div><Lb>Live Chat URL</Lb>{In({k:"wl_live_url",ph:"https://livechat..."})}</div>
      </div>
      <div><Lb>Partners (คั่น , )</Lb>{In({k:"wl_partners",ph:"EVOPLAY, CQ9, JILI, ..."})}</div>
      <div><Lb>ใบอนุญาต (คั่น , )</Lb>{In({k:"wl_certs",ph:"Curaçao eGaming, iTech Labs, ..."})}</div>
      <div><Lb>การรับผิดชอบ (คั่น , )</Lb>{In({k:"wl_responsible",ph:"18+, GamCare, ..."})}</div>
      <div><Lb>ความปลอดภัย (คั่น , )</Lb>{In({k:"wl_security",ph:"Verified, SSL Secured"})}</div>
    </>})}

    <div className="flex gap-2 justify-end">
      <button onClick={load} className="rounded-lg border border-line px-4 py-2.5 text-sm font-medium text-fg-2 hover:bg-sunken">รีเฟรช</button>
      <button disabled={saving} onClick={save} className="rounded-lg bg-accent px-6 py-2.5 text-sm font-medium text-accent-fg hover:bg-accent-h disabled:opacity-50">{saving?"กำลังบันทึก…":"บันทึก"}</button>
    </div>
  </div>);
}

function ServerHealthPage({ toast }) {
  const [data,setData]=useState(null),[loading,setLoading]=useState(true),[err,setErr]=useState(null);
  const [auto,setAuto]=useState(true);
  const samplesRef=useRef([]);

  const load=useCallback(async(quiet)=>{ if(!quiet)setLoading(true); setErr(null);
    try{
      const d=await api("/system-health");
      setData(d);
      const host=d.host||{};
      const total=Number(host.totalmem||0);
      const available=Number(host.availablemem??host.freemem??0);
      const net=host.network||{};
      const sample={ts:Date.parse(d.checkedAt)||Date.now(),memoryPct:total?Math.max(0,Math.min(100,((total-available)/total)*100)):0,cpuLoadPct:Number(host.cpu?.loadPct||0),cpuTimes:host.cpu?.times||null,rxBytes:Number(net.rxBytes||0),txBytes:Number(net.txBytes||0),rxRate:0,txRate:0};
      const prev=samplesRef.current[samplesRef.current.length-1];
      if(prev&&prev.cpuTimes&&sample.cpuTimes){const a=prev.cpuTimes,b=sample.cpuTimes;const dt=b.total-a.total;sample.cpuPct=dt>0?Math.max(0,Math.min(100,(1-(b.idle-a.idle)/dt)*100)):sample.cpuLoadPct;}else{sample.cpuPct=sample.cpuLoadPct;}
      if(prev&&sample.ts>prev.ts&&sample.rxBytes>=prev.rxBytes){const sec=(sample.ts-prev.ts)/1000;sample.rxRate=(sample.rxBytes-prev.rxBytes)/sec;sample.txRate=(sample.txBytes-prev.txBytes)/sec;}
      samplesRef.current.push(sample);
      if(samplesRef.current.length>36)samplesRef.current.shift();
    }catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail?.();} if(!quiet)setErr(e.message||"โหลดไม่สำเร็จ"); }
    finally{ if(!quiet)setLoading(false); } },[]);

  useEffect(()=>{ load(false); },[load]);
  useEffect(()=>{ if(!auto)return; const t=setInterval(()=>load(true),2000); return ()=>clearInterval(t); },[auto,load]);

  const fmtRate=(b)=>{if(b>=1048576)return(b/1048576).toFixed(1)+" MB/s";if(b>=1024)return(b/1024).toFixed(1)+" KB/s";return Math.round(b)+" B/s";};
  const fmtMem=(b)=>{if(!b)return"0";if(b>=1073741824)return(b/1073741824).toFixed(1)+" GB";if(b>=1048576)return(b/1048576).toFixed(0)+" MB";return(b/1024).toFixed(0)+" KB";};

  const drawChart=(canvas,values,color,maxVal=100)=>{
    if(!canvas)return;
    const rect=canvas.getBoundingClientRect();const dpr=window.devicePixelRatio||1;
    canvas.width=Math.max(1,Math.round(rect.width*dpr));canvas.height=Math.max(1,Math.round(rect.height*dpr));
    const ctx=canvas.getContext("2d");ctx.setTransform(dpr,0,0,dpr,0,0);
    const w=rect.width,h=rect.height;ctx.clearRect(0,0,w,h);
    ctx.strokeStyle="rgba(143,170,191,.18)";ctx.lineWidth=1;
    for(let i=1;i<4;i++){const y=(h/4)*i;ctx.beginPath();ctx.moveTo(0,y);ctx.lineTo(w,y);ctx.stroke();}
    const pts=values.length?values:[0];const mx=Math.max(maxVal,...pts,1);
    ctx.beginPath();
    pts.forEach((v,i)=>{const x=pts.length===1?w:(i/(pts.length-1))*w;const y=h-(Math.max(0,v)/mx)*(h-8)-4;if(i===0)ctx.moveTo(x,y);else ctx.lineTo(x,y);});
    ctx.strokeStyle=color;ctx.lineWidth=2.5;ctx.stroke();
    ctx.lineTo(w,h);ctx.lineTo(0,h);ctx.closePath();
    const grad=ctx.createLinearGradient(0,0,0,h);grad.addColorStop(0,color.replace(")",", .22)").replace("rgb","rgba"));grad.addColorStop(1,"rgba(0,0,0,0)");ctx.fillStyle=grad;ctx.fill();
  };

  const cpuRef=useCallback(el=>{if(el)drawChart(el,samplesRef.current.map(s=>s.cpuPct||0),"rgb(65,240,152)",100);},[data]);
  const ramRef=useCallback(el=>{if(el)drawChart(el,samplesRef.current.map(s=>s.memoryPct||0),"rgb(0,220,255)",100);},[data]);
  const bwRef=useCallback(el=>{const mx=Math.max(...samplesRef.current.map(s=>(s.rxRate||0)+(s.txRate||0)),1024);if(el)drawChart(el,samplesRef.current.map(s=>(s.rxRate||0)+(s.txRate||0)),"rgb(255,214,107)",mx);},[data]);

  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(false)}/>;
  if(!data) return null;

  const host=data.host||{};const checks=data.checks||[];const mem=data.process?.memory||{};
  const total=Number(host.totalmem||0);const available=Number(host.availablemem??host.freemem??0);
  const usedMem=Math.max(0,total-available);const memPct=total?Math.round((usedMem/total)*100):0;
  const last=samplesRef.current[samplesRef.current.length-1]||{};

  return (<div className="space-y-4">
    <div className="flex items-center gap-3">
      <button onClick={()=>load(false)} 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>
      <label className="flex items-center gap-2 cursor-pointer"><input type="checkbox" checked={auto} onChange={e=>setAuto(e.target.checked)} className="h-4 w-4 rounded border-line accent-accent"/><span className="text-sm text-fg-2">Auto-refresh (2 วินาที)</span></label>
    </div>

    <div className={"rounded-xl border p-4 flex items-center gap-3 "+(data.ok?"border-green-500/30 bg-green-500/5":"border-red-500/30 bg-red-500/5")}>
      <div className={"h-3 w-3 rounded-full "+(data.ok?"bg-green-500":"bg-red-500")}/>
      <div>
        <div className="text-sm font-semibold text-fg">{data.ok?"ระบบพร้อมใช้งาน":"มีบริการที่ต้องตรวจสอบ"}</div>
        <div className="text-[11px] text-muted">ตรวจล่าสุด {data.checkedAt?new Date(data.checkedAt).toLocaleString("th-TH"):"-"} · {Number(data.latencyMs||0)} ms</div>
      </div>
    </div>

    <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
      <div className="rounded-xl border border-line bg-surface p-4 shadow-sm">
        <div className="flex items-center justify-between mb-2"><span className="text-xs font-semibold text-muted">CPU</span><span className="text-lg font-bold text-fg tnum">{Math.round(last.cpuPct||0)}%</span></div>
        <canvas ref={cpuRef} className="w-full h-20" style={{display:"block"}}/>
        <div className="mt-1 text-[11px] text-muted">Load {(host.loadavg||[]).map(v=>Number(v||0).toFixed(2)).join(" / ")||"-"}</div>
      </div>
      <div className="rounded-xl border border-line bg-surface p-4 shadow-sm">
        <div className="flex items-center justify-between mb-2"><span className="text-xs font-semibold text-muted">RAM</span><span className="text-lg font-bold text-fg tnum">{memPct}%</span></div>
        <canvas ref={ramRef} className="w-full h-20" style={{display:"block"}}/>
        <div className="mt-1 text-[11px] text-muted">{fmtMem(usedMem)} / {fmtMem(total)}</div>
      </div>
      <div className="rounded-xl border border-line bg-surface p-4 shadow-sm">
        <div className="flex items-center justify-between mb-2"><span className="text-xs font-semibold text-muted">Bandwidth</span><span className="text-lg font-bold text-fg tnum">{fmtRate((last.rxRate||0)+(last.txRate||0))}</span></div>
        <canvas ref={bwRef} className="w-full h-20" style={{display:"block"}}/>
        <div className="mt-1 text-[11px] text-muted">ลง {fmtRate(last.rxRate||0)} · ขึ้น {fmtRate(last.txRate||0)}</div>
      </div>
    </div>

    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
      <div className="rounded-xl border border-line bg-surface p-4 shadow-sm">
        <h4 className="text-xs font-semibold text-muted mb-2">Process Memory</h4>
        <div className="space-y-1 text-sm">
          <div className="flex justify-between"><span className="text-fg-2">RSS</span><span className="font-medium text-fg tnum">{fmtMem(mem.rss)}</span></div>
          <div className="flex justify-between"><span className="text-fg-2">Heap Total</span><span className="font-medium text-fg tnum">{fmtMem(mem.heapTotal)}</span></div>
          <div className="flex justify-between"><span className="text-fg-2">Heap Used</span><span className="font-medium text-fg tnum">{fmtMem(mem.heapUsed)}</span></div>
          <div className="flex justify-between"><span className="text-fg-2">External</span><span className="font-medium text-fg tnum">{fmtMem(mem.external)}</span></div>
        </div>
      </div>
      {checks.length>0&&<div className="rounded-xl border border-line bg-surface p-4 shadow-sm">
        <h4 className="text-xs font-semibold text-muted mb-2">Service Checks</h4>
        <div className="space-y-1">
          {checks.map((c,i)=><div key={i} className="flex items-center gap-2 text-sm"><div className={"h-2 w-2 rounded-full "+(c.ok||c.status==="ok"?"bg-green-500":"bg-red-500")}/><span className="text-fg">{c.name||c.service||"Service "+(i+1)}</span></div>)}
        </div>
      </div>}
    </div>
  </div>);
}
