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 button = document.querySelector(element.btnBase).cloneNode(true);
  button.innerHTML = i18n.t('BTN_ADS_CAMPAGIN_OPEN');
  button.id = element.buttonId;

  button.style.background = 'rgb(60 0 177)';
  button.style['border-color'] = 'rgb(60 0 177)';
  button.style.color = '#fff';

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

  appendNextNode(document.querySelector(element.btnBase), 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.parent) && !document.querySelector(`#${elementAdsCampaignId.buttonId}`)) {
    addButtonAds(elementAdsCampaignId, campaignId);
  }
};
