chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: 'optimize-image',
    title: 'Optimize with ImageLite',
    contexts: ['image']
  });
});

chrome.contextMenus.onClicked.addListener(async (info) => {
  if (info.menuItemId !== 'optimize-image' || !info.srcUrl) return;

  try {
    const response = await fetch(info.srcUrl);
    const blob = await response.blob();
    const reader = new FileReader();

    reader.onload = () => {
      chrome.storage.local.set({
        pendingClipboardImage: reader.result,
        pendingClipboardType: blob.type,
        pendingClipboardName: filenameFromUrl(info.srcUrl, blob.type)
      }, async () => {
        await showPopupHint();
      });
    };

    reader.readAsDataURL(blob);
  } catch (error) {
    console.error('Failed to fetch image:', error);
  }
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'openWorkspace') {
    showPopupHint().then(() => sendResponse({ success: true }));
    return true;
  }

  if (message.action === 'openToolWindow') {
    openOverlayOrToolWindow(message.options || {}).then(sendResponse);
    return true;
  }

  if (message.action === 'resizeToolWindow') {
    resizeToolWindow(sender.tab?.windowId, message.expanded).then(sendResponse);
    return true;
  }

  if (message.action === 'returnToActionPopup') {
    returnToActionPopup(sender.tab?.windowId).then(sendResponse);
    return true;
  }

  return false;
});

async function showPopupHint() {
  if (chrome.action.openPopup) {
    try {
      await chrome.action.openPopup();
      return { success: true };
    } catch (error) {
      // Some browsers only allow opening the popup for direct extension gestures.
    }
  }

  chrome.action.setBadgeText({ text: '1' });
  chrome.action.setBadgeBackgroundColor({ color: '#7c5cfc' });
  chrome.action.setTitle({ title: 'ImageLite - image ready in popup' });
  return { success: false, fallback: 'badge' };
}

async function openToolWindow(options = {}) {
  const url = chrome.runtime.getURL('popup.html?window=1');
  const width = options.expanded === false ? 460 : 940;
  const height = options.expanded === false ? 680 : 780;
  const placement = getWindowPlacement(width, height, options.screen);

  await chrome.storage.local.set({
    imageliteWindowState: {
      locked: true,
      expanded: options.expanded !== false
    }
  });

  const existing = await chrome.storage.local.get('imageliteToolWindowId');
  if (existing.imageliteToolWindowId) {
    try {
      await chrome.windows.update(existing.imageliteToolWindowId, {
        focused: true,
        width,
        height,
        ...placement
      });
      return { success: true, focusedExisting: true };
    } catch (error) {
      await chrome.storage.local.remove('imageliteToolWindowId');
    }
  }

  try {
    const created = await chrome.windows.create({
      url,
      type: 'popup',
      width,
      height,
      ...placement,
      focused: true
    });
    if (created?.id) {
      await chrome.storage.local.set({ imageliteToolWindowId: created.id });
    }
    return { success: true };
  } catch (error) {
    console.error('Failed to open ImageLite tool window:', error);
    return { success: false, error: error.message };
  }
}

async function openOverlayOrToolWindow(options = {}) {
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (tab?.id && tab.url && !/^chrome|^edge|^opera|^about|^moz-extension|^chrome-extension/.test(tab.url)) {
      const response = await chrome.tabs.sendMessage(tab.id, {
        action: 'openImageLiteOverlay',
        expanded: options.expanded !== false
      });
      if (response?.success) return { success: true, mode: 'overlay' };
    }
  } catch (error) {
    // Restricted pages or unloaded content scripts fall back to a normal extension window.
  }

  return openToolWindow(options);
}

async function resizeToolWindow(windowId, expanded) {
  if (!windowId) return { success: false, error: 'Missing window id' };
  const width = expanded ? 940 : 460;
  const height = expanded ? 780 : 680;

  try {
    await chrome.windows.update(windowId, {
      width,
      height,
      focused: true
    });
    return { success: true };
  } catch (error) {
    return { success: false, error: error.message };
  }
}

async function returnToActionPopup(windowId) {
  const opened = await showPopupHint();
  if (!opened?.success) {
    return opened;
  }

  if (windowId) {
    try {
      await chrome.storage.local.remove('imageliteToolWindowId');
      await chrome.windows.remove(windowId);
    } catch (error) {
      // If the window already closed, the action popup is still the desired state.
    }
  }

  return { success: true };
}

function getWindowPlacement(width, height, screenInfo) {
  if (!screenInfo?.availWidth || !screenInfo?.availHeight) return {};
  return {
    left: Math.max(0, Math.round(((screenInfo.availLeft || 0) + (screenInfo.availWidth - width) / 2))),
    top: Math.max(0, Math.round(((screenInfo.availTop || 0) + (screenInfo.availHeight - height) / 2)))
  };
}

chrome.windows.onRemoved.addListener((windowId) => {
  chrome.storage.local.get('imageliteToolWindowId', (result) => {
    if (result.imageliteToolWindowId === windowId) {
      chrome.storage.local.remove('imageliteToolWindowId');
    }
  });
});

function filenameFromUrl(url, type) {
  try {
    const pathname = new URL(url).pathname;
    const rawName = pathname.split('/').pop();
    if (rawName) return decodeURIComponent(rawName).split('?')[0];
  } catch (error) {
    // Fall through to a type-based filename.
  }

  const ext = type?.split('/')[1] || 'png';
  return `image.${ext}`;
}
