const { app, BrowserWindow, ipcMain, shell, Menu, safeStorage, session } = require("electron");
const path = require("path");
const fs = require("fs");
const tef = require("./tef.cjs");

// ===== Mini-apps (WhatsApp, Gmail, etc.) =====
const DEFAULT_MINIAPPS = [
  { id: "whatsapp", nome: "WhatsApp", url: "https://web.whatsapp.com", icone: "💬" },
  { id: "gmail", nome: "Gmail", url: "https://mail.google.com", icone: "✉️" },
];
function miniappsFilePath() {
  return path.join(app.getPath("userData"), "miniapps.json");
}
function readMiniapps() {
  try {
    const p = miniappsFilePath();
    if (!fs.existsSync(p)) return DEFAULT_MINIAPPS.slice();
    const arr = JSON.parse(fs.readFileSync(p, "utf-8"));
    if (Array.isArray(arr)) return arr;
    return DEFAULT_MINIAPPS.slice();
  } catch (_) { return DEFAULT_MINIAPPS.slice(); }
}
function writeMiniapps(list) {
  try {
    fs.writeFileSync(miniappsFilePath(), JSON.stringify(list, null, 2));
    return true;
  } catch (_) { return false; }
}

// Janelas pop-out ativas por id de mini-app
const popoutWindows = new Map();
// Sessions já configuradas para conceder notificações
const configuredSessions = new Set();
function ensureMiniappSession(id) {
  const part = `persist:miniapp-${id}`;
  if (configuredSessions.has(part)) return part;
  configuredSessions.add(part);
  try {
    const s = session.fromPartition(part);
    s.setPermissionRequestHandler((_wc, permission, cb) => {
      const allowed = ["notifications", "media", "clipboard-read", "clipboard-sanitized-write", "fullscreen"];
      cb(allowed.includes(permission));
    });
    // User-Agent de Chrome desktop para evitar bloqueio (WhatsApp Web)
    s.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36");
  } catch (_) {}
  return part;
}

// ===== Credenciais salvas (criptografadas com safeStorage / DPAPI no Windows) =====
function credsFilePath() {
  return path.join(app.getPath("userData"), "luxos-creds.bin");
}
function readSavedCreds() {
  try {
    const p = credsFilePath();
    if (!fs.existsSync(p)) return null;
    if (!safeStorage.isEncryptionAvailable()) return null;
    const buf = fs.readFileSync(p);
    const json = safeStorage.decryptString(buf);
    const obj = JSON.parse(json);
    if (obj && typeof obj.usuario === "string" && typeof obj.senha === "string") return obj;
    return null;
  } catch (_) { return null; }
}
function writeSavedCreds(usuario, senha) {
  if (!safeStorage.isEncryptionAvailable()) return false;
  const enc = safeStorage.encryptString(JSON.stringify({ usuario, senha }));
  fs.writeFileSync(credsFilePath(), enc);
  return true;
}
function clearSavedCreds() {
  try { fs.unlinkSync(credsFilePath()); } catch (_) {}
  return true;
}


const PDV_URL = "https://sistema.dca3.com.br/v3/PDV";

let mainWindow = null;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1280,
    height: 800,
    minWidth: 1024,
    minHeight: 700,
    show: false,
    backgroundColor: "#1a0b06",
    title: "Luxos D'Cacau — PDV",
    icon: path.join(__dirname, "icon.ico"),
    webPreferences: {
      preload: path.join(__dirname, "preload.cjs"),
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: false,
      webviewTag: true,
    },
  });

  Menu.setApplicationMenu(null);

  mainWindow.loadFile(path.join(__dirname, "splash.html"));


  mainWindow.once("ready-to-show", () => {
    mainWindow.maximize();
    mainWindow.show();
  });

  // Links externos (target=_blank) abrem no navegador padrão
  mainWindow.webContents.setWindowOpenHandler(({ url }) => {
    if (url.startsWith(PDV_URL) || url.startsWith("https://sistema.dca3.com.br")) {
      return { action: "allow" };
    }
    shell.openExternal(url);
    return { action: "deny" };
  });
}

// ===== IPC =====
ipcMain.handle("tef:check", async () => {
  return await tef.checkRunning();
});

ipcMain.handle("tef:ensure", async () => {
  return await tef.ensureRunning();
});

ipcMain.handle("pdv:open", async (_e, url) => {
  if (mainWindow) {
    const target = typeof url === "string" && url ? url : "https://sistema.dca3.com.br/v3/PDV";
    await mainWindow.loadFile(path.join(__dirname, "shell.html"), {
      query: { url: target },
    });
  }
  return true;
});


ipcMain.handle("app:goSplash", async () => {
  if (mainWindow) {
    await mainWindow.loadFile(path.join(__dirname, "splash.html"));
  }
  return true;
});

