const { app, BrowserWindow, Menu, dialog, shell, session } = require('electron');
const path = require('path');

app.disableHardwareAcceleration();
app.commandLine.appendSwitch('disable-features', 'CalculateNativeWinOcclusion');
app.commandLine.appendSwitch('autoplay-policy', 'no-user-gesture-required');

const SITE = 'https://ratzonorchestra.com';
const VERSION = 'v1.78A';
const START_PATH = '/sheets/pdfreader/';

let mainWin = null;

function createWindow() {
  // Persistent session
  const persistSession = session.fromPartition('persist:jgmt-178a');

  // Mic permission auto-allow for the JG sites (asks user via prompt only when site requests it)
  persistSession.setPermissionRequestHandler((webContents, permission, callback) => {
    if (permission === 'media' || permission === 'microphone' || permission === 'midi' || permission === 'midiSysex') {
      callback(true);
    } else {
      callback(false);
    }
  });

  mainWin = new BrowserWindow({
    width: 1280, height: 860, minWidth: 720, minHeight: 480,
    backgroundColor: '#0a0a0a',
    title: 'JG Music Tools ' + VERSION,
    icon: path.join(__dirname, 'icon.ico'),
    show: false,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: true,
      session: persistSession,
      partition: 'persist:jgmt-178a',
    },
  });

  mainWin.loadURL(SITE + START_PATH);
  mainWin.once('ready-to-show', () => mainWin.show());

  mainWin.webContents.setWindowOpenHandler(({ url }) => {
    shell.openExternal(url);
    return { action: 'deny' };
  });

  buildMenu();
}

function buildMenu() {
  Menu.setApplicationMenu(Menu.buildFromTemplate([
    { label: 'File', submenu: [
      { label: 'Home', accelerator: 'Ctrl+H', click: () => mainWin && mainWin.loadURL(SITE + START_PATH) },
      { label: 'Sign out', click: async () => {
        const s = session.fromPartition('persist:jgmt-178a');
        await s.clearStorageData();
        mainWin && mainWin.loadURL(SITE + START_PATH);
      }},
      { type: 'separator' },
      { label: 'Quit', accelerator: 'Ctrl+Q', role: 'quit' },
    ]},
    { label: 'Tools', submenu: [
      { label: '📖 PDF Reader',  click: () => mainWin && mainWin.loadURL(SITE + '/sheets/pdfreader/') },
      { label: '🎯 Tuner',       click: () => mainWin && mainWin.loadURL(SITE + '/sheets/tuner/') },
      { label: '🎙 Recorder',    click: () => mainWin && mainWin.loadURL(SITE + '/sheets/recorder/') },
      { label: '🎹 Keyboard',    click: () => mainWin && mainWin.loadURL(SITE + '/sheets/keyboard/') },
      { label: '🎵 Transposer',  click: () => mainWin && mainWin.loadURL(SITE + '/sheets/transpose.php') },
      { type: 'separator' },
      { label: '📡 Live Broadcast', click: () => mainWin && mainWin.loadURL(SITE + '/sheets/live/') },
      { label: '🎼 Sheet Library',  click: () => mainWin && mainWin.loadURL(SITE + '/sheets/') },
    ]},
    { label: 'View', submenu: [
      { role: 'reload', accelerator: 'Ctrl+R' },
      { label: 'Hard reload', accelerator: 'Ctrl+Shift+R', click: () => mainWin && mainWin.webContents.reloadIgnoringCache() },
      { type: 'separator' },
      { role: 'togglefullscreen' },
      { role: 'zoomIn' }, { role: 'zoomOut' }, { role: 'resetZoom' },
      { type: 'separator' },
      { label: 'Always on top', type: 'checkbox', accelerator: 'Ctrl+T',
        click: (item) => mainWin && mainWin.setAlwaysOnTop(item.checked, 'screen-saver') },
      { type: 'separator' },
      { role: 'toggleDevTools', accelerator: 'F12' },
    ]},
    { label: 'Help', submenu: [
      { label: 'About JG Music Tools', click: () => dialog.showMessageBox({
        type: 'info', title: 'About',
        message: 'JG Music Tools ' + VERSION,
        detail: 'Universal music tools — PDF reader, tuner, DAW recorder, keyboard with 8 free synth sounds + Web MIDI, live broadcast.\n\nWindows portable build. Stays signed in across launches.\n\nratzonorchestra.com'
      })},
      { label: 'Open website', click: () => shell.openExternal(SITE + START_PATH) },
    ]},
  ]));
}

app.whenReady().then(createWindow);
app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); });
app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); });
