const electron = require('electron');
if (typeof electron === 'string') {
  const { spawnSync } = require('child_process');
  const env = { ...process.env };
  delete env.ELECTRON_RUN_AS_NODE;
  const result = spawnSync(electron, process.argv.slice(1), { stdio: 'inherit', env });
  process.exit(result.status == null ? 0 : result.status);
}
const { BrowserWindow, Menu, Tray, ipcMain, screen } = electron;
const app = electron.app;
const path = require('path');
const fs = require('fs');

const runtimeAppDataDir = path.join(__dirname, '.appdata');
if (app && app.setPath) {
  if (!fs.existsSync(runtimeAppDataDir)) fs.mkdirSync(runtimeAppDataDir, { recursive: true });
  const runtimeSessionDir = path.join(runtimeAppDataDir, 'session');
  if (!fs.existsSync(runtimeSessionDir)) fs.mkdirSync(runtimeSessionDir, { recursive: true });
  app.setPath('appData', runtimeAppDataDir);
  app.setPath('userData', path.join(runtimeAppDataDir, app.getName()));
  app.setPath('sessionData', runtimeSessionDir);
}

let petWindow = null;
let panelWindow = null;
let tray = null;

// --- 本地账户存储（JSON 原子写） ---
const userDataDir = app.getPath ? app.getPath('userData') : path.join(__dirname, '.userdata');
const accountStorePath = path.join(userDataDir, 'accounts.json');

function ensureUserDataDir() {
  try {
    if (!fs.existsSync(userDataDir)) fs.mkdirSync(userDataDir, { recursive: true });
  } catch (e) {
    console.error('创建 userData 目录失败:', e);
  }
}

function loadStore() {
  try {
    if (!fs.existsSync(accountStorePath)) return { accounts: {}, session: { current: null } };
    const raw = fs.readFileSync(accountStorePath, 'utf8');
    return JSON.parse(raw || '{}');
  } catch (e) {
    console.error('读取账户存储失败:', e);
    return { accounts: {}, session: { current: null } };
  }
}

function saveStoreAtomic(store) {
  try {
    ensureUserDataDir();
    const tmp = accountStorePath + '.tmp';
    fs.writeFileSync(tmp, JSON.stringify(store, null, 2), 'utf8');
    fs.renameSync(tmp, accountStorePath);
  } catch (e) {
    console.error('保存账户存储失败:', e);
  }
}

// IPC: 账户相关
ipcMain.handle('account-login', (event, email) => {
  try {
    if (!email || typeof email !== 'string' || !email.includes('@')) {
      return { success: false, message: '请输入有效邮箱' };
    }
    const store = loadStore();
    if (!store.accounts) store.accounts = {};
    if (!store.accounts[email]) {
      store.accounts[email] = { balance: 1000, transactions: [] };
    }
    store.session = store.session || {};
    store.session.current = email;
    saveStoreAtomic(store);
    return { success: true, account: store.accounts[email], current: email };
  } catch (e) {
    console.error('account-login 失败:', e);
    return { success: false, message: String(e) };
  }
});

ipcMain.handle('account-logout', () => {
  try {
    const store = loadStore();
    store.session = store.session || {};
    store.session.current = null;
    saveStoreAtomic(store);
    return { success: true };
  } catch (e) {
    console.error('account-logout 失败:', e);
    return { success: false, message: String(e) };
  }
});

ipcMain.handle('account-get', () => {
  try {
    const store = loadStore();
    const current = store.session && store.session.current;
    const account = current ? (store.accounts && store.accounts[current]) : null;
    return { success: true, current: current || null, account };
  } catch (e) {
    console.error('account-get 失败:', e);
    return { success: false, message: String(e) };
  }
});

ipcMain.handle('account-debit', (event, amount, actionName) => {
  try {
    amount = Number(amount) || 0;
    const store = loadStore();
    const current = store.session && store.session.current;
    if (!current) return { success: false, code: 'NOT_LOGGED', message: '未登录' };
    const acct = store.accounts && store.accounts[current];
    if (!acct) return { success: false, code: 'NOT_FOUND', message: '账户不存在' };
    if (acct.balance < amount) return { success: false, code: 'INSUFFICIENT', message: '积分不足' };
    acct.balance = acct.balance - amount;
    acct.transactions = acct.transactions || [];
    acct.transactions.unshift({ time: new Date().toISOString(), action: actionName || 'action', amount: amount, balance: acct.balance });
    saveStoreAtomic(store);
    return { success: true, account: acct };
  } catch (e) {
    console.error('account-debit 失败:', e);
    return { success: false, message: String(e) };
  }
});

ipcMain.handle('account-transactions', (event, limit = 100) => {
  try {
    const store = loadStore();
    const current = store.session && store.session.current;
    const acct = current ? (store.accounts && store.accounts[current]) : null;
    return { success: true, transactions: acct ? (acct.transactions || []).slice(0, limit) : [] };
  } catch (e) {
    console.error('account-transactions 失败:', e);
    return { success: false, message: String(e) };
  }
});

