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

const appendButtonUrl = async ({
  id, text, url, node, color, bg,
}) => {
  if (!(!document.getElementById(id) && document.querySelector(node))) {
    return false;
  }

  const buttonAdd = document.createElement('button');
  buttonAdd.innerHTML = text;
  buttonAdd.id = id;
  buttonAdd.type = 'button';
  buttonAdd.style.cursor = 'pointer';
  buttonAdd.style.color = color;
  buttonAdd.style.background = bg;

  buttonAdd.style.borderRadius = '5px';
  buttonAdd.style.margin = '5px';
  buttonAdd.style.padding = '5px';

  const onClick = () => {
    return bridgeOpenPopupUrl({
      path: url,
      qs: {},
    });
  };

  buttonAdd.addEventListener('click', onClick);

  appendNextNode(document.querySelector(node), buttonAdd);

  return buttonAdd;
};

export const addBtnLoader = async () => {
  const url = getCurrentUrl();

  const { useBetaMode } = await getSettingApp();

  if (url.includes('/portal/settings/shop/rating')) {
    const buttonReplyRating = {
      id: 'reply-rating',
      text: i18n.t('SHOPEE_AUTO_REPLY_RATING'),
      url: '/shopee/seller/auto/reply-rating',
      node: 'div.page-container > div > div > div > div.bg-white.shadow-card > span',
      color: '#fff',
      bg: 'rgb(60 0 177',
    };

    appendButtonUrl(buttonReplyRating);
  }

  if (url.includes('/portal/sale/order')) {
    const buttonReplyRating = {
      id: 'rating-order',
      text: i18n.t('SHOPEE_AUTO_RATING_ORDER'),
      url: '/shopee/seller/auto/rating-order',
      node: 'div.page.fulfillment-order > div > div > div.order-list > div > div.result-count-wrapper',
      color: '#fff',
      bg: 'rgb(60 0 177',
    };

    appendButtonUrl(buttonReplyRating);
  }

  if (useBetaMode) {
    if (url.includes('/portal/product/list')) {
      const buttonReplyRating = {
        id: 'product-manager',
        text: i18n.t('SHOPEE_PRODUCT_MANAGER'),
        url: '/shopee/seller/product/manager',
        node: '#app > div.app-container > div.page-container.responsive-container.has-sidebar-panel > div > div > div > div > div > div.list-page-header',
        color: '#fff',
        bg: 'rgb(60 0 177',
      };

      appendButtonUrl(buttonReplyRating);
    }
  }
};