ipcMain.handle("app:toggleFullscreen", () => {
  if (mainWindow) {
    mainWindow.setFullScreen(!mainWindow.isFullScreen());
    return mainWindow.isFullScreen();
  }
  return false;
});

ipcMain.handle("app:quit", () => {
  app.quit();
});

ipcMain.handle("config:get", () => {
  const cfgPath = tef.ensureConfigFile();
  return { path: cfgPath };
});

ipcMain.handle("config:open", async () => {
  const cfgPath = tef.ensureConfigFile();
  if (cfgPath) {
    await shell.openPath(cfgPath);
    return true;
  }
  return false;
});

// ===== Credenciais =====
ipcMain.handle("creds:get", () => readSavedCreds());
ipcMain.handle("creds:save", (_e, payload) => {
  if (!payload || typeof payload.usuario !== "string" || typeof payload.senha !== "string") return false;
  if (!payload.usuario || !payload.senha) return false;
  try { return writeSavedCreds(payload.usuario, payload.senha); }
  catch (_) { return false; }
});
ipcMain.handle("creds:clear", () => clearSavedCreds());
ipcMain.handle("creds:has", () => Boolean(readSavedCreds()));

// ===== Mini-apps IPC =====
ipcMain.handle("miniapps:list", () => readMiniapps());
ipcMain.handle("miniapps:save", (_e, list) => {
  if (!Array.isArray(list)) return false;
  // Sanitiza
  const clean = list
    .filter((x) => x && typeof x.id === "string" && typeof x.url === "string" && typeof x.nome === "string")
    .map((x) => ({
      id: String(x.id).slice(0, 40).replace(/[^a-z0-9_-]/gi, "-"),
      nome: String(x.nome).slice(0, 40),
      url: String(x.url).slice(0, 500),
      icone: typeof x.icone === "string" ? String(x.icone).slice(0, 6) : "🔗",
    }));
  return writeMiniapps(clean);
});
ipcMain.handle("miniapps:ensure-session", (_e, id) => ensureMiniappSession(String(id || "default")));
ipcMain.handle("miniapps:list-open", () => Array.from(popoutWindows.keys()));
ipcMain.handle("miniapps:popout", (_e, payload) => {
  if (!payload || !payload.id || !payload.url) return false;
  const id = String(payload.id);
  // Se já existe, foca
  const existing = popoutWindows.get(id);
  if (existing && !existing.isDestroyed()) {
    existing.show(); existing.focus();
    return true;
  }
  const part = ensureMiniappSession(id);
  const bounds = payload.bounds || {};
  const win = new BrowserWindow({
    width: Math.max(360, Number(bounds.width) || 420),
    height: Math.max(420, Number(bounds.height) || 720),
    x: typeof bounds.x === "number" ? bounds.x : undefined,
    y: typeof bounds.y === "number" ? bounds.y : undefined,
    alwaysOnTop: true,
    frame: false,
    resizable: true,
    skipTaskbar: false,
    backgroundColor: "#1a0b06",
    title: payload.nome || "App",
    icon: path.join(__dirname, "icon.ico"),
    webPreferences: {
      preload: path.join(__dirname, "preload.cjs"),
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: false,
      webviewTag: true,
    },
  });
  win.setMenu(null);
  win.loadFile(path.join(__dirname, "popout.html"), {
    query: {
      id,
      url: payload.url,
      nome: payload.nome || "App",
      icone: payload.icone || "🔗",
      partition: part,
    },
  });
  popoutWindows.set(id, win);
  win.on("closed", () => {
    popoutWindows.delete(id);
    if (mainWindow && !mainWindow.isDestroyed()) {
      mainWindow.webContents.send("miniapps:popout-closed", id);
    }
  });
  return true;
});
ipcMain.handle("miniapps:dock", (_e, id) => {
  const w = popoutWindows.get(String(id));
  if (w && !w.isDestroyed()) w.close();
  return true;
});
ipcMain.handle("miniapps:popout-toggle-top", (_e, id) => {
  const w = popoutWindows.get(String(id));
  if (!w || w.isDestroyed()) return false;
  const next = !w.isAlwaysOnTop();
  w.setAlwaysOnTop(next);
  return next;
});


// Atalhos globais úteis
app.whenReady().then(() => {
  try { tef.ensureConfigFile(); } catch (_) {}
  createWindow();

  const { globalShortcut } = require("electron");
  // F11 = tela cheia
  globalShortcut.register("F11", () => {
    if (mainWindow) mainWindow.setFullScreen(!mainWindow.isFullScreen());
  });
  // Ctrl+Shift+H = volta para splash
  globalShortcut.register("CommandOrControl+Shift+H", () => {
    if (mainWindow) mainWindow.loadFile(path.join(__dirname, "splash.html"));
  });
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") app.quit();
});

app.on("activate", () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
