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

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

let mainWindow;
let childWindow = null;

const userDataPath = app.getPath('userData');
const mainWindowConfigPath = path.join(userDataPath, 'main_window.json');
const childWindowConfigPath = path.join(userDataPath, 'child_window.json');

// ✅ JSON 保存／読込
function saveWindowBounds(win, filepath) {
  if (!win || win.isDestroyed() || win.isMinimized() || win.isMaximized()) return;
  const bounds = win.getBounds();
  fs.writeFileSync(filepath, JSON.stringify(bounds, null, 2));
}

function loadWindowBounds(filepath, defaults) {
  try {
    const data = fs.readFileSync(filepath, 'utf8');
    return { ...defaults, ...JSON.parse(data) };
  } catch {
    return defaults;
  }
}

// ✅ メインウィンドウ作成
function createWindow() {
  const bounds = loadWindowBounds(mainWindowConfigPath, {
    width: 460,
    height: 460
  });

  mainWindow = new BrowserWindow({
    ...bounds,
    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.on('close', () => {
    if (childWindow && !childWindow.isDestroyed()) {
      childWindow.close();
    }
    saveWindowBounds(mainWindow, mainWindowConfigPath);
  });

  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()) {
    win.isMaximized() ? win.unmaximize() : 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;
  }

  const mainBounds = mainWindow.getBounds();
  const display = screen.getDisplayMatching(mainBounds).workArea;

  const defaultX = Math.min(
    Math.max(mainBounds.x + mainBounds.width + 10, display.x),
    display.x + display.width - 800
  );

  const bounds = loadWindowBounds(childWindowConfigPath, {
    width: 800,
    height: 600,
    x: defaultX,
    y: mainBounds.y
  });

  childWindow = new BrowserWindow({
    ...bounds,
    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('close', () => saveWindowBounds(childWindow, childWindowConfigPath));
  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}?_=${Date.now()}`;

  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);
    }
  `);
});

// 🔊 起動時のあいさつボイス再生用（レンダラーで実行）
ipcMain.on('play-greeting', (event, zone) => {
  const win = BrowserWindow.fromWebContents(event.sender);
  if (win && !win.isDestroyed()) {
    win.webContents.send('play-greeting', zone);
  }
});

