const RECENT_ITEMS_KEY = 'recentItems';
const BLOCKED_ROOT_HOSTS = new Set([
  'facebook.com',
  'www.facebook.com',
  'm.facebook.com',
  'instagram.com',
  'www.instagram.com',
  'tiktok.com',
  'www.tiktok.com'
]);

async function getActiveTab() {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  return tab;
}

function qs(id) {
  return document.getElementById(id);
}

function isSupportedUrl(url) {
  try {
    const parsed = new URL(url);
    if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
      return false;
    }

    const path = parsed.pathname.replace(/\/+$/, '');
    const isRootPage = (path === '' || path === '/') && !parsed.search && !parsed.hash;

    return !isRootPage;
  } catch (_error) {
    return false;
  }
}

async function sendAction(type, payload) {
  const response = await chrome.runtime.sendMessage({ type, payload });
  if (!response?.ok) {
    throw new Error(response?.error || 'MeetMic action failed');
  }
  return response;
}

async function loadHistory() {
  const { [RECENT_ITEMS_KEY]: items = [] } = await chrome.storage.local.get(RECENT_ITEMS_KEY);
  const list = qs('history-list');
  const empty = qs('history-empty');
  list.innerHTML = '';

  if (!items.length) {
    empty.hidden = false;
    return;
  }

  empty.hidden = true;

  for (const item of items) {
    const li = document.createElement('li');
    li.className = 'history-item';
    const meta = document.createElement('div');
    meta.className = 'history-item__meta';
    const title = document.createElement('div');
    title.className = 'history-item__title';
    title.textContent = item.title;
    const detail = document.createElement('div');
    meta.append(title, detail);

    const action = document.createElement('button');
    action.className = 'history-item__action';
    action.textContent = 'Again';
    action.disabled = !isSupportedUrl(item.url);
    action.addEventListener('click', async () => {
      if (action.disabled) {
        return;
      }
      await sendAction('meetmic:openSource', item);
    });

    li.append(meta, action);
    list.append(li);
  }
}

async function main() {
  const tab = await getActiveTab();
  const sendPageButton = qs('send-page');

  sendPageButton.disabled = !isSupportedUrl(tab?.url);

  sendPageButton.addEventListener('click', async () => {
    if (sendPageButton.disabled) {
      return;
    }

    await sendAction('meetmic:openSource', {
      url: tab.url,
      title: tab.title || tab.url,
      domain: new URL(tab.url).hostname,
      sourceKind: 'page',
      pageTitle: tab.title || tab.url,
      pageUrl: tab.url
    });
    await loadHistory();
  });

  qs('clear-history').addEventListener('click', async () => {
    await chrome.storage.local.set({ [RECENT_ITEMS_KEY]: [] });
    await loadHistory();
  });

  qs('open-site').addEventListener('click', async () => {
    await chrome.runtime.sendMessage({ type: 'meetmic:openWebsite' });
  });

  await loadHistory();
}

main().catch((error) => {
  console.error(error);
});
