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

let mainWindow;
let childWindow = null;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 460,
    height: 600,
    resizable: false,
    frame: false,
    icon: path.join(__dirname, '../launcher/images/EggTarutaru.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-close', (event) => {
  const win = BrowserWindow.fromWebContents(event.sender);
  if (win && !win.isDestroyed()) win.close();
});

ipcMain.on('open-child-window', (event, { url, label }) => {
  if (childWindow && !childWindow.isDestroyed()) {
    childWindow.webContents.send('set-url', { url, label }); // ✅ 再利用時にURLだけ送る
    childWindow.focus();
    return;
  }

  childWindow = new BrowserWindow({
    width: 800,
    height: 600,
    frame: false, // ✅ カスタムUIなので false にする
    icon: path.join(__dirname, '../launcher/images/EggTarutaru.ico'),
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: false,
      webviewTag: true
    },
  });

  childWindow.loadFile('child.html'); // ✅ HTMLベースのカスタムUIを使用

  childWindow.webContents.once('did-finish-load', () => {
    childWindow.webContents.send('set-url', { url, label }); // ✅ 初回読み込み時にデータ送信
    childWindow.webContents.openDevTools();
  });

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