(function() {
  'use strict';

  if (window.__PANDA_OZON_INSIGHTS__) return;
  window.__PANDA_OZON_INSIGHTS__ = true;

  var TEST_MODE = !!window.__PANDA_OZON_INSIGHTS_TEST__;
  var HOST_OK = TEST_MODE || /(^|\.)ozon\.(ru|kz|by)$/i.test(location.hostname);
  if (!HOST_OK || /seller\.ozon\./i.test(location.hostname)) return;

  var CACHE = new Map();
  var LOADING = new Map();
  var QUICK_LIST_URL = 'https://sczfai.com/pages/quick-list.html';
  var MAX_LIST_CARDS = 36;
  var ENABLE_DETAIL_CARD = false;
  var ENABLE_LIST_CARDS = false;

  function injectStyle() {
    if (document.getElementById('panda-ozon-insights-style')) return;
    var style = document.createElement('style');
    style.id = 'panda-ozon-insights-style';
    style.textContent = [
      '.panda-ozon-card{box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",Arial,sans-serif;color:#111827;background:#fff;border:1px solid #dbe7ff;border-radius:12px;box-shadow:0 8px 26px rgba(15,78,193,.16);overflow:hidden}',
      '.panda-ozon-card *{box-sizing:border-box}',
      '.panda-ozon-head{display:flex;align-items:center;justify-content:center;gap:8px;background:#fff;padding:13px 14px 10px;border-bottom:1px solid #edf3ff}',
      '.panda-ozon-logo{height:28px;max-width:150px;object-fit:contain}',
      '.panda-ozon-brand{font-size:21px;font-weight:700;color:#10203f;letter-spacing:0}',
      '.panda-ozon-code{display:flex;align-items:center;justify-content:center;gap:6px;margin:0 14px;padding:10px 0 8px;border-bottom:1px solid #e5edff;font-size:14px;font-weight:600;color:#111827}',
      '.panda-ozon-note{margin:0 14px;padding:7px 0;border-bottom:1px solid #edf3ff;text-align:center;font-size:13px;line-height:1.4;color:#b42318;font-weight:600}',
      '.panda-ozon-copy{border:0;background:#0b6cff;color:#fff;border-radius:4px;font-size:12px;line-height:1;padding:4px 6px;cursor:pointer}',
      '.panda-ozon-detail{width:286px;margin:12px 0 0}',
      '.panda-ozon-detail .panda-ozon-body{padding:10px 14px 12px}',
      '.panda-ozon-grid{display:grid;grid-template-columns:repeat(3,1fr);border-top:1px solid #edf2ff;border-left:1px solid #edf2ff}',
      '.panda-ozon-cell{min-height:50px;padding:9px 5px;text-align:center;border-right:1px solid #edf2ff;border-bottom:1px solid #edf2ff}',
      '.panda-ozon-label{font-size:13px;color:#111827;font-weight:600;line-height:1.32;margin-bottom:4px}',
      '.panda-ozon-value{font-size:13px;color:#005bff;font-weight:700;line-height:1.32;word-break:break-word}',
      '.panda-ozon-value.bad{color:#e11d48}.panda-ozon-value.good{color:#059669}.panda-ozon-value.dark{color:#111827}',
      '.panda-ozon-foot{font-size:12px;color:#6b7280;text-align:center;padding:8px 10px 10px}',
      '.panda-ozon-loading,.panda-ozon-error{padding:14px 12px;text-align:center;font-size:13px;line-height:1.5;color:#52637a}',
      '.panda-ozon-error{color:#b42318}.panda-ozon-retry{margin-top:8px;border:0;border-radius:6px;background:#0b6cff;color:#fff;padding:5px 10px;font-size:12px;cursor:pointer}',
      '.panda-ozon-list{width:100%;margin-top:8px;border-radius:9px;box-shadow:0 5px 16px rgba(15,78,193,.12)}',
      '.panda-ozon-list-host{display:flex!important;flex-direction:column!important;align-items:stretch!important}',
      '.panda-ozon-list-host>.panda-ozon-list{flex:0 0 auto;align-self:stretch;min-width:0}',
      '.panda-ozon-list-top{height:32px;background:#005bff;color:#fff;border-radius:9px 9px 0 0;display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:700}',
      '.panda-ozon-list-inner{background:#fff;border:1px solid #d7e5ff;border-top:0;border-radius:0 0 9px 9px;padding:8px 8px 10px}',
      '.panda-ozon-list-title{text-align:center;color:#111827;font-size:13px;font-weight:700;line-height:1.38;margin-bottom:7px}',
      '.panda-ozon-row{display:flex;align-items:flex-start;justify-content:space-between;gap:6px;border-top:1px solid #edf2ff;padding:4px 0;font-size:13px;line-height:1.38}',
      '.panda-ozon-row span:first-child{flex:0 0 auto;max-width:60%;color:#111827;font-weight:600;text-align:left;overflow-wrap:anywhere}.panda-ozon-row span:last-child{flex:1;min-width:0;color:#005bff;font-weight:700;text-align:right;overflow-wrap:anywhere}',
      '.panda-ozon-row .bad{color:#e11d48!important}.panda-ozon-row .good{color:#059669!important}',
      '.panda-ozon-actions{display:flex;gap:6px;padding:8px 8px 0}',
      '.panda-ozon-action{flex:1;border:0;border-radius:5px;padding:6px 5px;font-size:13px;font-weight:700;line-height:1.2;cursor:pointer;color:#fff;background:#005bff}',
      '.panda-ozon-action.copy{background:#10b981}.panda-ozon-action:hover{filter:brightness(.96)}',
      '.panda-ozon-detail .panda-ozon-actions{padding:0 14px 12px}.panda-ozon-detail .panda-ozon-action{font-size:12px;padding:7px 6px;border-radius:6px}',
      '.panda-ozon-mini-error{font-size:11px;color:#b42318;text-align:center;padding:8px 6px;background:#fff;border:1px solid #ffd3d3;border-radius:8px;margin-top:8px}',
      '.panda-ozon-status{color:#b42318!important}',
      '.panda-ozon-fixed{position:fixed;right:18px;top:380px;z-index:2147483600}',
      '@media(max-width:900px){.panda-ozon-fixed{position:static;width:100%;margin:12px 0}.panda-ozon-detail{width:100%}}'
    ].join('');
    document.documentElement.appendChild(style);
  }

  function escapeHtml(value) {
    return String(value == null ? '' : value)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;');
  }

  function extractSku(url) {
    var text = String(url || '');
    var match = text.split('?')[0].match(/-(\d+)(?:\/)?$/);
    if (match) return match[1];
    match = text.match(/\/product\/[^?#]*?(\d{6,})(?:[/?#]|$)/);
    return match ? match[1] : '';
  }

  function currentSku() {
    return String(window.__PANDA_OZON_TEST_SKU__ || extractSku(location.href) || '');
  }

  function isProductPage() {
    return /\/product\//i.test(location.pathname) || (TEST_MODE && !!currentSku());
  }

  function firstItem(items) {
    if (Array.isArray(items)) return items[0] || {};
    if (items && typeof items === 'object') return items[0] || items['0'] || {};
    return {};
  }

  function num(value) {
    if (value == null || value === '' || value === '-') return null;
    var n = parseFloat(String(value).replace(/\s/g, '').replace(',', '.').replace(/[^\d.-]/g, ''));
    return isFinite(n) ? n : null;
  }

  function fmt(value, suffix, digits) {
    var n = num(value);
    if (n == null) return '-';
    var opts = { maximumFractionDigits: digits == null ? 2 : digits };
    return n.toLocaleString('zh-CN', opts) + (suffix || '');
  }

  function fmtInt(value) {
    var n = num(value);
    return n == null ? '-' : Math.round(n).toLocaleString('zh-CN');
  }

  function fmtRub(value) {
    var n = num(value);
    return n == null ? '-' : n.toLocaleString('zh-CN', { maximumFractionDigits: 2 }) + '卢布';
  }

  function fmtPct(value) {
    var n = num(value);
    if (n == null) return '-';
    return n.toLocaleString('zh-CN', { maximumFractionDigits: 3 }) + '%';
  }

  function quickPrice(data) {
    var price = num(data && (data.minSellerPrice != null ? data.minSellerPrice : (data.avgPrice != null ? data.avgPrice : data.frontPrice)));
    return price == null ? '' : String(Math.round(price * 100) / 100);
  }

  function quickSku(data) {
    return String((data && (data.variantId || data.sku)) || '');
  }

  function quickListHref(data) {
    var sku = quickSku(data);
    var price = quickPrice(data);
    var params = [
      'sku=' + encodeURIComponent(sku),
      'price=' + encodeURIComponent(price),
      'source=ozon-plugin'
    ];
    return QUICK_LIST_URL + '?' + params.join('&');
  }

  function actionsHtml(data) {
    var sku = quickSku(data);
    return '<div class="panda-ozon-actions">'
      + '<button class="panda-ozon-action panda-ozon-copy copy" data-copy="' + escapeHtml(sku) + '">复制SKU</button>'
      + '<button class="panda-ozon-action panda-ozon-quick" data-quick-url="' + escapeHtml(quickListHref(data)) + '">一键上货</button>'
      + '</div>';
  }

  function fmtDate(value) {
    if (!value || value === '-') return '-';
    var text = String(value);
    var match = text.match(/\d{4}-\d{2}-\d{2}/);
    return match ? match[0] : text.slice(0, 10);
  }

  function clsByNumber(value) {
    var n = num(value);
    if (n == null || n === 0) return '';
    return n < 0 ? 'bad' : 'good';
  }

  function pickCommission(detail, item) {
    var list = Array.isArray(detail && detail.commissions) ? detail.commissions : [];
    if (!list.length) return null;
    var schema = String((item && item.salesSchema) || '').toUpperCase();
    var found = list.find(function(row) {
      return schema && String(row.sale_schema || '').toUpperCase() === schema;
    }) || list.find(function(row) {
      return String(row.sale_schema || '').toUpperCase() === 'FBS';
    }) || list[0];
    return found || null;
  }

  function normalize(raw, sku) {
    var analytics = raw && raw.analytics ? raw.analytics : raw;
    var item = firstItem(analytics && analytics.items);
    var detail = raw && raw.productDetail ? raw.productDetail : (analytics && analytics.productDetail) || {};
    var specs = detail && detail.specifications ? detail.specifications : {};
    var commission = pickCommission(detail, item);
    var dimensions = [
      specs.length || detail.depth,
      specs.width || detail.width,
      specs.height || detail.height
    ].filter(function(v) { return num(v) != null; });
    var productName = item.name || detail.name || item.skuName || '';
    return {
      sku: String((item && (item.sku || item.variantId)) || sku || ''),
      variantId: item.variantId || detail.variant_id || sku || '',
      title: productName,
      brand: item.brand || detail.brand || '-',
      category1: item.category1 || '-',
      category3: item.category3 || '-',
      frontPrice: null,
      rating: null,
      reviews: null,
      soldCount: item.soldCount,
      soldSum: item.gmvSum != null ? item.gmvSum : item.soldSum,
      salesDynamics: item.salesDynamics,
      avgPrice: item.avgPrice,
      minSellerPrice: item.minSellerPrice,
      addRate: item.convToCartPdp != null ? item.convToCartPdp : item.convToCart,
      views: item.views != null ? item.views : item.qtyViewPdp,
      drr: item.drr,
      daysWithTrafarets: item.daysWithTrafarets,
      searchConv: item.convToCartSearch,
      exposeConv: item.convViewToOrder != null ? item.convViewToOrder : item.pdpToCartConversion,
      exposes: item.sessionCount != null ? item.sessionCount : item.qtyViewPdp,
      promoDays: item.daysInPromo,
      detailViews: item.qtyViewPdp,
      avgDeliveryTime: item.avgDeliveryTime,
      redemptionRate: item.nullableRedemptionRate,
      promoRevenueShare: item.promoRevenueShare,
      salesSchema: item.salesSchema || ((detail.sources && detail.sources[0] && detail.sources[0].shipment_type) || '-'),
      stock: item.stock != null ? item.stock : (detail.stocks && detail.stocks.stocks && detail.stocks.stocks[0] ? detail.stocks.stocks[0].present : '-'),
      createDate: item.nullableCreateDate || detail.created_at || detail.createDate,
      sellerName: item.sellerName || '-',
      sellerId: item.sellerId || '-',
      commissionValue: commission && commission.value,
      commissionPercent: commission && commission.percent,
      commissionSchema: commission && commission.sale_schema,
      volume: item.volume != null ? item.volume : detail.volume_weight,
      dimensions: dimensions.length === 3 ? dimensions.join('*') : '-',
      weight: specs.weight || detail.weight || (detail.volume_weight ? Math.round(Number(detail.volume_weight) * 1000) : null),
      allowCopy: detail.is_copy_allowed === false ? '否' : '是',
      sellerCount: item.sumItemsInStock || item.accessibility || '-',
      error: raw && raw.error,
      detailError: detail && detail._error
    };
  }

  function emptyData(sku, extra) {
    extra = extra || {};
    return {
      sku: String(sku || extra.sku || ''),
      variantId: String(extra.variantId || sku || ''),
      title: extra.title || '',
      brand: '-',
      category1: '-',
      category3: '-',
      frontPrice: extra.frontPrice || extra.price || null,
      rating: extra.rating || null,
      reviews: extra.reviews || null,
      soldCount: null,
      soldSum: null,
      salesDynamics: null,
      avgPrice: extra.price || null,
      minSellerPrice: extra.price || null,
      addRate: null,
      views: null,
      drr: null,
      daysWithTrafarets: null,
      searchConv: null,
      exposeConv: null,
      exposes: null,
      promoDays: null,
      detailViews: null,
      avgDeliveryTime: null,
      redemptionRate: null,
      promoRevenueShare: null,
      salesSchema: '-',
      stock: null,
      createDate: null,
      sellerName: '-',
      sellerId: '-',
      commissionValue: null,
      commissionPercent: null,
      commissionSchema: '',
      volume: null,
      dimensions: '-',
      weight: null,
      allowCopy: '-',
      sellerCount: null
    };
  }

  function pickDataValue(primary, fallback) {
    if (primary == null || primary === '' || primary === '-') return fallback;
    return primary;
  }

  function mergeData(base, seller) {
    base = base || {};
    seller = seller || {};
    var out = {};
    Object.keys(base).forEach(function(key) { out[key] = base[key]; });
    Object.keys(seller).forEach(function(key) {
      out[key] = pickDataValue(seller[key], out[key]);
    });
    out.sku = out.sku || base.sku || seller.sku;
    out.variantId = out.variantId || out.sku;
    out.frontPrice = pickDataValue(out.frontPrice, pickDataValue(out.minSellerPrice, out.avgPrice));
    return out;
  }

  function getText(selectors, root) {
    root = root || document;
    for (var i = 0; i < selectors.length; i++) {
      var node = root.querySelector(selectors[i]);
      var text = node && (node.innerText || node.textContent || '').trim();
      if (text) return text.replace(/\s+/g, ' ');
    }
    return '';
  }

  function parsePriceText(text) {
    var match = String(text || '').replace(/\s/g, '').replace(',', '.').match(/(\d+(?:\.\d+)?)/);
    return match ? match[1] : '';
  }

  function readPageBasics(sku) {
    var title = getText(['h1', '[data-widget*="webProductHeading"]', '[data-widget*="webProductTitle"]']);
    var priceText = getText([
      '[data-widget*="webPrice"]',
      '[data-widget*="skuPrice"]',
      '[data-widget*="webSale"]',
      '[data-widget*="webAddToCart"]'
    ]);
    var ratingText = document.body ? (document.body.innerText || '') : '';
    var rating = (ratingText.match(/(\d+(?:[.,]\d+)?)\s*[• ]*\s*\d+\s*(?:отзыв|отзыва|отзывов)/i) || [])[1] || '';
    var reviews = (ratingText.match(/(\d[\d\s]*)\s*(?:отзыв|отзыва|отзывов)/i) || [])[1] || '';
    return emptyData(sku, {
      title: title,
      frontPrice: parsePriceText(priceText),
      rating: rating,
      reviews: reviews
    });
  }

  function requestPublicData(sku) {
    if (TEST_MODE) return Promise.resolve(readPageBasics(sku));
    if (!isProductPage()) return Promise.resolve(null);
    var path = location.pathname + (location.search || '');
    return fetch('/api/entrypoint-api.bx/page/json/v2?url=' + encodeURIComponent(path), { credentials: 'include' })
      .then(function(resp) { return resp.ok ? resp.json() : null; })
      .then(function(data) {
        var script = data && data.seo && data.seo.script && data.seo.script[0] && data.seo.script[0].innerHTML;
        if (!script) return null;
        var json = JSON.parse(script);
        var brand = json.brand && (json.brand.name || json.brand);
        var offers = json.offers || {};
        var rating = json.aggregateRating || {};
        return emptyData(sku || json.sku, {
          title: json.name,
          brand: brand,
          frontPrice: offers.price,
          rating: rating.ratingValue,
          reviews: rating.reviewCount
        });
      }).catch(function() { return null; });
  }

  function requestInsights(sku) {
    if (!sku) return Promise.reject(new Error('未识别到商品 SKU'));
    if (CACHE.has(sku)) return Promise.resolve(CACHE.get(sku));
    if (LOADING.has(sku)) return LOADING.get(sku);

    var promise = new Promise(function(resolve, reject) {
      var done = false;
      var timer = setTimeout(function() {
        if (!done) reject(new Error('请求超时'));
      }, 32000);

      try {
        if (!window.chrome || !chrome.runtime || !chrome.runtime.sendMessage) {
          reject(new Error('后台分析数据待插件环境补全'));
          return;
        }
        chrome.runtime.sendMessage({ type: 'panda:ozonInsights', sku: sku }, function(resp) {
          done = true;
          clearTimeout(timer);
          if (chrome.runtime.lastError) {
            reject(new Error(chrome.runtime.lastError.message));
            return;
          }
          if (!resp || !resp.ok) {
            reject(new Error((resp && resp.error) || '没有返回数据'));
            return;
          }
          var normalized = normalize(resp.data || {}, sku);
          CACHE.set(sku, normalized);
          resolve(normalized);
        });
      } catch (error) {
        done = true;
        clearTimeout(timer);
        reject(error);
      }
    });

    LOADING.set(sku, promise);
    promise.then(function() { LOADING.delete(sku); }, function() { LOADING.delete(sku); });
    return promise;
  }

  function row(label, value, cls) {
    return '<div class="panda-ozon-row"><span>' + escapeHtml(label) + '</span><span class="' + (cls || '') + '">' + escapeHtml(value) + '</span></div>';
  }

  function gridCell(label, value, cls) {
    return '<div class="panda-ozon-cell"><div class="panda-ozon-label">' + escapeHtml(label) + '</div><div class="panda-ozon-value ' + (cls || '') + '">' + escapeHtml(value) + '</div></div>';
  }

  function detailHtml(data, statusText) {
    var commission = data.commissionValue != null
      ? '-' + fmtRub(data.commissionValue) + ' (' + (data.commissionSchema || '佣金') + ' ' + fmtPct(data.commissionPercent) + ')'
      : '-';
    var grid = [
      gridCell('当前售价', fmtRub(data.frontPrice), 'dark'),
      gridCell('评分', data.rating || '-'),
      gridCell('评论数', fmtInt(data.reviews)),
      gridCell('月销量', fmtInt(data.soldCount)),
      gridCell('月销售额', fmtRub(data.soldSum)),
      gridCell('月销售变化', fmtPct(data.salesDynamics), clsByNumber(data.salesDynamics)),
      gridCell('平均价格', fmtRub(data.avgPrice), 'dark'),
      gridCell('最低售价', fmtRub(data.minSellerPrice), 'dark'),
      gridCell('品牌', data.brand),
      gridCell('曝光量', fmtInt(data.views)),
      gridCell('曝光转化率', fmtPct(data.exposeConv)),
      gridCell('搜索转换率', fmtPct(data.searchConv)),
      gridCell('加购率', fmtPct(data.addRate)),
      gridCell('结算率', fmtPct(data.redemptionRate)),
      gridCell('推广费用占比', fmtPct(data.drr)),
      gridCell('开启模板活动天数', fmtInt(data.daysWithTrafarets)),
      gridCell('开启促销天数', fmtInt(data.promoDays)),
      gridCell('促销收入占比', fmtPct(data.promoRevenueShare)),
      gridCell('平均运输时间', fmtInt(data.avgDeliveryTime) + '天'),
      gridCell('配送方式', data.salesSchema),
      gridCell('销售卖家数', fmtInt(data.sellerCount)),
      gridCell('是否允许复制', data.allowCopy),
      gridCell('出售时间', fmtDate(data.createDate)),
      gridCell('库存', fmtInt(data.stock)),
      gridCell('佣金', commission),
      gridCell('体积', data.dimensions),
      gridCell('重量', data.weight ? fmtInt(data.weight) + 'g' : '-')
    ].join('');

    return '<div class="panda-ozon-head">'
      + '<span class="panda-ozon-brand">熊猫助手</span>'
      + '</div>'
      + '<div class="panda-ozon-code">商品编码：<span>' + escapeHtml(data.variantId || data.sku) + '</span><button class="panda-ozon-copy" data-copy="' + escapeHtml(data.variantId || data.sku) + '">复制</button></div>'
      + (statusText ? '<div class="panda-ozon-note">' + escapeHtml(statusText) + '</div>' : '')
      + '<div class="panda-ozon-body"><div class="panda-ozon-grid">' + grid + '</div></div>'
      + actionsHtml(data)
      + '<div class="panda-ozon-foot">数据来自 Ozon Seller 后台登录态</div>';
  }

  function listHtml(data, statusText) {
    var commission = data.commissionValue != null
      ? '-' + fmtRub(data.commissionValue) + ' (' + fmtPct(data.commissionPercent) + ')'
      : '-';
    var body = ''
      + '<div class="panda-ozon-list-title">商品ID：' + escapeHtml(data.variantId || data.sku) + '<br>数据一览</div>'
      + (statusText ? row('状态', statusText, 'panda-ozon-status') : '')
      + row('品牌', data.brand)
      + row('标题', data.title || '-')
      + row('当前售价', fmtRub(data.frontPrice))
      + row('评分', data.rating || '-')
      + row('评论数', fmtInt(data.reviews))
      + row('出售时间', fmtDate(data.createDate))
      + row('一级类目', data.category1)
      + row('三级类目', data.category3)
      + row('30天销量', fmtInt(data.soldCount))
      + row('30天销售额', fmtRub(data.soldSum))
      + row('30天销售变化', fmtPct(data.salesDynamics), clsByNumber(data.salesDynamics))
      + row('平均售价', fmtRub(data.avgPrice))
      + row('最低售价', fmtRub(data.minSellerPrice))
      + row('加购率', fmtPct(data.addRate))
      + row('浏览量', fmtInt(data.views))
      + row('推广费用占比', fmtPct(data.drr))
      + row('开启模板活动天数', fmtInt(data.daysWithTrafarets))
      + row('搜索转换率', fmtPct(data.searchConv))
      + row('曝光转化率', fmtPct(data.exposeConv))
      + row('曝光次数', fmtInt(data.exposes))
      + row('开启促销天数', fmtInt(data.promoDays))
      + row('详情页访问量', fmtInt(data.detailViews))
      + row('平均运输时间', fmtInt(data.avgDeliveryTime) + '天')
      + row('结算率', fmtPct(data.redemptionRate))
      + row('促销收入占比', fmtPct(data.promoRevenueShare))
      + row('配送方式', data.salesSchema)
      + row('佣金', commission)
      + row('体积', data.dimensions)
      + row('重量', data.weight ? fmtInt(data.weight) + 'g' : '-')
      + row('销售该商品卖家数量', fmtInt(data.sellerCount))
      + row('是否允许复制', data.allowCopy)
      + actionsHtml(data);
    return '<div class="panda-ozon-list-top">数据一览</div><div class="panda-ozon-list-inner">' + body + '</div>';
  }

  function loadingHtml() {
    return '<div class="panda-ozon-loading">正在读取 Ozon 后台真实数据...</div>';
  }

  function errorHtml(message, sku) {
    return '<div class="panda-ozon-error">' + escapeHtml(message || '获取失败')
      + '<br><button class="panda-ozon-retry" data-retry="' + escapeHtml(sku || '') + '">重新获取</button></div>';
  }

  function findRightRailAnchor() {
    var selectors = [
      '[data-widget*="webPrice"]',
      '[data-widget*="skuPrice"]',
      '[data-widget*="webSale"]',
      '[data-widget*="webAddToCart"]',
      '[data-widget*="webCurrentSeller"]',
      '[data-widget*="webBuybox"]',
      '[data-widget*="webProductInformation"]',
      '[data-widget*="webStickyProducts"]'
    ];
    var nodes = [];
    selectors.forEach(function(sel) {
      document.querySelectorAll(sel).forEach(function(node) { nodes.push(node); });
    });
    for (var i = 0; i < nodes.length; i++) {
      var el = nodes[i];
      var cur = el;
      for (var depth = 0; cur && depth < 7; depth++, cur = cur.parentElement) {
        var rect = cur.getBoundingClientRect();
        if (rect.width >= 240 && rect.width <= 430 && rect.left > window.innerWidth * 0.45) {
          return cur;
        }
      }
    }
    return nodes[0] || null;
  }

  function mountDetail() {
    if (!ENABLE_DETAIL_CARD) {
      var disabledCard = document.getElementById('panda-ozon-detail-card');
      if (disabledCard) disabledCard.remove();
      return;
    }
    if (!isProductPage()) return;
    var sku = currentSku();
    if (!sku) return;
    var existing = document.getElementById('panda-ozon-detail-card');
    if (existing && existing.dataset.sku === sku) return;
    if (existing) existing.remove();

    var card = document.createElement('div');
    card.id = 'panda-ozon-detail-card';
    card.dataset.sku = sku;
    card.className = 'panda-ozon-card panda-ozon-detail';
    var baseData = readPageBasics(sku);
    card.innerHTML = detailHtml(baseData, '正在读取后台分析数据');

    var anchor = findRightRailAnchor();
    if (anchor && anchor.parentNode) {
      anchor.parentNode.insertBefore(card, anchor.nextSibling);
    } else {
      card.classList.add('panda-ozon-fixed');
      document.body.appendChild(card);
    }

    requestPublicData(sku).then(function(publicData) {
      if (publicData && card.dataset.sku === sku) {
        baseData = mergeData(baseData, publicData);
        card.innerHTML = detailHtml(baseData, '正在读取后台分析数据');
      }
    });

    requestInsights(sku).then(function(data) {
      card.innerHTML = detailHtml(mergeData(baseData, data));
    }).catch(function(error) {
      card.innerHTML = detailHtml(baseData, error.message || '后台分析数据未补全');
    });
  }

  function findProductCard(anchor) {
    var direct = anchor.closest('[data-index], [data-widget="skuShelfGoods"] [class], [data-widget="skuGridSimple"] [class], [data-widget="searchResultsV2"] [class], [data-widget="tileGridDesktop"] [class]');
    if (direct && direct.tagName === 'A') direct = direct.parentElement;
    if (direct && direct.contains(anchor) && direct.querySelectorAll('a[href*="/product/"]').length > 6) direct = null;
    if (direct && direct !== document.body) {
      var directRect = direct.getBoundingClientRect();
      if (directRect.width >= 110 && directRect.width <= 420 && directRect.height >= 80 && directRect.height <= 1800) {
        return direct;
      }
    }

    var best = null;
    var cur = anchor;
    for (var depth = 0; cur && depth < 10; depth++, cur = cur.parentElement) {
      if (!cur || cur === document.body) break;
      if (cur.tagName === 'A') continue;
      var rect = cur.getBoundingClientRect();
      if (rect.width >= 110 && rect.width <= 420 && rect.height >= 80 && rect.height <= 1800) {
        best = cur;
      }
    }
    return best;
  }

  function isVisibleProductAnchor(anchor) {
    if (!anchor || !anchor.href || anchor.closest('#panda-ozon-detail-card')) return false;
    var rect = anchor.getBoundingClientRect();
    return rect.width > 20 && rect.height > 20 && rect.bottom > 0 && rect.top < window.innerHeight + 1200;
  }

  function collectProductAnchors() {
    var seen = {};
    return Array.from(document.querySelectorAll(
      '[data-widget="skuShelfGoods"] a[href*="/product/"],'
      + '[data-widget="skuGridSimple"] a[href*="/product/"],'
      + '[data-widget="searchResultsV2"] a[href*="/product/"],'
      + '[data-widget="tileGridDesktop"] a[href*="/product/"],'
      + '[data-index] a[href*="/product/"],'
      + 'a[href*="/product/"]'
    )).filter(function(anchor) {
      var sku = extractSku(anchor.href);
      if (!sku || seen[sku] || !isVisibleProductAnchor(anchor)) return false;
      seen[sku] = true;
      return true;
    });
  }

  function readCardBasics(cardRoot, sku) {
    var text = cardRoot ? (cardRoot.innerText || '') : '';
    var priceMatch = text.match(/(\d[\d\s.,]*)\s*(?:₽|руб|руб\.|Р)/i);
    return emptyData(sku, {
      title: text.split('\n').filter(Boolean).slice(0, 2).join(' / '),
      frontPrice: priceMatch ? priceMatch[1] : null,
      price: priceMatch ? priceMatch[1] : null
    });
  }

  function mountListCards() {
    if (!ENABLE_LIST_CARDS) {
      document.querySelectorAll('.panda-ozon-list').forEach(function(panel) {
        var host = panel.parentElement;
        panel.remove();
        if (host && !host.querySelector('.panda-ozon-list')) {
          host.classList.remove('panda-ozon-list-host');
        }
      });
      return;
    }
    var onDetailPage = /\/product\//i.test(location.pathname);
    var current = currentSku();
    var mounted = document.querySelectorAll('.panda-ozon-list').length;
    if (mounted >= MAX_LIST_CARDS) return;

    var anchors = collectProductAnchors();
    for (var i = 0; i < anchors.length && mounted < MAX_LIST_CARDS; i++) {
      var anchor = anchors[i];
      var sku = extractSku(anchor.href);
      if (!sku || sku === current) continue;
      var cardRoot = findProductCard(anchor);
      if (!cardRoot || cardRoot.querySelector('.panda-ozon-list')) continue;
      if (cardRoot.closest('#panda-ozon-detail-card')) continue;
      var rect = cardRoot.getBoundingClientRect();
      if (onDetailPage && rect.top < 260 && rect.left < window.innerWidth * 0.55) continue;

      var panel = document.createElement('div');
      panel.className = 'panda-ozon-card panda-ozon-list';
      panel.dataset.sku = sku;
      var baseData = readCardBasics(cardRoot, sku);
      panel.innerHTML = listHtml(baseData, '正在读取');
      cardRoot.classList.add('panda-ozon-list-host');
      cardRoot.appendChild(panel);
      mounted++;

      requestInsights(sku).then((function(targetPanel, targetBase) {
        return function(data) {
          targetPanel.innerHTML = listHtml(mergeData(targetBase, data));
        };
      })(panel, baseData)).catch((function(targetPanel, targetSku, targetBase) {
        return function(error) {
          targetPanel.innerHTML = listHtml(targetBase || emptyData(targetSku), error.message || '后台数据未补全');
          targetPanel.dataset.sku = targetSku;
        };
      })(panel, sku, baseData));
    }
  }

  function boot() {
    injectStyle();
    mountDetail();
    mountListCards();
  }

  document.addEventListener('click', function(event) {
    var copy = event.target.closest('.panda-ozon-copy');
    if (copy) {
      event.preventDefault();
      event.stopPropagation();
      navigator.clipboard && navigator.clipboard.writeText(copy.dataset.copy || '');
      copy.textContent = '已复制';
      setTimeout(function() { copy.textContent = copy.classList.contains('panda-ozon-action') ? '复制SKU' : '复制'; }, 900);
      return;
    }
    var quick = event.target.closest('.panda-ozon-quick');
    if (quick) {
      event.preventDefault();
      event.stopPropagation();
      var href = quick.dataset.quickUrl || QUICK_LIST_URL;
      window.open(href, '_blank');
      return;
    }
    var retry = event.target.closest('.panda-ozon-retry');
    if (retry) {
      event.preventDefault();
      var sku = retry.dataset.retry;
      CACHE.delete(sku);
      var card = retry.closest('.panda-ozon-card');
      if (card) card.innerHTML = loadingHtml();
      requestInsights(sku).then(function(data) {
        if (card) card.innerHTML = detailHtml(data);
      }).catch(function(error) {
        if (card) card.innerHTML = errorHtml(error.message, sku);
      });
    }
  }, true);

  var lastUrl = location.href;
  setInterval(function() {
    if (location.href !== lastUrl) {
      lastUrl = location.href;
      setTimeout(boot, 600);
    } else {
      mountListCards();
    }
  }, 1200);

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot);
  } else {
    setTimeout(boot, 300);
  }

  var observer = new MutationObserver(function() {
    clearTimeout(observer._timer);
    observer._timer = setTimeout(mountListCards, 500);
  });
  if (document.body) observer.observe(document.body, { childList: true, subtree: true });
})();
