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

const urlParams = new URLSearchParams(window.location.search);
const initialURL = urlParams.get('url') || '';

contextBridge.exposeInMainWorld('electronAPI', {
  initialURL: initialURL,  // ここで渡す

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

  readMessageFile: () => {
    const filePath = path.join(__dirname, 'message.txt');
    try {
      return fs.readFileSync(filePath, 'utf8');
    } catch {
      return null;
    }
  },

  getUserDataPath: () => {
    return path.join(os.homedir(), 'AppData', 'Roaming', 'ぶぅたんのねごと');
  },

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

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

contextBridge.exposeInMainWorld('ipcRenderer', ipcRenderer);

