/* global chrome */

const COCHAV_HANOFESH_URL = 'https://cochav-hanofesh.com/?source=chrome_ext';
const DEFAULT_CONTEXT_MENU_ITEMS = [
  'email@gmail.com'
];
const DEFAULT_EMAIL_SUFFIXES = [
  'gmail.com',
  'outlook.com',
  'hotmail.com',
  'okmail.co.il',
  'enativ.com',
  'walla.co.il',
  'yahoo.com',
  'netvision.net.il',
  'bezeqint.net',
  '012.net.il'
];

// Initialize context menus when the extension is installed or updated
chrome.runtime.onInstalled.addListener(async () => {
  await saveDefaultOptions();
  await initializeContextMenus();
});

// Re-initialize context menus when Chrome starts up
chrome.runtime.onStartup.addListener(() => {
  initializeContextMenus();
});

async function initializeContextMenus () {
  try {
    await chrome.contextMenus.removeAll();
    const storage = await chrome.storage.sync.get('options');

    const contextMenuItems = (storage.options && storage.options.pasteEmailList)
      ? storage.options.pasteEmailList
      : DEFAULT_CONTEXT_MENU_ITEMS;

    if (!contextMenuItems || contextMenuItems.length === 0) {
      await setUpEmptyContextMenu();
      return;
    }

    for (const command of contextMenuItems) {
      if (command && command.trim()) {
        await chrome.contextMenus.create({
          id: `paste_${command}`, // Adding unique id
          title: command,
          contexts: ['editable']
        });
      }
    }

    await chrome.contextMenus.create({
      id: 'separator1',
      type: 'separator',
      contexts: ['editable']
    });

    await chrome.contextMenus.create({
      id: 'cochav_hanofesh',
      title: 'כוכב הנופש',
      contexts: ['editable']
    });
  } catch (error) {
    console.error('Error creating context menus:', error);
  }
}

// Listen for changes in storage and update context menus
chrome.storage.onChanged.addListener((changes, namespace) => {
  if (changes.options?.newValue?.pasteEmailList) {
    initializeContextMenus();
  }
});

function setUpEmptyContextMenu () {
  return Promise.all([
    chrome.contextMenus.create({
      id: 'separator_empty',
      type: 'separator',
      contexts: ['editable']
    }),
    chrome.contextMenus.create({
      id: 'empty_menu',
      title: 'ריק',
      enabled: false,
      contexts: ['editable']
    })
  ]);
}

function saveDefaultOptions () {
  return new Promise((resolve, reject) => {
    chrome.storage.sync.set({
      options: {
        pasteEmailList: DEFAULT_CONTEXT_MENU_ITEMS,
        autocompleteEmailList: DEFAULT_EMAIL_SUFFIXES
      }
    }, () => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError);
      } else {
        resolve();
      }
    });
  });
}

// Listen for context menu clicks
chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (!tab?.id) return;

  if (info.menuItemId === 'cochav_hanofesh') {
    chrome.tabs.create({ url: COCHAV_HANOFESH_URL, active: true });
  } else if (info.menuItemId.startsWith('paste_')) {
    const textToPaste = info.menuItemId.replace('paste_', '');
    chrome.tabs.sendMessage(tab.id, {
      action: 'paste',
      value: textToPaste
    }).catch(console.error);
  }
});
