import i18n from '@/plugins/i18n';
import { bridgeShopeeGetAffiliateChatMesage } from '@/bridge/content/background';
import { setInputNative } from '@content/service/util';
import { loggerContent } from '@/plugins/logger';

const elementChat = {
  input: '#root > div > div > div > div > div > div > div > div > div > div > div > div > textarea',
};

const elementAffiliate = {
  trackedId: 'autoshopee_aff_link',
  root: 'div.shopee-react-checkbox-group > div > section > div > div > div > div > div.be6wBntJmR',
  productId: 'div.d_8Rgdw7m7 > label > input.shopee-react-checkbox__input',
  productName: 'div.ROwxwn1s2L > div > div',
  parent: 'div.NSGsJzUkfg',
  baseBtn: 'div.b5PN3ddbxd',
};

const massAffLink = async () => {
  const listElement = [...document.querySelectorAll(elementAffiliate.root)];

  if (!listElement.length) {
    return false;
  }

  listElement.forEach((root) => {
    try {
      if (!root.querySelector(`#${elementAffiliate.trackedId}`)) {
        const partent = root.querySelector(elementAffiliate.parent);
        const productIdEl = root.querySelector(elementAffiliate.productId);
        const productNameEl = root.querySelector(elementAffiliate.productName);
        const baseBtnEl = root.querySelector(elementAffiliate.baseBtn);

        if (!(partent && productIdEl && productNameEl && baseBtnEl)) {
          return;
        }

        const productId = productIdEl.getAttribute('value');
        const productName = productNameEl.getAttribute('title');
        const elementAdd = baseBtnEl.cloneNode();

        partent.append(elementAdd);
        elementAdd.id = elementAffiliate.trackedId;
        elementAdd.addEventListener('click', async () => {
          setInputNative(document.querySelector(elementChat.input), `${i18n.t('PROCESSING_STATUS')}...`);
          bridgeShopeeGetAffiliateChatMesage({ id: productId, name: productName }).then((data) => {
            setInputNative(document.querySelector(elementChat.input), data);
          });
        });
        elementAdd.innerHTML = i18n.t('SHOPEE_AFFILIATE_BTN');
      }
    } catch (error) {
      loggerContent.error({
        msg: 'AFF_SHORT_LINK_ERROR',
        error,
      });
    }
  });
};

export function main(ctx) {
  ctx.setInterval(() => {
    massAffLink();
  }, 500);
}
