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

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: () => path.join(os.homedir(), 'AppData', 'Roaming', 'ぶぅたんのねごと'),

  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;
    }
  },

  playGreeting: (zone) => {
    const fileMap = {
      '朝': 'greeting_ohayou.mp3',
      '昼': 'greeting_konnichiwa.mp3',
      'おやつ': 'greeting_snack.mp3',
      '夕方': 'greeting_evening.mp3',
      '夜': 'greeting_konbanwa.mp3',
      '深夜': 'greeting_Late_Night.mp3'
    };
    const filename = fileMap[zone];
    if (!filename) return;
    const audioPath = `http://busyuka.mydns.jp:6500/FFXI/launcher/audio/${filename}`;
    const audio = new Audio(audioPath);
    audio.play().catch(e => console.error('🔈 音声再生エラー:', e));
  },

  getSettings: () => {
    try {
      const settingsPath = path.join(os.homedir(), 'AppData', 'Roaming', 'ぶぅたんのねごと', 'settings.json');
      return JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
    } catch {
      return {};
    }
  },

  playButtonVoice: (filename) => {
    try {
      const setting = JSON.parse(fs.readFileSync(
        path.join(os.homedir(), 'AppData', 'Roaming', 'ぶぅたんのねごと', 'settings.json'),
        'utf8'
      ));
      if (setting.voice === false) return;
    } catch {}
    const audioPath = `http://busyuka.mydns.jp:6500/FFXI/launcher/audio/${filename}`;
    const audio = new Audio(audioPath);
    audio.volume = 0.8;
    audio.play().catch(err => console.error('🔈 ボタン音声エラー:', err));
  },

  sayByeByeMofu: () => {
    const setting = JSON.parse(fs.readFileSync(
      path.join(os.homedir(), 'AppData', 'Roaming', 'ぶぅたんのねごと', 'settings.json'),
      'utf8'
    ));
    if (setting.voice === false) {
      ipcRenderer.send('window-close');
      return;
    }

    const audio = new Audio('http://busyuka.mydns.jp:6500/FFXI/launcher/audio/bye_mofu.mp3');
    audio.volume = 0.8;

    audio.onended = () => ipcRenderer.send('window-close');
    audio.onerror = () => setTimeout(() => ipcRenderer.send('window-close'), 1000);
    audio.play().catch(() => setTimeout(() => ipcRenderer.send('window-close'), 1000));
  },

  saveSettings: (settings) => {
    try {
      const dir = path.join(os.homedir(), 'AppData', 'Roaming', 'ぶぅたんのねごと');
      if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
      fs.writeFileSync(path.join(dir, 'settings.json'), JSON.stringify(settings, null, 2), 'utf8');
    } catch (e) {
      console.error('[saveSettings] 設定保存エラー:', e);
    }
  }
});
