// Biz Connect — technician desktop client (Electron main process).
//
// This is a thin shell: it loads the live Connect web UI from the server origin, so every
// relative /api and /ws URL in the web app keeps working unchanged. What it adds over a
// browser tab:
//   - native full-screen capture for "Share Screen" (setDisplayMediaRequestHandler)
//   - a real desktop window (no browser chrome), persisted login session
//   - external links open in the user's browser, not inside the app
//
// Server origin is configurable so the same build works against prod or a dev server.
const { app, BrowserWindow, session, desktopCapturer, shell, Menu, ipcMain, nativeImage, Notification } = require('electron');
const path = require('path');
const fs = require('fs');
const os = require('os');
const crypto = require('crypto');

// A stable per-install id (persisted in userData), so the server can count installs and
// associate them with the user who signs in. Created once, then reused across launches.
function getInstallId() {
  try {
    const p = path.join(app.getPath('userData'), 'install-id');
    if (fs.existsSync(p)) { const v = fs.readFileSync(p, 'utf8').trim(); if (v) return v; }
    const id = crypto.randomUUID();
    fs.writeFileSync(p, id);
    return id;
  } catch (_) { return 'unknown'; }
}
// The renderer (web app) reads this synchronously to report telemetry after login.
ipcMain.on('get-install-info', (e) => {
  e.returnValue = { installId: getInstallId(), appVersion: app.getVersion(), os: process.platform + ' ' + os.release() };
});
// Auto-update: only NATIVE shell changes (this .exe) need this — all web/UI changes arrive
// live from the server. Checks the self-hosted feed (publish config in package.json →
// https://remote.bizgaze.com/downloads/latest.yml), downloads in the background, and installs
// on the next restart. No-op in dev (unpackaged).
let autoUpdater = null;
try { ({ autoUpdater } = require('electron-updater')); } catch (_) { /* not installed in dev */ }
// #12: manual "Check for updates" from Settings. Returns the current status; the background updater
// (configured in app.whenReady) downloads and prompts to restart when a build is ready.
ipcMain.handle('check-updates', async () => {
  const current = app.getVersion();
  if (!app.isPackaged || !autoUpdater) return { status: 'dev', current };
  try {
    const r = await autoUpdater.checkForUpdates();
    const v = r && r.updateInfo && r.updateInfo.version;
    return (v && v !== current) ? { status: 'available', version: v, current } : { status: 'current', current };
  } catch (e) { return { status: 'error', message: String((e && e.message) || e), current }; }
});
// #3: restart-and-install, triggered from the web update banner's "Restart" button.
ipcMain.handle('restart-to-update', () => { try { if (autoUpdater) autoUpdater.quitAndInstall(); } catch (_) {} });
// Chat toast: sender/group avatar + message; clicking it raises the app and opens that chat.
// Uses Electron's OWN Notification (native, no SnoreToast) whose 'click' event fires reliably.
const APP_ID = 'com.bizgaze.connect.desktop';

// Resolve the sender/group avatar to a local temp PNG for the toast icon. Accepts either a data:
// URL (legacy) or an http(s) DP URL, which we download (external photos can't be drawn to a canvas
// in the renderer without tainting it, so the renderer now passes the URL straight through).
function tmpPngPath() { return path.join(app.getPath('temp'), 'bizc-toast-' + crypto.randomBytes(4).toString('hex') + '.png'); }
function avatarToTempPng(src) {
  return new Promise((resolve) => {
    try {
      if (!src) return resolve(null);
      if (/^data:image\/png;base64,/.test(src)) { const p = tmpPngPath(); fs.writeFileSync(p, Buffer.from(src.split(',')[1], 'base64')); return resolve(p); }
      if (/^https?:\/\//i.test(src)) {
        const mod = src.startsWith('https') ? require('https') : require('http');
        const p = tmpPngPath(); const file = fs.createWriteStream(p);
        const req = mod.get(src, (res) => {
          if (res.statusCode !== 200) { res.resume(); file.close(() => { try { fs.unlinkSync(p); } catch (_) {} }); return resolve(null); }
          res.pipe(file); file.on('finish', () => file.close(() => resolve(p)));
        });
        req.on('error', () => resolve(null));
        req.setTimeout(2500, () => { try { req.destroy(); } catch (_) {} resolve(null); });
        return;
      }
      resolve(null);
    } catch (_) { resolve(null); }
  });
}

// Keep STRONG references to live notifications. Electron/Windows garbage-collects a Notification
// with no reference, which closed the toast within ~1s and made clicks do nothing.
const activeNotifs = new Set();

