const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');

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

let mainWindow;
let childWindow = null;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 460,
    height: 460,
    resizable: false,
    frame: false,
    icon: path.join(__dirname, 'launcher_icon.ico'),
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: false
    }
  });

  mainWindow.loadFile('index.html');
  mainWindow.setMenuBarVisibility(false);
  // mainWindow.webContents.openDevTools(); // ← デバッグ用（必要に応じて）
  mainWindow.on('closed', () => { mainWindow = null; });
}

app.whenReady().then(createWindow);

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

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

// ✅ ウィンドウ制御系イベント
ipcMain.on('window-minimize', (event) => {
  const win = BrowserWindow.fromWebContents(event.sender);
  if (win && !win.isDestroyed()) win.minimize();
});

ipcMain.on('window-maximize', (event) => {
  const win = BrowserWindow.fromWebContents(event.sender);
  if (win && !win.isDestroyed()) {
    if (win.isMaximized()) {
      win.unmaximize();
    } else {
      win.maximize();
    }
  }
});

ipcMain.on('window-close', (event) => {
  const win = BrowserWindow.fromWebContents(event.sender);
  if (win && !win.isDestroyed()) win.close();
});

// ✅ 「さよなら」トリガー → レンダラーへ通知
ipcMain.on('say-bye', (event) => {
  const win = BrowserWindow.fromWebContents(event.sender);
  if (win && !win.isDestroyed()) {
    win.webContents.send('say-bye');
  }
});

// ✅ 子ウィンドウ処理
ipcMain.on('open-child-window', (event, { url, label, icon }) => {
  if (childWindow && !childWindow.isDestroyed()) {
    childWindow.webContents.send('set-url', { url, label, icon });
    childWindow.focus();
    return;
  }

  childWindow = new BrowserWindow({
    width: 800,
    height: 600,
    frame: false,
    icon: path.join(__dirname, 'launcher_icon.ico'),
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: false,
      webviewTag: true
    },
  });

  childWindow.loadFile('child.html');

  childWindow.webContents.once('did-finish-load', () => {
    childWindow.webContents.send('set-url', { url, label, icon });
  });

  childWindow.on('closed', () => {
    childWindow = null;
  });
});

// ✅ 🔊 ボタン押下時の音声を再生
ipcMain.on('play-button-voice', (event, filename) => {
  const win = BrowserWindow.fromWebContents(event.sender);
  if (!win || win.isDestroyed()) return;

  const audioUrl = `http://busyuka.mydns.jp:6500/FFXI/launcher/audio/${filename}`;

  win.webContents.executeJavaScript(`
    try {
      const audio = new Audio('${audioUrl}');
      audio.volume = 0.8;
      audio.play().catch(err => console.warn('🔇 ボタン音声エラー:', err));
    } catch (e) {
      console.error('🔇 JS再生エラー:', e);
    }
  `);
});
