import { createIntegratedUi } from 'wxt/utils/content-script-ui/integrated';
import i18n from '@/plugins/i18n';
import { bridgeOpenPopupUrl } from '@/bridge/content/background';
import {
  SPY_BTN_BASE_STYLE,
  SPY_BTN_HOVER_STYLE,
  SPY_BTN_NORMAL_STYLE,
  SHOP_RESERVED_SEGMENTS,
  CONTENT_OPTIONS,
} from '@content/shopee/client/constant';

/**
 * @returns {string | null}
 */
const getShopUsername = () => {
  const match = window.location.pathname.match(/^\/([^/?#]+)\/?$/);

  if (!match) {
    return null;
  }

  const segment = match[1];

  if (SHOP_RESERVED_SEGMENTS.includes(segment)) {
    return null;
  }

  return segment;
};

/**
 * @returns {string | null}
 */
const getShopIdFromPage = () => {
  try {
    const nextData = window.__NEXT_DATA__;
    if (nextData && nextData.props && nextData.props.pageProps) {
      const shopId = nextData.props.pageProps.shopId || nextData.props.pageProps.shop_id;
      if (shopId) {
        return String(shopId);
      }
    }
  } catch (e) {
    // ignore
  }

  return null;
};

export class ShopSpyBtnLoader {
  /**
   * @param {import('wxt/utils/content-script-context').ContentScriptContext} ctx
   */
  constructor(ctx) {
    this.ctx = ctx;
    this.currentUsername = null;
    this.ui = null;
  }

  removeBtn() {
    if (this.ui) {
      this.ui.remove();
      this.ui = null;
    }
  }

  appendBtn(username) {
    if (!CONTENT_OPTIONS.floatSpyShopBtn) {
      return;
    }

    if (this.ui) {
      return;
    }

    this.ui = createIntegratedUi(this.ctx, {
      position: 'overlay',
      zIndex: 9999,
      onMount(container) {
        const btn = document.createElement('button');
        btn.innerHTML = `<span style="font-size:14px;margin-right:6px">🏪</span><span>${i18n.t('SPY_SHOP_BTN')}</span>`;

        Object.assign(btn.style, SPY_BTN_BASE_STYLE, { fontSize: '13px', fontWeight: '600' });

        btn.addEventListener('mouseenter', () => {
          Object.assign(btn.style, SPY_BTN_HOVER_STYLE);
        });

        btn.addEventListener('mouseleave', () => {
          Object.assign(btn.style, SPY_BTN_NORMAL_STYLE);
        });

        btn.addEventListener('click', () => {
          const shopId = getShopIdFromPage();

          if (shopId) {
            bridgeOpenPopupUrl({ path: `/shopee/spy/shop/${shopId}` });
            return;
          }

          bridgeOpenPopupUrl({
            path: '/shopee/spy/shop/by-username',
            qs: { username },
          });
        });

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

    this.ui.mount();
  }

  initialize() {
    const username = getShopUsername();

    if (!username) {
      this.removeBtn();
      this.currentUsername = null;
      return;
    }

    if (username !== this.currentUsername) {
      this.removeBtn();
      this.currentUsername = username;
    }

    this.appendBtn(username);
  }
}