// Resolves {open} when the toast is clicked (renderer then opens that chat), else null.
ipcMain.handle('reply-notification', async (_e, payload = {}) => {
  if (!Notification.isSupported()) return null;
  // Do NOT block the toast on the avatar download (that made desktop notifications lag ~15s vs the
  // browser's instant one). Race it against a short cap: use the DP only if it's ready fast.
  const img = await Promise.race([
    avatarToTempPng(payload.avatar),
    new Promise((r) => setTimeout(() => r(null), 600)),
  ]);
  return await new Promise((resolve) => {
    let done = false;
    let n;
    const finish = (v) => {
      if (done) return; done = true;
      if (n) { activeNotifs.delete(n); }
      if (img) { try { fs.unlinkSync(img); } catch (_) {} }
      resolve(v);
    };
    try {
      n = new Notification({
        title: payload.title || 'Biz Connect',
        body: payload.body || '',
        icon: img ? nativeImage.createFromPath(img) : undefined,
        silent: false,
        // A call invite stays on screen until clicked/ended; a chat toast uses the default timeout.
        timeoutType: payload.persistent ? 'never' : 'default',
      });
      activeNotifs.add(n); // strong ref → toast isn't collected; click stays live
      n.on('click', () => {
        if (win) { if (win.isMinimized()) win.restore(); win.show(); win.focus(); } // raise the app
        finish({ kind: payload.kind, id: payload.id, open: true });
      });
      n.on('close', () => finish(null)); // user/system dismissed it → no action (don't force-close)
      n.show();
      // Safety timeout so the promise never leaks. Calls get the full ring window; chats shorter.
      setTimeout(() => { try { if (n) n.close(); } catch (_) {} finish(null); }, payload.persistent ? 45000 : 25000);
    } catch (_) { finish(null); }
  });
});

// Windows attributes notifications to the AppUserModelID. Without setting it, toasts read
// "electron.app.<name>"; setting it to the installer's appId makes Windows resolve the
// installed "Biz Connect" shortcut, so notifications show "Biz Connect".
app.setAppUserModelId('com.bizgaze.connect.desktop');

// Renderer asks (via preload) to raise the window — e.g. when an OS notification is clicked.
ipcMain.on('focus-window', () => {
  if (!win) return;
  if (win.isMinimized()) win.restore();
  win.show();
  win.focus();
});

// Unread badge on the taskbar icon. The renderer computes the count (chats with unread) and
// draws the badge image (it has a canvas); Windows shows it via an overlay icon, macOS/Linux
// via the dock badge count.
ipcMain.on('set-unread', (_e, { count, dataUrl } = {}) => {
  try {
    if (typeof app.setBadgeCount === 'function') app.setBadgeCount(count || 0); // macOS/Linux dock
    if (!win) return;
    const overlay = (count > 0 && dataUrl) ? nativeImage.createFromDataURL(dataUrl) : null;
    win.setOverlayIcon(overlay, count > 0 ? (count + ' unread chats') : ''); // Windows taskbar
  } catch (_) {}
});

// Server origin: a PACKAGED build (the installer) points at production; running from source in dev
// (`npm start`, unpackaged) defaults to the local server so you can test the shell against localhost
// with no flags or separate "local" build. SERVER_URL always overrides (e.g. point dev at prod).
const SERVER_URL = (process.env.SERVER_URL || (app.isPackaged ? 'https://remote.bizgaze.com' : 'http://localhost:8090')).replace(/\/+$/, '');

let win;
let splash;

// A tiny brand-blue splash (splash.html) shown while the web UI loads, so launch feels instant
// and on-brand instead of a blank window. Closed as soon as the main window is ready to show.
function createSplash() {
  splash = new BrowserWindow({
    width: 440, height: 440, frame: false, resizable: false, center: true,
    backgroundColor: '#1F3B73', skipTaskbar: true, alwaysOnTop: true, show: true,
    webPreferences: { contextIsolation: true, nodeIntegration: false },
  });
  splash.loadFile(path.join(__dirname, 'splash.html'));
  splash.on('closed', () => { splash = null; });
}
function closeSplash() { if (splash) { try { splash.close(); } catch (_) {} splash = null; } }

