/**
 * 熊猫ERP - OZON商品数据浮窗
 * 完全独立的脚本，不依赖其他任何文件
 */
(function() {
  'use strict';

  // 只在OZON商品详情页运行
  if (!location.href.includes('ozon.ru/product/') && !location.href.includes('ozon.kz/product/') && !location.href.includes('ozon.by/product/')) {
    return;
  }

  console.log('[熊猫ERP] OZON商品数据浮窗加载');

  function getSkuFromUrl() {
    var pathMatch = location.pathname.match(/-(\d+)(?:\/)?$/);
    if (pathMatch) return pathMatch[1];

    var hrefMatch = location.href.match(/-(\d+)(?:[/?#]|$)/);
    if (hrefMatch) return hrefMatch[1];

    return '';
  }

  var SKU = getSkuFromUrl();

  function insertCard() {
    if (document.getElementById('panda-ozon-card')) return true;
    if (!SKU) {
      console.warn('[熊猫ERP] 未能从OZON商品详情页URL提取SKU:', location.href);
      return false;
    }

    var container = document.querySelector('[data-widget*="skuPrice"]') ||
                    document.querySelector('[data-widget*="webPrice"]') ||
                    document.querySelector('[data-widget*="webSale"]') ||
                    document.querySelector('[data-widget*="webProductHeading"]') ||
                    document.querySelector('.product-main-info') ||
                    document.querySelector('[class*="price"][class*="main"]') ||
                    document.querySelector('[data-widget*="webPackage"]');

    var card = document.createElement('div');
    card.id = 'panda-ozon-card';
    card.style.cssText = 'background:#fff;border-radius:12px;padding:16px;margin:12px 0;border:1px solid #e9ebef;font-size:13px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;box-shadow:0 4px 16px rgba(0,0,0,.08)';
    card.innerHTML = '<div style="font-size:14px;font-weight:700;color:#005bff;margin-bottom:8px;display:flex;justify-content:space-between"><span>\u{1F42C} \u{718A}\u{732B}\u{5E97}\u{957F}</span><span style="font-weight:400;font-size:12px;color:#999">SKU: '+SKU+'</span></div><div id="panda-ozon-body" style="color:#6b7280;font-size:12px;padding:12px 0;text-align:center">\u{6B63}\u{5728}\u{52A0}\u{8F7D}\u{6570}\u{636E}...</div>';

    if (container && container.parentNode) {
      container.parentNode.insertBefore(card, container.nextSibling);
    } else {
      card.style.cssText += ';position:fixed;right:16px;top:96px;width:360px;max-width:calc(100vw - 32px);z-index:2147483647';
      document.body.appendChild(card);
    }
    return true;
  }

  // 加载数据
  function fetchData() {
    var body = document.getElementById('panda-ozon-body');
    if (!body) return;

    fetch('/api/entrypoint-api.bx/page/json/v2?url=' + location.pathname)
      .then(function(r) { return r.text(); })
      .then(function(txt) {
        var d = JSON.parse(txt);
        if (d && d.seo && d.seo.script) {
          var script = Array.isArray(d.seo.script) ? d.seo.script[0] : d.seo.script;
          var raw = script && (script.innerHTML || script.text || script);
          var pd = JSON.parse(raw);
          var n = (pd.name || '').substring(0, 60);
          var pr = pd.offers ? (pd.offers.price || '') : '';
          var s = (pd.seller && pd.seller.name) || (pd.brand && pd.brand.name) || '';
          var si = (pd.seller && pd.seller.id) || '';
          body.innerHTML = ''
            + '<div style="display:flex;justify-content:space-between;padding:5px 0;border-bottom:1px solid #f0f0f0"><span style="color:#888">\u{5546}\u{54C1}</span><span style="font-weight:500;text-align:right;max-width:280px">' + n + '</span></div>'
            + '<div style="display:flex;justify-content:space-between;padding:5px 0;border-bottom:1px solid #f0f0f0"><span style="color:#888">\u{4EF7}\u{683C}</span><span style="font-weight:700;color:#e74c3c;font-size:15px">' + pr + ' \u{20BD}</span></div>'
            + '<div style="display:flex;justify-content:space-between;padding:5px 0;border-bottom:1px solid #f0f0f0"><span style="color:#888">\u{5356}\u{5BB6}</span><span style="font-weight:500">' + s + '</span></div>'
            + '<div style="display:flex;justify-content:space-between;padding:5px 0"><span style="color:#888">\u{5356}\u{5BB6}ID</span><span style="font-weight:500;color:#005bff">' + si + '</span></div>';
        } else {
          body.textContent = '\u{6682}\u{65E0}\u{6570}\u{636E}';
        }
      })
      .catch(function() {
        var b = document.getElementById('panda-ozon-body');
        if (b) b.textContent = '\u{83B7}\u{53D6}\u{5931}\u{8D25}';
      });
  }

  // 尝试插入卡片，如果DOM没准备好就等MutationObserver
  setTimeout(function() {
    if (insertCard()) { fetchData(); return; }

    var obs = new MutationObserver(function() {
      if (insertCard()) {
        obs.disconnect();
        fetchData();
      }
    });
    obs.observe(document.body, { childList: true, subtree: true });
    setTimeout(function() { obs.disconnect(); }, 12000);
  }, 500);
})();
