import queryString from 'query-string';
import { bridgeOpenPopupUrl } from '@/bridge/content/background';
import i18n from '@/plugins/i18n';

const createFloatButton = () => {
  const urlQuery = queryString.parseUrl(window.location.href).query;

  if (!urlQuery.job_id) {
    return false;
  }

  const buttonPrinter = document.createElement('button');
  buttonPrinter.innerHTML = [
    '<span class="shopee-seller-iconfont seller-icon-print"></span>',
    i18n.t('SESSION_PRINT_OPEN_BTN'),
  ].join(' ');

  buttonPrinter.style.cssText = `
    position: fixed;
    bottom: 20px;
    right: 50px;
    border-radius: 5px;
    background: #ee4d2d;
    color: white;
    border: none;
    cursor: pointer;
    padding: 10px;
    z-index: 9999;
  `;

  const jobId = urlQuery.job_id;
  const shopId = urlQuery.shop_id;
  const from = 'shopee';

  const onClick = () => bridgeOpenPopupUrl({
    path: '/printer/index',
    qs: {
      jobId,
      from,
      shopId,
    },
  });

  buttonPrinter.addEventListener('click', onClick);

  document.body.appendChild(buttonPrinter);
};

export function main(ctx) {
  if (document.readyState === 'complete') {
    createFloatButton();
  } else {
    ctx.addEventListener(window, 'load', createFloatButton);
  }
}