function createWindow() {
  win = new BrowserWindow({
    width: 1200,
    height: 800,
    minWidth: 880,
    minHeight: 600,
    title: 'Biz Connect',
    backgroundColor: '#1F3B73',
    show: false, // reveal only once the page is ready — the splash covers the gap
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false,
      // Persist cookies/localStorage so the technician stays logged in between launches.
      partition: 'persist:bizconnect',
    },
  });

  // Reveal the main window when its first paint is ready, and retire the splash. A fallback
  // timer guarantees we never get stuck on the splash if the load stalls.
  const reveal = () => { closeSplash(); if (win && !win.isVisible()) { win.show(); win.focus(); } };
  win.once('ready-to-show', reveal);
  setTimeout(reveal, 12000);

  // Open the landing page (same entry as the website): the "before login" screen with the
  // no-login "Share my screen" option + sign-in. It redirects logged-in users straight to /home.
  win.loadURL(SERVER_URL + '/');

  // Open target=_blank / external links in the system browser instead of a new Electron window.
  win.webContents.setWindowOpenHandler(({ url }) => {
    if (!url.startsWith(SERVER_URL)) { shell.openExternal(url); return { action: 'deny' }; }
    return { action: 'allow' };
  });
}

// The full Connect experience needs several web capabilities that Electron denies by
// default. We grant them for our own trusted origin:
//   - media            → camera + mic for meetings/calls (getUserMedia)
//   - display-capture  → "Share my screen" (getDisplayMedia)
//   - notifications    → in-app alerts
//   - clipboard, fullscreen, pointerLock → chat paste + meeting UX
// Without this, meetings silently have no camera/mic and notifications never fire.
const GRANTED = new Set([
  'media', 'display-capture', 'notifications',
  'clipboard-read', 'clipboard-sanitized-write', 'fullscreen', 'pointerLock',
]);

function configureSession() {
  const ses = session.fromPartition('persist:bizconnect');
  // getDisplayMedia: prefer the OS's native screen/window PICKER (Windows 11 / macOS) so the user
  // chooses what to share (and can pick a single window, avoiding the whole-screen mirror). If the
  // system picker isn't available, this handler falls back to auto-selecting the primary display.
  ses.setDisplayMediaRequestHandler((request, callback) => {
    desktopCapturer.getSources({ types: ['screen', 'window'] }).then((sources) => {
      callback(sources.length ? { video: sources[0], audio: 'loopback' } : {});
    }).catch(() => callback({}));
  }, { useSystemPicker: true });
  // Async grant (getUserMedia, notifications, …)
  ses.setPermissionRequestHandler((_wc, permission, callback) => callback(GRANTED.has(permission)));
  // Sync check (some getUserMedia paths query this before requesting)
  ses.setPermissionCheckHandler((_wc, permission) => GRANTED.has(permission));
}

app.whenReady().then(() => {
  configureSession();
  createSplash();
  createWindow();
  Menu.setApplicationMenu(null); // hide the default menu bar; the web UI is the chrome
  app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); });
  // Check for shell updates on launch, then every 6 hours. Only in packaged builds.
  if (app.isPackaged && autoUpdater) {
    // #3: surface update progress to the web UI so the user can SEE an update is downloading /
    // installing, instead of it happening silently in the background.
    const sendUpdate = (data) => { try { if (win && !win.isDestroyed()) win.webContents.send('update-event', data); } catch (_) {} };
    autoUpdater.on('checking-for-update', () => sendUpdate({ phase: 'checking' }));
    autoUpdater.on('update-available', (info) => sendUpdate({ phase: 'available', version: info && info.version }));
    autoUpdater.on('update-not-available', () => sendUpdate({ phase: 'current' }));
    autoUpdater.on('download-progress', (p) => sendUpdate({ phase: 'downloading', percent: Math.round((p && p.percent) || 0) }));
    autoUpdater.on('error', () => sendUpdate({ phase: 'error' }));
    // When an update finishes downloading (auto or via the Settings "Check for updates"), offer a
    // clear restart prompt instead of only the silent on-next-launch install.
    let promptedForUpdate = false;
    autoUpdater.on('update-downloaded', async (info) => {
      sendUpdate({ phase: 'ready', version: info && info.version });
      if (promptedForUpdate) return; promptedForUpdate = true;
      try {
        const { dialog } = require('electron');
        const res = await dialog.showMessageBox(win || undefined, {
          type: 'info', buttons: ['Restart now', 'Later'], defaultId: 0, cancelId: 1,
          title: 'Update ready', message: 'Biz Connect ' + ((info && info.version) || '') + ' is ready.',
          detail: 'Restart the app to finish updating.',
        });
        if (res.response === 0) autoUpdater.quitAndInstall();
      } catch (_) { /* fall back to install-on-next-launch */ }
    });
    const check = () => autoUpdater.checkForUpdatesAndNotify().catch(() => {});
    check();
    setInterval(check, 6 * 60 * 60 * 1000);
  }
});

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