const { app, BrowserWindow, protocol, net } = require('electron');
const path = require('path');
const fs = require('fs');
const { pathToFileURL } = require('url');

// Deve ser chamado antes de app.ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true, supportFetchAPI: true } }
]);

app.commandLine.appendSwitch('no-proxy-server');
app.commandLine.appendSwitch('enable-gpu-rasterization');
app.commandLine.appendSwitch('enable-zero-copy');
app.commandLine.appendSwitch('ignore-gpu-blocklist');

function createWindow() {
  const win = new BrowserWindow({
    width: 1280,
    height: 800,
    show: true, // (Esconde ou mostra o processo de carregamento)
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  });

  win.setMenuBarVisibility(false);
  win.maximize();

  if (!app.isPackaged) {
    win.loadURL('http://localhost:5173');
  } else {
    win.loadURL('app://localhost/');
  }

  win.once('ready-to-show', () => {
    win.show();
  });
}

app.whenReady().then(() => {
  if (app.isPackaged) {
    const distPath = path.join(__dirname, 'dist');

    protocol.handle('app', (request) => {
      const url = new URL(request.url);
      const filePath = path.join(distPath, url.pathname);

      // Se o arquivo exato existir, serve ele
      if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
        return net.fetch(pathToFileURL(filePath).href);
      }

      // Caso contrário, serve index.html (rotas do React Router)
      return net.fetch(pathToFileURL(path.join(distPath, 'index.html')).href);
    });
  }

  createWindow();

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

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