// 创建桌宠窗口
function createPetWindow() {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize;
  
  petWindow = new BrowserWindow({
    width: 150,
    height: 150,
    frame: false,
    transparent: true,
    alwaysOnTop: true,
    skipTaskbar: true,
    resizable: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  });

  petWindow.loadFile('pet.html');
  petWindow.setIgnoreMouseEvents(false);
  
  // 设置初始位置在屏幕中央
  petWindow.setPosition(
    Math.floor(width / 2) - 75,
    Math.floor(height / 2) - 75
  );

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

// 创建主面板窗口
function createPanelWindow() {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize;
  
  // 严格按照要求设置位置和尺寸
  const panelWidth = 420;
  const panelHeight = Math.max(600, Math.floor(height * 0.75));
  const panelX = width - panelWidth - 16;
  const panelY = 80;
  
  panelWindow = new BrowserWindow({
    width: panelWidth,
    height: panelHeight,
    x: panelX,
    y: panelY,
    frame: true,
    transparent: false,
    alwaysOnTop: false,
    skipTaskbar: false,
    resizable: true,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  });

  // P0: 禁用原生菜单栏（Windows/Linux 会显示 File/Edit/...）
  try {
    panelWindow.setMenuBarVisibility(false);
    panelWindow.removeMenu();
  } catch (e) {
    console.error('禁用面板菜单栏失败:', e);
  }

  // DevTools 兜底入口：F12 或 Ctrl/Cmd+Shift+I
  try {
    panelWindow.webContents.on('before-input-event', (event, input) => {
      const isF12 = input.type === 'keyDown' && input.key === 'F12';
      const isCtrlShiftI =
        input.type === 'keyDown' &&
        (input.control || input.meta) &&
        input.shift &&
        (input.key === 'I' || input.key === 'i');

      if (isF12 || isCtrlShiftI) {
        event.preventDefault();
        if (panelWindow.webContents.isDevToolsOpened()) {
          panelWindow.webContents.closeDevTools();
        } else {
          panelWindow.webContents.openDevTools({ mode: 'detach' });
        }
      }
    });

    if (process.env.PANEL_DEVTOOLS === '1') {
      panelWindow.webContents.once('did-finish-load', () => {
        panelWindow.webContents.openDevTools({ mode: 'detach' });
      });
    }
  } catch (e) {
    console.error('DevTools 绑定失败:', e);
  }

  panelWindow.loadFile('panel.html');
  
  panelWindow.on('closed', () => {
    panelWindow = null;
  });
}

// 创建系统托盘
function createTray() {
  try {
    // 优先使用 tray.ico，兜底使用 tray.png
    let trayIconPath;
    const trayIcoPath = path.join(__dirname, 'assets', 'tray.ico');
    const trayPngPath = path.join(__dirname, 'assets', 'tray.png');
    
    // 检查文件是否存在且有效
    const fs = require('fs');
    try {
      if (fs.existsSync(trayIcoPath)) {
        const stats = fs.statSync(trayIcoPath);
        if (stats.size > 0) {
          trayIconPath = trayIcoPath;
        }
      }
      
      if (!trayIconPath && fs.existsSync(trayPngPath)) {
        const stats = fs.statSync(trayPngPath);
        if (stats.size > 0) {
          trayIconPath = trayPngPath;
        }
      }
    } catch (fsError) {
      console.error('检查图标文件失败:', fsError);
    }
    
    if (!trayIconPath) {
      console.error('未找到有效的托盘图标文件，跳过托盘创建');
      return;
    }
    
    // 尝试创建托盘，如果失败则跳过
    try {
      tray = new Tray(trayIconPath);
    } catch (trayError) {
      console.error('创建托盘图标失败，跳过托盘创建:', trayError);
      return;
    }
    
    const contextMenu = Menu.buildFromTemplate([
      {
        label: '显示面板',
        click: () => {
          if (!panelWindow) {
            createPanelWindow();
          } else {
            panelWindow.focus();
          }
        }
      },
      {
        label: '退出',
        click: () => {
          app.quit();
        }
      }
    ]);
    
    tray.setToolTip('桌面宠物');
    tray.setContextMenu(contextMenu);
  } catch (error) {
    console.error('创建托盘失败:', error);
    // 不抛出异常，继续运行应用
  }
}

// IPC 处理程序
ipcMain.handle('open-panel', () => {
  if (!panelWindow) {
    createPanelWindow();
  } else {
    panelWindow.focus();
  }
});

ipcMain.handle('move-pet', (event, deltaX, deltaY) => {
  if (petWindow) {
    const [currentX, currentY] = petWindow.getPosition();
    petWindow.setPosition(currentX + deltaX, currentY + deltaY);
  }
});

ipcMain.handle('quit-app', () => {
  app.quit();
});

// 应用程序就绪时创建窗口
app.whenReady().then(() => {
  createPetWindow();
  createTray();
  
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createPetWindow();
    }
  });
});

// 所有窗口关闭时退出应用（除了桌宠）
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// 防止多个实例
const gotTheLock = app.requestSingleInstanceLock();

if (!gotTheLock) {
  app.quit();
} else {
  app.on('second-instance', () => {
    // 当运行第二个实例时，将会聚焦到主窗口
    if (petWindow) {
      if (petWindow.isMinimized()) petWindow.restore();
      petWindow.focus();
    }
  });
}
