import { bridgeOpenPopupUrl } from '@/bridge/content/background';
import i18n from '@/plugins/i18n';
import { getCurrentUrl } from '@/lib/content';
import { appendNextNode } from '@content/service/util';

const elementAdsCampaignId = {
  btnBase: '#app > div.full-screen-container > div.module-page-detail > button.eds-button--normal',
  buttonId: 'autoshopee-btn-ads-campagin-id',
};

const addButtonAds = async (element, campaignId) => {
  const baseBtn = document.querySelector(element.btnBase);

  if (!baseBtn) {
    return null;
  }

  const button = baseBtn.cloneNode(true);
  button.innerHTML = i18n.t('BTN_ADS_CAMPAGIN_OPEN');
  button.id = element.buttonId;

  button.style.background = '#ee4d2d';
  button.style['border-color'] = '#ee4d2d';
  button.style.color = '#fff';

  button.addEventListener('click', async () => {
    bridgeOpenPopupUrl({
      path: `/shopee/seller/ads/${campaignId}`,
      qs: {},
    });
  });

  appendNextNode(baseBtn, button);

  return button;
};

export const loadCampaignId = async () => {
  const url = getCurrentUrl();
  const matchCampaignId = url.match(/marketing\/pas\/(.*?)\/(\d*?)\?from/);

  if (!(matchCampaignId && matchCampaignId[2])) {
    return false;
  }

  const campaignId = matchCampaignId[2];
  if (document.querySelector(elementAdsCampaignId.btnBase) && !document.querySelector(`#${elementAdsCampaignId.buttonId}`)) {
    addButtonAds(elementAdsCampaignId, campaignId);
  }
};
