/* ==========================================================================
 * ADMIN NEXT — page-notifications.jsx  (การแจ้งเตือน LINE/Telegram + LINE Login + Admin Login)
 * ========================================================================== */

function NotificationsPage({ toast }) {
  const [cfg,setCfg]=useState({}),[loading,setLoading]=useState(true),[saving,setSaving]=useState(false),[err,setErr]=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{ await api("/settings",{method:"POST",body:cfg}); toast("บันทึกแล้ว"); }
    catch(e){ toast(e.message||"บันทึกไม่สำเร็จ"); } finally{ setSaving(false); } };
  const set=(k,v)=>setCfg(c=>({...c,[k]:v}));

  const uploadAdminBg=async(file)=>{
    if(!file) return;
    if(file.size>10*1024*1024){ toast("ไฟล์ต้องไม่เกิน 10MB"); return; }
    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:"admin_login_bg",fileName:file.name,mimeType:file.type,dataUrl}});
      if(r.url) set("admin_login_bg_url",r.url);
      toast("อัปโหลดรูปแล้ว");
    }catch(e){ toast(e.message||"อัปโหลดไม่สำเร็จ"); }
  };

  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,type="text",ph=""})=><input type={type} 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 Sel=({k,options,ph})=><select value={cfg[k]||""} onChange={e=>set(k,e.target.value)} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm">{ph&&<option value="">{ph}</option>}{options.map(([v,l])=><option key={v} value={v}>{l}</option>)}</select>;
  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>;

  return (<div className="space-y-5">
    {Section({title:"ช่องทางแจ้งเตือน",children:<>
      <div><Lb>ช่องทางแจ้งเตือน</Lb>{Sel({k:"notification_channel",options:[["line","LINE Notify"],["telegram","Telegram"],["both","ทั้ง LINE + Telegram"]]})}</div>
      <div><Lb>LINE Notify Token</Lb>{In({k:"notification_line_token",type:"password"})}</div>
      <div><Lb>Telegram Bot Token</Lb>{In({k:"notification_telegram_token",type:"password"})}</div>
      <div><Lb>Telegram Chat ID</Lb>{In({k:"notification_telegram_chat_id"})}</div>
    </>})}

    {Section({title:"เหตุการณ์ที่แจ้ง",children:<>
      <div><Lb>แจ้งเตือนฝากเงิน</Lb>{Sel({k:"notification_deposit_enabled",options:[["1","เปิด"],["0","ปิด"]]})}</div>
      <div><Lb>แจ้งเตือนถอนเงิน</Lb>{Sel({k:"notification_withdraw_enabled",options:[["1","เปิด"],["0","ปิด"]]})}</div>
      <div><Lb>แจ้งเตือนเมื่อ Admin Login</Lb>{Sel({k:"notification_admin_login_enabled",options:[["1","เปิด"],["0","ปิด"]]})}</div>
      <div><Lb>แจ้งเตือนการทำงานของ Admin</Lb>{Sel({k:"notification_admin_action_enabled",options:[["1","เปิด"],["0","ปิด"]]})}</div>
    </>})}

    {Section({title:"LINE Login Connect",children:<>
      <div><Lb>LINE Login Channel ID</Lb>{In({k:"line_login_channel_id"})}</div>
      <div><Lb>LINE Login Channel Secret</Lb>{In({k:"line_login_channel_secret",type:"password"})}</div>
      <div><Lb>LINE Login Callback URL</Lb>{In({k:"line_login_redirect_uri",ph:"https://..."})}</div>
    </>})}

    {Section({title:"หน้า Login หลังบ้าน",children:<>
      <div>
        <Lb>รูปพื้นหลัง Admin Login <span className="text-xs font-normal text-muted">(แนะนำ 1920×1080px)</span></Lb>
        {In({k:"admin_login_bg_url",ph:"https://..."})}
        {cfg.admin_login_bg_url&&<img src={cfg.admin_login_bg_url} className="mt-2 max-h-32 rounded-lg border border-line object-contain" onError={e=>{e.target.style.display="none"}}/>}
        <label className="mt-2 inline-flex items-center gap-1.5 rounded-lg border border-line bg-surface px-3 py-1.5 text-xs font-medium text-fg-2 hover:bg-sunken cursor-pointer"><Ic d={I.upload||I.plus} size={14}/> อัปโหลดรูป<input type="file" accept="image/*" className="hidden" onChange={e=>uploadAdminBg(e.target.files[0])}/></label>
      </div>
    </>})}

    {Section({title:"กำหนดเวลา Login Staff",children:<>
      <div><Lb>จำกัดเวลา Login Staff</Lb>{Sel({k:"admin_login_hours_enabled",options:[["1","เปิด (Staff เข้าได้เฉพาะช่วงที่กำหนด)"],["0","ปิด (เข้าได้ตลอด 24 ชม.)"]]})}</div>
      {(cfg.admin_login_hours_enabled==="1")&&<>
        <div><Lb>เวลาเริ่มเข้าระบบ</Lb><input type="time" value={cfg.admin_login_from||""} onChange={e=>set("admin_login_from",e.target.value)} className="w-40 rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
        <div><Lb>เวลาสิ้นสุดเข้าระบบ</Lb><input type="time" value={cfg.admin_login_to||""} onChange={e=>set("admin_login_to",e.target.value)} className="w-40 rounded-lg border border-line bg-surface px-3 py-2 text-sm"/></div>
      </>}
    </>})}

    <div className="flex justify-end">
      <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>);
}
