const { contextBridge, ipcRenderer } = require('electron');
const fs = require('fs');
const path = require('path');
const os = require('os');

const userDataPath = path.join(os.homedir(), 'AppData', 'Roaming', 'ぶぅたんのねごと');
const settingsPath = path.join(userDataPath, 'settings.json');
const boundsPath = path.join(userDataPath, 'child_window.json');

contextBridge.exposeInMainWorld('electronAPI', {
  minimize: () => ipcRenderer.send('window-minimize'),
  maximize: () => ipcRenderer.send('window-maximize'),
  close: () => ipcRenderer.send('window-close'),
  openChildWindow: (data) => ipcRenderer.send('open-child-window', data),

  onSetUrl: (callback) => ipcRenderer.on('set-url', (event, data) => callback(data)),

  getMessageUrl: () => 'http://busyuka.mydns.jp:6500/FFXI/launcher/message.json',

  getUserDataPath: () => userDataPath,

  saveFile: (filePath, content) => {
    try {
      const dir = path.dirname(filePath);
      if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
      fs.writeFileSync(filePath, content, 'utf8');
    } catch (e) {
      console.error('[saveFile] ファイル保存エラー:', e);
    }
  },

  readJsonFile: (filePath) => {
    try {
      return JSON.parse(fs.readFileSync(filePath, 'utf8'));
    } catch {
      return null;
    }
  },

  getSettings: () => {
    try {
      return JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
    } catch {
      return {};
    }
  },

  saveSettings: (settings) => {
    try {
      if (!fs.existsSync(userDataPath)) fs.mkdirSync(userDataPath, { recursive: true });
      fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2), 'utf8');
    } catch (e) {
      console.error('[saveSettings] 設定保存エラー:', e);
    }
  },

  playButtonVoice: (filename) => {
    try {
      const setting = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
      if (setting.voice === false) return;
    } catch {}
    ipcRenderer.send('play-button-voice', filename);
  },

  playGreeting: (zone) => {
    ipcRenderer.send('play-greeting', zone);
  },

  sayByeByeMofu: () => {
    ipcRenderer.send('say-bye');
  },

  onSayBye: (callback) => {
    ipcRenderer.on('say-bye', () => callback());
  },

  // ✅ 子ウィンドウ位置とサイズの保存と読み込み
  saveChildWindowBounds: (bounds) => {
    try {
      if (!fs.existsSync(userDataPath)) fs.mkdirSync(userDataPath, { recursive: true });
      fs.writeFileSync(boundsPath, JSON.stringify(bounds, null, 2), 'utf8');
    } catch (e) {
      console.error('[saveChildWindowBounds] 保存エラー:', e);
    }
  },

  loadChildWindowBounds: () => {
    try {
      return JSON.parse(fs.readFileSync(boundsPath, 'utf8'));
    } catch {
      return null;
    }
  }
});
