import i18n from '@/plugins/i18n';
import { bridgeOpenPopupUrl } from '@/bridge/content/background';

const BTN_ID = 'autoshopee_spy_shop_btn';

const RESERVED_SEGMENTS = [
  'search', 'buyer', 'cart', 'account', 'chat', 'order',
  'product', 'mall', 'voucher', 'blog', 'help',
];

const getButtonStyle = () => ({
  position: 'fixed',
  right: '16px',
  top: '50%',
  transform: 'translateY(-50%)',
  zIndex: '9999',
  display: 'flex',
  flexDirection: 'row',
  alignItems: 'center',
  justifyContent: 'center',
  padding: '10px 18px',
  color: '#fff',
  background: 'linear-gradient(135deg, #3c00b1 0%, #7c3aed 100%)',
  borderRadius: '24px',
  cursor: 'pointer',
  border: '2px solid rgba(255,255,255,0.2)',
  boxShadow: '0 4px 14px rgba(60,0,177,0.55)',
  transition: 'all 0.2s ease',
  whiteSpace: 'nowrap',
  fontSize: '13px',
  fontWeight: '600',
});

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

  if (!match) {
    return null;
  }

  const segment = match[1];

  if (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 (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, getButtonStyle());

    btn.addEventListener('mouseenter', () => {
      btn.style.transform = 'translateY(-50%) scale(1.05)';
      btn.style.boxShadow = '0 6px 20px rgba(60,0,177,0.7)';
    });

    btn.addEventListener('mouseleave', () => {
      btn.style.transform = 'translateY(-50%) scale(1)';
      btn.style.boxShadow = '0 4px 14px rgba(60,0,177,0.55)';
    });

    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);
  }
}
