const RECENT_ITEMS_KEY = 'recentItems';
const MAX_RECENT_ITEMS = 8;

function normalizeUrl(url) {
  try {
    const parsed = new URL(url);

    if (parsed.hostname.includes('youtube.com') || parsed.hostname === 'youtu.be') {
      const videoId = parsed.searchParams.get('v') || (parsed.hostname === 'youtu.be' ? parsed.pathname.replace('/', '') : '');
      if (videoId) {
        return `https://www.youtube.com/watch?v=${videoId}`;
      }
    }

    parsed.hash = '';
    ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'feature', 'si'].forEach((key) => {
      parsed.searchParams.delete(key);
    });
    return parsed.toString();
  } catch (_error) {
    return url;
  }
}

function buildActionUrl(url) {
  let actionUrl = `quickwhisper://open?url=${encodeURI(url)}`;
  actionUrl = actionUrl.replaceAll('&', '%26');
  actionUrl = actionUrl.replaceAll('#', '%23');
  return actionUrl;
}

async function rememberRecentItem(item) {
  const storage = await chrome.storage.local.get(RECENT_ITEMS_KEY);
  const recentItems = storage[RECENT_ITEMS_KEY] || [];
  const normalizedUrl = normalizeUrl(item.url);
  const deduped = recentItems.filter((entry) => entry.url !== normalizedUrl);
  deduped.unshift({
    ...item,
    url: normalizedUrl,
    savedAt: new Date().toISOString()
  });
  await chrome.storage.local.set({
    [RECENT_ITEMS_KEY]: deduped.slice(0, MAX_RECENT_ITEMS)
  });
}

async function openLinkInQuickWhisper(url, options = {}) {
  if (!url || (!url.startsWith('https://') && !url.startsWith('http://'))) {
    return { ok: false, error: 'Unsupported URL' };
  }

  const normalizedUrl = normalizeUrl(url);
  await rememberRecentItem({
    url: normalizedUrl,
    title: options.title || normalizedUrl,
    domain: options.domain || new URL(normalizedUrl).hostname,
    sourceKind: options.sourceKind || 'page',
    pageTitle: options.pageTitle || options.title || normalizedUrl,
    pageUrl: options.pageUrl || normalizedUrl
  });
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  await chrome.tabs.update(tab.id, {
    url: buildActionUrl(normalizedUrl)
  });
  return { ok: true };
}

function openQuickWhisperWebsite() {
  return chrome.tabs.create({ url: 'https://quickwhisper.app' });
}

function createContextMenus() {
  const items = [
    {
      id: 'open-in-quickwhisper-send-page',
      title: 'Send page to QuickWhisper',
      contexts: ['page']
    },
    {
      id: 'open-in-quickwhisper-send-link',
      title: 'Send link to QuickWhisper',
      contexts: ['link']
    },
    {
      id: 'open-in-quickwhisper-send-audio',
      title: 'Send audio to QuickWhisper',
      contexts: ['audio']
    },
    {
      id: 'open-in-quickwhisper-send-video',
      title: 'Send video to QuickWhisper',
      contexts: ['video']
    }
  ];

  for (const item of items) {
    chrome.contextMenus.create(item);
  }
}

chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.removeAll(() => {
    createContextMenus();
  });
});

chrome.contextMenus.onClicked.addListener(async (info, tab) => {
  const sourceUrl = info.linkUrl || info.srcUrl || tab?.url;
  const title = tab?.title || sourceUrl;
  const domain = sourceUrl ? new URL(sourceUrl).hostname : '';
  const sourceKind = info.menuItemId.includes('audio') ? 'audio' : info.menuItemId.includes('video') ? 'video' : info.linkUrl ? 'link' : 'page';

  if (info.menuItemId.startsWith('open-in-quickwhisper-send')) {
    await openLinkInQuickWhisper(sourceUrl, {
      title,
      domain,
      sourceKind,
      pageTitle: tab?.title || title,
      pageUrl: tab?.url || sourceUrl
    });
  }
});

chrome.commands.onCommand.addListener(async (command) => {
  if (command === 'XUOpenCurrentSite') {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (tab?.url) {
      await openLinkInQuickWhisper(tab.url, {
        title: tab.title || tab.url,
        domain: new URL(tab.url).hostname,
        sourceKind: 'page',
        pageTitle: tab.title || tab.url,
        pageUrl: tab.url
      });
    }
  }
});

chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
  if (message?.type === 'quickwhisper:openSource') {
    openLinkInQuickWhisper(message.payload?.url, message.payload)
      .then(sendResponse)
      .catch((error) => sendResponse({ ok: false, error: error.message }));
    return true;
  }

  if (message?.type === 'quickwhisper:openWebsite') {
    openQuickWhisperWebsite()
      .then(() => sendResponse({ ok: true }))
      .catch((error) => sendResponse({ ok: false, error: error.message }));
    return true;
  }

  return false;
});
