import i18n from '@/plugins/i18n';
import { bridgeOpenPopupUrl } from '@/bridge/content/background';
import {
  ELEMENT_IDS,
  SPY_BTN_BASE_STYLE,
  SPY_BTN_HOVER_STYLE,
  SPY_BTN_NORMAL_STYLE,
  SHOP_RESERVED_SEGMENTS,
  CONTENT_OPTIONS,
} from '@content/shopee/client/constant';

const BTN_ID = ELEMENT_IDS.SPY_SHOP_BTN;

/**
 * @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 {
  constructor() {
    this.currentUsername = null;
  }

  removeBtn() {
    const existing = document.querySelector(`#${BTN_ID}`);
    if (existing) {
      existing.remove();
    }
  }

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

    if (document.querySelector(`#${BTN_ID}`)) {
      return;
    }

    const btn = document.createElement('button');
    btn.id = BTN_ID;
    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 },
      });
    });

    document.body.append(btn);
  }

  initialize() {
    const username = getShopUsername();

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

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

    this.appendBtn(username);
  }
}
