// main.js - Electron's Main Process Script

const { app, BrowserWindow, screen, Menu, ipcMain } = require("electron");
const path = require("path");
const fs = require("fs");
const Store = require('electron-store');

// --- Initialize Settings Store ---
const store = new Store();

// --- Font Handling ---
const fontsPath = path.join(__dirname, 'fonts');
let availableFonts = [];
try {
  availableFonts = fs.readdirSync(fontsPath).filter(file => file.endsWith('.otf') || file.endsWith('.ttf'));
} catch (error) {
  console.error("Could not read fonts directory.", error);
}

// --- Default State for First Launch ---
const defaultState = {
  x: undefined,
  y: undefined,
  scale: 1.0,
  color: '#FFC0CB',
  opacity: 1.0,
  font: 'Anurati-Regular.otf',
  visibility: { day: true, date: true, time: true }
};

// Load saved state or use defaults
let widgetState = store.get('widgetState', defaultState);

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    x: widgetState.x,
    y: widgetState.y,
    width: 800,
    height: 450,
    transparent: true,
    frame: false,
    alwaysOnTop: false,
    skipTaskbar: true,
    focusable: true,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
    },
  });

  mainWindow.loadFile(path.join(__dirname, "index.html"));

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.webContents.send('initialize-settings', widgetState);
  });
  
  mainWindow.on("closed", () => { mainWindow = null; });
}

// IPC listener to save any setting change immediately
ipcMain.on('save-setting', (event, { key, value }) => {
  const keys = key.split('.');
  let current = widgetState;
  for (let i = 0; i < keys.length - 1; i++) {
    current = current[keys[i]];
  }
  current[keys[keys.length - 1]] = value;
  
  store.set('widgetState', widgetState);
});

// Manual dragging logic
ipcMain.on('move-window', (event, { deltaX, deltaY }) => {
  if (mainWindow) {
    const [x, y] = mainWindow.getPosition();
    mainWindow.setPosition(x + deltaX, y + deltaY);
  }
});

// Save position at the end of a drag
ipcMain.on('drag-end', () => {
  if (mainWindow) {
    const [x, y] = mainWindow.getPosition();
    widgetState.x = x;
    widgetState.y = y;
    store.set('widgetState', widgetState);
  }
});

// Click-through logic
ipcMain.on('set-interactive', () => { if (mainWindow) mainWindow.setIgnoreMouseEvents(false); });
ipcMain.on('set-click-through', () => { if (mainWindow) mainWindow.setIgnoreMouseEvents(true, { forward: true }); });

// Context Menu
ipcMain.on('show-context-menu', (event) => {
  const fontSubmenu = availableFonts.map(fontFile => ({
    label: fontFile.replace(/\.(otf|ttf)$/, ''),
    type: 'radio',
    checked: widgetState.font === fontFile,
    click: () => event.sender.send('change-setting', { key: 'font', value: fontFile })
  }));

  const opacitySubmenu = Array.from({ length: 10 }, (_, i) => {
    const opacityValue = (i + 1) / 10;
    return {
      label: `${(i + 1) * 10}%`,
      type: 'radio',
      checked: Math.abs(widgetState.opacity - opacityValue) < 0.01,
      click: () => event.sender.send('change-setting', { key: 'opacity', value: opacityValue })
    };
  }).reverse();

  // --- THIS IS THE FIX ---
  // Count how many elements are currently visible.
  const visibleCount = Object.values(widgetState.visibility).filter(v => v === true).length;

  const toggleSubmenu = [
    {
      label: 'Day',
      type: 'checkbox',
      checked: widgetState.visibility.day,
      // Disable this item if it's currently visible AND it's the last one left.
      enabled: !(widgetState.visibility.day && visibleCount === 1),
      click: (menuItem) => event.sender.send('change-setting', {key: 'visibility.day', value: menuItem.checked})
    },
    {
      label: 'Date',
      type: 'checkbox',
      checked: widgetState.visibility.date,
      enabled: !(widgetState.visibility.date && visibleCount === 1),
      click: (menuItem) => event.sender.send('change-setting', {key: 'visibility.date', value: menuItem.checked})
    },
    {
      label: 'Time',
      type: 'checkbox',
      checked: widgetState.visibility.time,
      enabled: !(widgetState.visibility.time && visibleCount === 1),
      click: (menuItem) => event.sender.send('change-setting', {key: 'visibility.time', value: menuItem.checked})
    },
  ];
  // --- END OF FIX ---

  const template = [
    { label: 'Scale', submenu: [
        { label: 'Small (80%)', type: 'radio', checked: widgetState.scale === 0.8, click: () => event.sender.send('change-setting', {key: 'scale', value: 0.8})},
        { label: 'Medium (100%)', type: 'radio', checked: widgetState.scale === 1.0, click: () => event.sender.send('change-setting', {key: 'scale', value: 1.0})},
        { label: 'Large (120%)', type: 'radio', checked: widgetState.scale === 1.2, click: () => event.sender.send('change-setting', {key: 'scale', value: 1.2})},
    ] },
    { label: 'Font', submenu: fontSubmenu.length > 0 ? fontSubmenu : [{ label: 'No fonts found', enabled: false }] },
    { label: 'Color', click: () => event.sender.send('pick-color') },
    { label: 'Opacity', submenu: opacitySubmenu },
    { type: 'separator' },
    { label: 'Toggle Elements', submenu: toggleSubmenu }, // Use the new submenu with the logic
    { type: 'separator' },
    { label: 'Quit Clock', role: 'quit' },
  ];
  
  const menu = Menu.buildFromTemplate(template);
  menu.popup({ window: mainWindow });
});

app.disableHardwareAcceleration();
app.whenReady().then(createWindow);
app.on("window-all-closed", () => { if (process.platform !== "darwin") app.quit(); });
app.on("activate", () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); });