import queryString from 'query-string';
import { createIntegratedUi } from 'wxt/utils/content-script-ui/integrated';
import { bridgeOpenPopupUrl } from '@/bridge/content/background';
import i18n from '@/plugins/i18n';

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

  if (!urlQuery.job_id) {
    return;
  }

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

  const ui = createIntegratedUi(ctx, {
    position: 'overlay',
    zIndex: 9999,
    onMount(container) {
      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;
      `;

      buttonPrinter.addEventListener('click', () => bridgeOpenPopupUrl({
        path: '/printer/index',
        qs: { jobId, from, shopId },
      }));

      container.append(buttonPrinter);
    },
  });

  ui.mount();
};

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