/* ==========================================================================
 * ADMIN NEXT — page-abdconsole.jsx  (ABD Console)
 * ========================================================================== */

function AbdConsolePage({ toast }) {
  const [tab,setTab]=useState("devices"); // devices | settings
  const Tb=({k,label})=><button onClick={()=>setTab(k)} className={"rounded-lg px-4 py-2 text-sm font-medium transition-colors "+(tab===k?"bg-accent text-accent-fg":"text-fg-2 hover:bg-sunken")}>{label}</button>;

  return (<div className="space-y-5">
    <div className="flex gap-1 rounded-lg bg-sunken p-1"><Tb k="devices" label="อุปกรณ์"/><Tb k="settings" label="ตั้งค่า"/></div>
    {tab==="devices"&&<AbdDevices toast={toast}/>}
    {tab==="settings"&&<AbdSettings toast={toast}/>}
  </div>);
}

function AbdDevices({ toast }) {
  const [devices,setDevices]=useState([]);
  const [apps,setApps]=useState([]);
  const [loading,setLoading]=useState(true);
  const [err,setErr]=useState(null);

  const load=useCallback(async()=>{ setLoading(true); setErr(null);
    try{
      const [dev,ap]=await Promise.all([
        api("/abd-console/devices").catch(()=>[]),
        api("/abd-console/apps").catch(()=>[])
      ]);
      setDevices(Array.isArray(dev)?dev:dev.devices||[]);
      setApps(Array.isArray(ap)?ap:ap.apps||[]);
    }catch(e){ if(e.status===401||e.status===403){window.__nxAuthFail?.();} setErr(e.message||"โหลดไม่สำเร็จ"); }
    finally{ setLoading(false); } },[]);
  useEffect(()=>{ load(); },[load]);

  const sendAction=async(device_id,action,payload={})=>{
    try{ await api(`/abd-console/device/${action}`,{method:"POST",body:{device_id,...payload}}); toast(`${action} สำเร็จ`); }
    catch(e){ toast(e.message||`${action} ไม่สำเร็จ`); }
  };

  const [labelEdit,setLabelEdit]=useState(null);
  const [labelVal,setLabelVal]=useState("");
  const saveLabel=async()=>{
    if(!labelEdit) return;
    try{ await api("/abd-console/device-label",{method:"PATCH",body:{device_id:labelEdit,label:labelVal}}); toast("บันทึกแล้ว"); setLabelEdit(null); load(); }
    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}/>;

  return (<div className="space-y-4">
    <div className="flex items-center gap-2"><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>

    <h3 className="text-sm font-semibold text-fg">อุปกรณ์ที่เชื่อมต่อ ({devices.length})</h3>
    {devices.length===0?<div className="rounded-lg border border-line bg-surface p-8 text-center text-sm text-muted">ไม่มีอุปกรณ์เชื่อมต่อ</div>:(
    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
      {devices.map((d,i)=>(
        <div key={d.device_id||i} className="rounded-xl border border-line bg-surface p-4 shadow-sm space-y-3">
          <div className="flex items-center justify-between">
            <div className="font-medium text-sm">{d.label||d.device_id||`Device ${i+1}`}</div>
            <Badge color={d.status==="online"?"green":"red"}>{d.status||"unknown"}</Badge>
          </div>
          <div className="text-xs text-muted space-y-1">
            {d.device_id&&<div>ID: <span className="mono">{d.device_id}</span></div>}
            {d.model&&<div>Model: {d.model}</div>}
          </div>
          <div className="flex flex-wrap gap-2">
            <button onClick={()=>sendAction(d.device_id,"screenshot")} className="rounded border border-line px-2 py-1 text-xs text-fg-2 hover:bg-sunken">Screenshot</button>
            <button onClick={()=>sendAction(d.device_id,"home")} className="rounded border border-line px-2 py-1 text-xs text-fg-2 hover:bg-sunken">Home</button>
            <button onClick={()=>sendAction(d.device_id,"back")} className="rounded border border-line px-2 py-1 text-xs text-fg-2 hover:bg-sunken">Back</button>
            <button onClick={()=>{setLabelEdit(d.device_id);setLabelVal(d.label||"");}} className="rounded border border-line px-2 py-1 text-xs text-accent hover:bg-sunken">ตั้งชื่อ</button>
          </div>
        </div>))}
    </div>)}

    {apps.length>0&&(<>
      <h3 className="text-sm font-semibold text-fg mt-6">แอปที่ติดตั้ง ({apps.length})</h3>
      <div className="overflow-x-auto rounded-xl border border-line bg-surface shadow-sm">
        <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">Package</th>
          </tr></thead>
          <tbody>{apps.map((a,i)=>(
            <tr key={i} className="border-b border-line last:border-0 hover:bg-sunken/40">
              <td className="px-4 py-3">{a.name||a.label||"-"}</td>
              <td className="px-4 py-3 mono text-muted text-xs">{a.package||a.packageName||"-"}</td>
            </tr>))}</tbody>
        </table>
      </div>
    </>)}

    {labelEdit&&(<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 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="mb-3 text-sm font-semibold">ตั้งชื่ออุปกรณ์</h3>
        <input type="text" value={labelVal} onChange={e=>setLabelVal(e.target.value)} placeholder="ชื่ออุปกรณ์" className="mb-4 w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/>
        <div className="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>);
}

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

  const load=useCallback(async()=>{ setLoading(true); setErr(null);
    try{ const d=await api("/abd-console/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("/abd-console/settings",{method:"PATCH",body:cfg}); toast("บันทึกแล้ว"); }
    catch(e){ toast(e.message||"บันทึกไม่สำเร็จ"); } finally{ setSaving(false); } };
  const set=(k,v)=>setCfg(c=>({...c,[k]:v}));

  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-4">
    <div className="rounded-xl border border-line bg-surface p-5 shadow-sm space-y-4">
      <h3 className="text-sm font-semibold text-fg">ตั้งค่า ABD Console</h3>
      {Object.entries(cfg).map(([k,v])=>(
        <div key={k}><label className="mb-1 block text-xs font-semibold text-fg-2">{k.replace(/_/g," ")}</label>
        {typeof v==="boolean"?(<label className="flex items-center gap-2 cursor-pointer"><input type="checkbox" checked={v} onChange={e=>set(k,e.target.checked)} className="h-4 w-4 rounded border-line accent-accent"/><span className="text-sm text-fg-2">{v?"เปิด":"ปิด"}</span></label>)
        :(<input type="text" value={v||""} onChange={e=>set(k,e.target.value)} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm"/>)}
        </div>))}
    </div>
    <div className="flex justify-end"><button onClick={save} disabled={saving} 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>);
}
