/**
 * HTML-tag fallback (phao cuoi cung).
 *
 * Chi doc cac TAG cau truc cua trang san pham dang mo (<title>, <meta og:*>,
 * <meta name="description">, <link rel="canonical">) de dung mot product toi thieu
 * (partial). KHONG parse JSON blob (ld+json / __INITIAL_STATE__ / mfe-initial-data).
 *
 * Dung khi passive cache miss VA ca 3 phuong thuc active-replay deu tra null.
 * Chay trong content script (co document). Ket qua danh dau `partial: true`.
 */

const decodeEntities = (value) => {
  if (!value) {
    return '';
  }

  return value
    .replace(/&amp;/g, '&')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, "'")
    .replace(/&#x2F;/gi, '/')
    .replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code)));
};

const metaContent = (key, attr = 'property') => {
  const node = document.querySelector(`meta[${attr}="${key}"]`);

  if (!node) {
    return '';
  }

  return node.getAttribute('content') || '';
};

/**
 * Trich fileId tu URL CDN Shopee (`.../file/{fileId}`), khong phu thuoc host quoc gia.
 * @param {string} imageUrl
 * @returns {string}
 */
const extractFileId = (imageUrl) => {
  if (!imageUrl) {
    return '';
  }

  const match = imageUrl.match(/\/file\/([^/?#]+)/);

  if (match && match[1]) {
    return match[1];
  }

  return '';
};

const stripShopeeTitle = (title) => {
  if (!title) {
    return '';
  }

  return title.replace(/\s*\|\s*Shopee.*$/i, '').trim();
};

/**
 * Dung raw product flat-shape ma refactorProduct() tieu thu (itemid/shopid/image/images/...).
 * KHONG di qua adapterDetailProduct (adapter do can shape nested cua get_pc).
 * @param {string|number} productId
 * @param {string|number} shopId
 * @returns {object|null}
 */
export const buildProductFromHtml = (productId, shopId) => {
  const itemId = Number(productId);
  const shopIdNumber = Number(shopId);

  if (!(itemId && shopIdNumber)) {
    return null;
  }

  const ogImage = metaContent('og:image');
  const rawTitle = metaContent('og:title') || document.title || '';
  const title = decodeEntities(stripShopeeTitle(rawTitle));
  const description = decodeEntities(metaContent('og:description') || metaContent('description', 'name'));

  const fileId = extractFileId(ogImage);
  const imageField = fileId || ogImage;
  const images = imageField ? [imageField] : [];

  return {
    itemid: itemId,
    shopid: shopIdNumber,
    item_id: itemId,
    shop_id: shopIdNumber,
    name: title,
    title,
    description,
    image: imageField,
    images,
    long_images: [],
    models: [],
    tier_variations: [],
    video_info_list: [],
    currency: 'VND',
    partial: true,
  };
};
