const { contextBridge, ipcRenderer } = require("electron");

contextBridge.exposeInMainWorld("electronAPI", {
  isElectron: true,
  platform: process.platform,
  checkTef: () => ipcRenderer.invoke("tef:check"),
  ensureTef: () => ipcRenderer.invoke("tef:ensure"),
  openPdv: () => ipcRenderer.invoke("pdv:open"),
  goSplash: () => ipcRenderer.invoke("app:goSplash"),
  toggleFullscreen: () => ipcRenderer.invoke("app:toggleFullscreen"),
  quit: () => ipcRenderer.invoke("app:quit"),
  getConfig: () => ipcRenderer.invoke("config:get"),
  openConfig: () => ipcRenderer.invoke("config:open"),
  getCreds: () => ipcRenderer.invoke("creds:get"),
  saveCreds: (usuario, senha) => ipcRenderer.invoke("creds:save", { usuario, senha }),
  clearCreds: () => ipcRenderer.invoke("creds:clear"),
  hasCreds: () => ipcRenderer.invoke("creds:has"),
  // Mini-apps
  listMiniapps: () => ipcRenderer.invoke("miniapps:list"),
  saveMiniapps: (list) => ipcRenderer.invoke("miniapps:save", list),
  ensureMiniappSession: (id) => ipcRenderer.invoke("miniapps:ensure-session", id),
  popoutMiniapp: (payload) => ipcRenderer.invoke("miniapps:popout", payload),
  dockMiniapp: (id) => ipcRenderer.invoke("miniapps:dock", id),
  listOpenPopouts: () => ipcRenderer.invoke("miniapps:list-open"),
  toggleAlwaysOnTop: (id) => ipcRenderer.invoke("miniapps:popout-toggle-top", id),
  onPopoutClosed: (cb) => {
    const fn = (_e, id) => cb(id);
    ipcRenderer.on("miniapps:popout-closed", fn);
    return () => ipcRenderer.removeListener("miniapps:popout-closed", fn);
  },
});
