(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;

  // 旧 content-script 保留稳定的真实数据请求；本脚本接收结果后唯一负责渲染。
  // 标记也用于阻止旧脚本再插入带头像的 .hq_main 卡片。
  window.__PANDA_OZON_SINGLE_CARD__ = true;

  var CACHE = new Map();
  var LOADING = new Map();
  var OFFER_CACHE = new Map();
  var PRICE = window.PandaOzonPrice || null;
  var QUICK_LIST_URL = 'https://sczfai.com/pages/quick-list.html';
  // 商品详情优先展示完整数据卡；列表页只处理首屏少量卡片，避免一次打开
  // 大量 Seller API 请求导致 Ozon 页面卡顿或触发限流。
  var MAX_LIST_CARDS = 8;
  var ENABLE_DETAIL_CARD = true;
  var ENABLE_LIST_CARDS = true;
  var MAX_CONCURRENT_INSIGHT_REQUESTS = 3;
  var INSIGHT_QUEUE = [];
  var ACTIVE_INSIGHT_REQUESTS = 0;

  function enqueueInsightRequest(task) {
    return new Promise(function(resolve, reject) {
      INSIGHT_QUEUE.push({ task: task, resolve: resolve, reject: reject });
      drainInsightQueue();
    });
  }

  function drainInsightQueue() {
    while (ACTIVE_INSIGHT_REQUESTS < MAX_CONCURRENT_INSIGHT_REQUESTS && INSIGHT_QUEUE.length) {
      var next = INSIGHT_QUEUE.shift();
      ACTIVE_INSIGHT_REQUESTS++;
      Promise.resolve().then(next.task).then(next.resolve, next.reject).then(function() {
        ACTIVE_INSIGHT_REQUESTS--;
        drainInsightQueue();
      });
    }
  }

  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}',
      // 详情卡跟随旧版 webSale 右侧容器的实际宽度，避免固定宽度留下空白。
      '.panda-ozon-detail{width:100%;min-width:0;margin:12px 0 0;align-self:stretch}',
      '.panda-ozon-detail-host{display:block;width:100%;min-width:0;flex:0 0 100%}',
      '.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-seller-value{display:flex;align-items:center;justify-content:center;gap:6px;min-height:18px;color:#005bff;font-size:13px;font-weight:700;line-height:1.32;word-break:break-word}',
      '.panda-ozon-view-offers{border:0;background:transparent;padding:0;color:#111827;font:inherit;font-size:12px;font-weight:700;text-decoration:underline;cursor:pointer}.panda-ozon-view-offers:hover{color:#005bff}.panda-ozon-view-offers:disabled{opacity:.6;cursor:wait}',
      '.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:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:6px;padding:8px 8px 0}',
      '.panda-ozon-action{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.panda-ozon-select{background:#0f9f6e}.panda-ozon-action.panda-ozon-select.is-saved{background:#e9f8f2;color:#087a56;border:1px solid #9edcc7}',
      '.panda-ozon-action.copy{background:#10b981}.panda-ozon-action.source{background:#f59e0b}.panda-ozon-action:hover{filter:brightness(.96)}.panda-ozon-action:disabled{opacity:.62;cursor:wait}',
      '.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-offer-mask{position:fixed;inset:0;z-index:2147483646;display:flex;align-items:center;justify-content:center;padding:18px;background:rgba(15,23,42,.42)}',
      '.panda-ozon-offer-dialog{width:min(520px,100%);max-height:min(640px,calc(100vh - 36px));display:flex;flex-direction:column;background:#fff;border-radius:12px;box-shadow:0 20px 50px rgba(15,23,42,.28);overflow:hidden}',
      '.panda-ozon-offer-head{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:13px 15px;border-bottom:1px solid #e5edff;font-size:15px;font-weight:800;color:#10203f}',
      '.panda-ozon-offer-close{border:0;background:transparent;padding:2px 4px;color:#64748b;font-size:22px;line-height:1;cursor:pointer}',
      '.panda-ozon-offer-body{overflow:auto;padding:12px 15px;color:#334155;font-size:13px;line-height:1.5}',
      '.panda-ozon-offer-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:7px;margin:0;padding:0;list-style:none}',
      '.panda-ozon-offer-list a{display:block;padding:7px 8px;border:1px solid #dbe7ff;border-radius:6px;color:#005bff;text-decoration:none;font-weight:700;overflow-wrap:anywhere}.panda-ozon-offer-list a:hover{background:#f3f7ff}',
      '.panda-ozon-offer-actions{display:flex;justify-content:flex-end;gap:8px;padding:10px 15px 14px;border-top:1px solid #edf2ff}',
      '.panda-ozon-offer-button{border:0;border-radius:6px;padding:7px 10px;background:#005bff;color:#fff;font-size:13px;font-weight:700;cursor:pointer}.panda-ozon-offer-button.secondary{background:#eef4ff;color:#005bff}',
      '.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 firstPositive() {
    for (var i = 0; i < arguments.length; i++) {
      var value = num(arguments[i]);
      if (value != null && value > 0) return value;
    }
    return 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 fmtDeliveryDays(value) {
    var n = num(value);
    // Ozon analytics uses -1 as an unavailable sentinel. It is not a real
    // negative delivery duration and must never be shown as “-1天”.
    return n == null || n < 0 ? '-' : Math.round(n).toLocaleString('zh-CN') + '天';
  }

  function currencyCode(value) {
    var text = String(value == null ? '' : value).trim().toUpperCase();
    if (!text) return '';
    if (text === 'RUB' || /₽|РУБ|RUR/.test(text)) return 'RUB';
    if (text === 'KZT' || /₸|ТЕНГЕ/.test(text)) return 'KZT';
    if (text === 'BYN' || /BR\.?|БЕЛ\.?s*РУБ/.test(text)) return 'BYN';
    if (text === 'CNY' || /¥|RMB|人民币/.test(text)) return 'CNY';
    if (text === 'USD' || /\$|US\s*DOLLAR/.test(text)) return 'USD';
    if (text === 'EUR' || /€|EURO/.test(text)) return 'EUR';
    return '';
  }

  function pageCurrency() {
    var text = getText([
      '[data-widget*="webPrice"]', '[data-widget*="skuPrice"]',
      '[data-widget*="webSale"]', '[data-widget*="webAddToCart"]'
    ]);
    return currencyCode(text) || (/\.kz$/i.test(location.hostname) ? 'KZT' : (/\.by$/i.test(location.hostname) ? 'BYN' : 'RUB'));
  }

  function currencyLabel(code) {
    return { RUB: '卢布', KZT: '坚戈', BYN: '白俄罗斯卢布', CNY: '人民币', USD: '美元', EUR: '欧元' }[currencyCode(code)] || String(code || '');
  }

  function fmtMoney(value, currency) {
    var n = num(value);
    return n == null ? '-' : n.toLocaleString('zh-CN', { maximumFractionDigits: 2 }) + currencyLabel(currency || pageCurrency());
  }

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

  function realRating(value) {
    var rating = num(value);
    // Ozon 星级固定在 0–5；大于 5 的数值是评论数或其他统计，绝不能当评分显示。
    return rating != null && rating >= 0 && rating <= 5 ? rating.toLocaleString('zh-CN', { maximumFractionDigits: 2 }) : null;
  }

  function quickPrice(data) {
    var price = num(data && (data.frontPrice != null ? data.frontPrice : (data.minSellerPrice != null ? data.minSellerPrice : data.avgPrice)));
    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',
      'source_url=' + encodeURIComponent(location.href),
      'source_title=' + encodeURIComponent(data.title || '')
    ];
    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-collect" data-collect="current">采集当前变体</button>'
      + '<button class="panda-ozon-action panda-ozon-collect" data-collect="all">采集全部变体</button>'
      + '<button class="panda-ozon-action panda-ozon-source source" data-source-title="' + escapeHtml(data.title || '') + '">1688找货源</button>'
      + '<button class="panda-ozon-action panda-ozon-quick" data-quick-url="' + escapeHtml(quickListHref(data)) + '">一键上货</button>'
      + '<button class="panda-ozon-action panda-ozon-follow follow" data-product-id="' + escapeHtml(currentSku() || sku) + '">复制跟卖SKU</button>'
      + '<button class="panda-ozon-action panda-ozon-select" type="button">加入选品池</button>'
      + '</div>';
  }

  function firstProductImage() {
    var meta = document.querySelector('meta[property="og:image"],meta[name="twitter:image"]');
    var metaImage = meta && meta.getAttribute('content');
    if (/^https?:\/\//i.test(metaImage || '')) return metaImage;
    var selectors = [
      '[data-widget*="webGallery"] img',
      '[data-widget*="webImage"] img',
      '[data-widget*="webProduct"] img',
      'main img'
    ];
    for (var i = 0; i < selectors.length; i++) {
      var images = document.querySelectorAll(selectors[i]);
      for (var j = 0; j < images.length; j++) {
        var src = images[j].currentSrc || images[j].src || images[j].getAttribute('src') || '';
        if (/^https?:\/\//i.test(src) && images[j].naturalWidth >= 180) return src;
      }
    }
    return '';
  }

  function selectionSnapshot(data) {
    data = data || {};
    var sku = String(data.variantId || data.sku || currentSku() || '');
    return {
      source_platform: 'ozon',
      source_url: location.href,
      ozon_product_id: sku,
      sku: sku,
      title: data.title || (document.querySelector('h1') && document.querySelector('h1').innerText) || '',
      image_url: firstProductImage(),
      price: data.frontPrice,
      currency: data.currency,
      rating: data.rating,
      review_count: data.reviews,
      seller_count: data.sellerCount,
      category_name: data.category3 && data.category3 !== '-' ? data.category3 : data.category1,
      weight: data.weight,
      dimensions: data.dimensions,
      raw_snapshot: data
    };
  }

  function offerSku(offer, current) {
    if (!offer || typeof offer !== 'object') return '';
    var directKeys = ['sku', 'product_sku', 'productSku', 'offer_sku', 'offerSku', 'id', 'product_id', 'productId'];
    for (var i = 0; i < directKeys.length; i++) {
      var value = offer[directKeys[i]];
      if (value != null && String(value) && String(value) !== String(current)) return String(value);
    }
    var linkKeys = ['url', 'href', 'link', 'product_url', 'productUrl'];
    for (var j = 0; j < linkKeys.length; j++) {
      var link = String(offer[linkKeys[j]] || '');
      var match = link.match(/-(\d+)(?:[/?#]|$)/);
      if (match && match[1] !== String(current)) return match[1];
    }
    return '';
  }

  function collectOfferSkus(value, current, output, depth) {
    if (!value || depth > 7) return;
    if (Array.isArray(value)) {
      value.forEach(function(item) { collectOfferSkus(item, current, output, depth + 1); });
      return;
    }
    if (typeof value !== 'object') return;
    var sku = offerSku(value, current);
    if (sku && output.indexOf(sku) < 0) output.push(sku);
    ['offers', 'items', 'sellers', 'results', 'products', 'catalog'].forEach(function(key) {
      if (value[key]) collectOfferSkus(value[key], current, output, depth + 1);
    });
  }

  function fetchOtherSellerSku(productId) {
    var current = String(productId || currentSku() || '');
    if (!current) return Promise.reject(new Error('未识别到商品 SKU'));
    if (OFFER_CACHE.has(current)) return OFFER_CACHE.get(current);
    var modalUrl = '/modal/otherOffersFromSellers?product_id=' + encodeURIComponent(current) + '&page_changed=true';
    var request = fetch('/api/entrypoint-api.bx/page/json/v2?url=' + encodeURIComponent(modalUrl), {
      credentials: 'include'
    }).then(function(response) {
      if (!response.ok) throw new Error('读取其他卖家数据失败');
      return response.json();
    }).then(function(payload) {
      var found = [];
      var states = payload && payload.widgetStates ? payload.widgetStates : {};
      Object.keys(states).forEach(function(key) {
        var state = states[key];
        if (typeof state === 'string') {
          try { state = JSON.parse(state); } catch (ignore) { return; }
        }
        collectOfferSkus(state, current, found, 0);
      });
      collectOfferSkus(payload && payload.catalog, current, found, 0);
      return found;
    });
    OFFER_CACHE.set(current, request);
    request.catch(function() { OFFER_CACHE.delete(current); });
    return request;
  }

  function writeClipboard(text) {
    if (navigator.clipboard && navigator.clipboard.writeText) return navigator.clipboard.writeText(text);
    var input = document.createElement('textarea');
    input.value = text;
    input.style.position = 'fixed';
    input.style.opacity = '0';
    document.body.appendChild(input);
    input.select();
    document.execCommand('copy');
    input.remove();
    return Promise.resolve();
  }

  function downloadFollowSkus(skus) {
    var content = skus.join('\n') + '\n';
    var blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
    var url = URL.createObjectURL(blob);
    var link = document.createElement('a');
    link.href = url;
    link.download = 'ozon-follow-skus-' + (currentSku() || 'export') + '.txt';
    document.body.appendChild(link);
    link.click();
    link.remove();
    setTimeout(function() { URL.revokeObjectURL(url); }, 1000);
  }

  function closeOfferDialog() {
    var dialog = document.getElementById('panda-ozon-offer-dialog');
    if (dialog) dialog.remove();
  }

  function openOfferDialog(productId, skus) {
    closeOfferDialog();
    var mask = document.createElement('div');
    mask.id = 'panda-ozon-offer-dialog';
    mask.className = 'panda-ozon-offer-mask';
    var list = (skus || []).map(function(sku) {
      var href = 'https://www.ozon.ru/product/' + encodeURIComponent(sku);
      return '<li><a href="' + href + '" target="_blank" rel="noopener">SKU ' + escapeHtml(sku) + '</a></li>';
    }).join('');
    mask.innerHTML = '<section class="panda-ozon-offer-dialog" role="dialog" aria-modal="true" aria-label="其他卖家 SKU">'
      + '<div class="panda-ozon-offer-head"><span>其他卖家在售 SKU（' + escapeHtml((skus || []).length) + '）</span><button type="button" class="panda-ozon-offer-close" aria-label="关闭">×</button></div>'
      + '<div class="panda-ozon-offer-body"><p>已排除当前商品 SKU。点击编号可在新标签页查看商品。</p><ul class="panda-ozon-offer-list">' + list + '</ul></div>'
      + '<div class="panda-ozon-offer-actions"><button type="button" class="panda-ozon-offer-button secondary panda-ozon-offer-download">下载列表</button><button type="button" class="panda-ozon-offer-button panda-ozon-offer-copyall">复制全部 SKU</button></div>'
      + '</section>';
    mask.dataset.productId = String(productId || '');
    mask.dataset.skus = JSON.stringify(skus || []);
    document.body.appendChild(mask);
  }

  function showOfferDialogLoading(productId) {
    closeOfferDialog();
    var mask = document.createElement('div');
    mask.id = 'panda-ozon-offer-dialog';
    mask.className = 'panda-ozon-offer-mask';
    mask.innerHTML = '<section class="panda-ozon-offer-dialog" role="dialog" aria-modal="true" aria-label="其他卖家 SKU">'
      + '<div class="panda-ozon-offer-head"><span>其他卖家在售 SKU</span><button type="button" class="panda-ozon-offer-close" aria-label="关闭">×</button></div>'
      + '<div class="panda-ozon-offer-body">正在读取其他卖家数据…</div></section>';
    mask.dataset.productId = String(productId || '');
    document.body.appendChild(mask);
  }

  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 normalizeCommissionPercent(value) {
    var rate = num(value);
    if (rate == null) return null;
    if (rate > 100 && rate <= 10000) rate = rate / 100;
    return rate >= 0 && rate <= 100 ? rate : null;
  }

  function findCommissionRate(payload, preferredSchema) {
    var candidates = [];
    var seen = typeof WeakSet === 'function' ? new WeakSet() : null;
    var schema = String(preferredSchema || '').toLowerCase();

    function walk(node, path, depth) {
      if (node == null || depth > 9) return;
      if (typeof node === 'number' || typeof node === 'string') {
        var name = String(path || '').toLowerCase();
        if (!/(commission|комисс|sales?_?percent|sale_percent|fbs[^.]*percent|percent[^.]*fbs)/i.test(name)) return;
        if (/(amount|sum|fee|cost|руб|price|value)/i.test(name)) return;
        var rate = normalizeCommissionPercent(node);
        if (rate == null) return;
        var score = 10;
        if (schema && name.indexOf(schema) >= 0) score += 80;
        if (/rfbs|real.?fbs|fbs/.test(name)) score += 60;
        else if (/sales?_?percent|sale_percent/.test(name)) score += 40;
        else if (/commission|комисс/.test(name)) score += 25;
        candidates.push({ percent: rate, score: score, source: name });
        return;
      }
      if (typeof node !== 'object') return;
      if (seen) {
        if (seen.has(node)) return;
        seen.add(node);
      }
      if (Array.isArray(node)) {
        node.forEach(function(value, index) { walk(value, path + '[' + index + ']', depth + 1); });
        return;
      }
      Object.keys(node).forEach(function(key) {
        walk(node[key], path ? path + '.' + key : key, depth + 1);
      });
    }

    walk(payload, '', 0);
    candidates.sort(function(a, b) { return b.score - a.score; });
    return candidates[0] || null;
  }

  function pickCommission(detail, item, sellerVariant) {
    var list = Array.isArray(detail && detail.commissions) ? detail.commissions : [];
    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];
    if (found) return found;

    // Newer Seller Portal responses often keep only the real percentage in
    // search-variant-model or a nested detail field instead of commissions[].
    var nested = findCommissionRate(sellerVariant || detail, schema);
    return nested ? {
      value: null,
      percent: nested.percent,
      sale_schema: schema || 'FBS',
      source: nested.source
    } : 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 sellerVariant = raw && raw.sellerVariant ? raw.sellerVariant : null;
    var specs = detail && detail.specifications ? detail.specifications : {};
    var commission = pickCommission(detail, item, sellerVariant);
    var currency = currencyCode(item.priceCurrency || item.currency || item.currencyCode || detail.priceCurrency || detail.currency || detail.currency_code) || pageCurrency();
    // seller-prototype 返回的是 Ozon 发布所使用的真实物流规格（mm / g）。
    // 除了生成展示字符串，还保留四个独立数值，供“一键上货”原样传入采集链路。
    var packageLength = firstPositive(specs.length, specs.depth, detail.depth);
    var packageWidth = firstPositive(specs.width, detail.width);
    var packageHeight = firstPositive(specs.height, detail.height);
    var packageWeight = firstPositive(specs.weight, detail.weight);
    var dimensions = [packageLength, packageWidth, packageHeight].filter(function(v) { return 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 || '-',
      currency: currency,
      frontPrice: null,
      frontPriceSource: '',
      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: num(item.avgDeliveryTime) != null ? item.avgDeliveryTime : item.avgDeliveryDays,
      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: packageWeight,
      packageLength: packageLength,
      packageWidth: packageWidth,
      packageHeight: packageHeight,
      packageWeight: packageWeight,
      allowCopy: detail.is_copy_allowed === false ? '否' : '是',
      // Seller count is populated from the public other-offers endpoint.
      // sumItemsInStock/accessibility are stock fields, not seller counts.
      sellerCount: null,
      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: '-',
      currency: extra.currency || pageCurrency(),
      frontPrice: extra.frontPrice || extra.price || null,
      frontPriceSource: extra.frontPriceSource || '',
      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 basePrice = num(base.frontPrice);
    var sellerPrice = num(seller.frontPrice);
    var sourceRank = function(source) {
      return { 'ozon-widget-state': 4, 'ozon-price-dom': 3, 'seo-offer': 1 }[String(source || '')] || 0;
    };
    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;
    // “当前售价”只允许来自页面主价格组件。最低跟卖价和平均价是不同指标，
    // 不能在 Seller 数据返回后覆盖页面真实售价。
    if (sellerPrice != null && (basePrice == null || sourceRank(seller.frontPriceSource) > sourceRank(base.frontPriceSource))) {
      out.frontPrice = sellerPrice;
      out.frontPriceSource = seller.frontPriceSource || '';
    } else {
      out.frontPrice = basePrice;
      out.frontPriceSource = base.frontPriceSource || '';
    }
    out.currency = currencyCode(out.currency) || currencyCode(base.currency) || pageCurrency();
    out.rating = realRating(seller.rating) || realRating(base.rating) || null;
    return out;
  }

  function legacyDetailData(raw, sku) {
    raw = raw || {};
    var dimensions = raw.ptj || [raw.dimL, raw.dimW, raw.dimH].filter(function(value) {
      return value != null && value !== '' && value !== '-';
    }).join('*') || '-';
    return {
      sku: String(raw.sku || sku || ''),
      variantId: String(raw.sku || sku || ''),
      title: raw.title || raw.name || '',
      brand: raw.brand || '-',
      category1: raw.category1 || '-',
      category3: raw.category3 || '-',
      currency: raw.currency || raw.priceCurrency || pageCurrency(),
      frontPrice: null,
      frontPriceSource: '',
      soldCount: raw.sales,
      soldSum: raw.gmv,
      salesDynamics: raw.salesDynamics,
      avgPrice: raw.avgPrice,
      minSellerPrice: raw.minSellerPrice,
      addRate: raw.convTocartPdp != null ? raw.convTocartPdp : raw.pdpToCartConversion,
      views: raw.views != null ? raw.views : raw.sessionCount,
      drr: raw.drr,
      daysWithTrafarets: raw.daysWithTrafarets,
      searchConv: raw.convToCartSearch,
      exposeConv: raw.convViewToOrder,
      exposes: raw.sessionCount,
      promoDays: raw.daysInPromo,
      detailViews: raw.sessionCount,
      avgDeliveryTime: raw.avgDeliveryDays,
      redemptionRate: raw.nullableRedemptionRate,
      promoRevenueShare: raw.promoRevenueShare,
      salesSchema: raw.salesSchema || '-',
      stock: raw.stock,
      createDate: raw.pCreateDate,
      sellerName: raw.sellerName || '-',
      sellerId: raw.sellerId || '-',
      commissionValue: raw.commission,
      commissionPercent: raw.commissionPercent,
      commissionSchema: raw.commissionSchema || '',
      volume: raw.ptj,
      dimensions: dimensions,
      weight: raw.pWeight,
      allowCopy: raw.hasGollowSales == null ? '-' : raw.hasGollowSales,
      sellerCount: raw.sellerCount
    };
  }

  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 readDomMainPrice() {
    if (!PRICE) return null;
    var selectors = [
      '[data-widget="webPrice"]',
      '[data-widget^="webPrice-"]',
      '[data-widget="skuPrice"]',
      '[data-widget^="skuPrice-"]'
    ];
    for (var i = 0; i < selectors.length; i++) {
      var widget = document.querySelector(selectors[i]);
      if (!widget) continue;
      var stateValues = [];
      if (widget.hasAttribute && widget.hasAttribute('data-state')) stateValues.push(widget.getAttribute('data-state'));
      widget.querySelectorAll('[data-state]').forEach(function(node) { stateValues.push(node.getAttribute('data-state')); });
      var fromState = PRICE.fromDataStates(stateValues);
      if (fromState) {
        fromState.source = 'ozon-widget-state';
        return fromState;
      }
      var fromText = PRICE.fromPriceText(widget.innerText || widget.textContent || '');
      if (fromText) {
        fromText.source = 'ozon-price-dom';
        return fromText;
      }
    }
    return null;
  }

  function readPageBasics(sku) {
    var title = getText(['h1', '[data-widget*="webProductHeading"]', '[data-widget*="webProductTitle"]']);
    var mainPrice = readDomMainPrice();
    var priceText = mainPrice ? mainPrice.raw : '';
    var ratingText = document.body ? (document.body.innerText || '') : '';
    var rating = '';
    document.querySelectorAll('script[type="application/ld+json"]').forEach(function(node) {
      if (rating) return;
      try {
        var json = JSON.parse(node.textContent || '{}');
        var source = Array.isArray(json) ? json : [json];
        source.forEach(function(item) { if (!rating && item && item.aggregateRating) rating = realRating(item.aggregateRating.ratingValue) || ''; });
      } catch (ignore) {}
    });
    if (!rating) {
      // 仅接受 0–5 的星级，再读取紧随其后的评论数；避免把“22,974 отзывов”中的 22 当评分。
      rating = ((ratingText.match(/\b([0-5](?:[.,]\d+)?)\s*(?:★|⭐|рейтинг|оценк)/i) || [])[1]
        || (ratingText.match(/\b([0-5](?:[.,]\d+)?)\s+[\d\s]+\s*(?:отзыв|отзыва|отзывов)/i) || [])[1] || '');
      rating = realRating(rating) || '';
    }
    var reviews = (ratingText.match(/(\d[\d\s]*)\s*(?:отзыв|отзыва|отзывов)/i) || [])[1] || '';
    return emptyData(sku, {
      title: title,
      frontPrice: mainPrice ? mainPrice.price : null,
      frontPriceSource: mainPrice ? mainPrice.source : '',
      currency: (mainPrice && mainPrice.currency) || currencyCode(priceText) || pageCurrency(),
      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 widgetPrice = PRICE && data ? PRICE.fromWidgetStates(data.widgetStates) : null;
        var script = data && data.seo && data.seo.script && data.seo.script[0] && data.seo.script[0].innerHTML;
        if (!script && !widgetPrice) return null;
        var json = script ? 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,
          // SEO offers.price 在部分商品会返回“买 1 卢布”的促销门槛，不是售价。
          // 当前售价只接收 webPrice / skuPrice 的 cardPrice 或 price。
          frontPrice: widgetPrice ? widgetPrice.price : null,
          frontPriceSource: widgetPrice ? 'ozon-widget-state' : '',
          currency: (widgetPrice && widgetPrice.currency) || currencyCode(offers.currency || offers.priceCurrency) || pageCurrency(),
          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 = enqueueInsightRequest(function() { return 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 sellerOffersCell(data) {
    var productId = currentSku() || data.variantId || data.sku || '';
    return '<div class="panda-ozon-cell"><div class="panda-ozon-label">销售卖家数</div><div class="panda-ozon-seller-value"><span data-seller-count="' + escapeHtml(productId) + '">'
      + escapeHtml(data.sellerCount == null ? '读取中' : fmtInt(data.sellerCount)) + '</span><button type="button" class="panda-ozon-view-offers" data-product-id="' + escapeHtml(productId) + '">查看</button></div></div>';
  }

  function commissionText(data) {
    var percent = normalizeCommissionPercent(data && data.commissionPercent);
    var amount = num(data && data.commissionValue);
    var price = num(data && data.frontPrice);
    if (amount == null && percent != null && price != null) amount = price * percent / 100;
    if (amount == null && percent == null) return '-';
    var schema = (data && data.commissionSchema) || '佣金';
    if (amount == null) return schema + ' ' + fmtPct(percent);
    return '-' + fmtMoney(amount, data.currency) + ' (' + schema + ' ' + fmtPct(percent) + ')';
  }

  function syncSellerCount(card, data) {
    if (!card || !data) return;
    var productId = String(currentSku() || data.variantId || data.sku || '');
    var countEl = card.querySelector('[data-seller-count]');
    if (!productId || !countEl) return;
    fetchOtherSellerSku(productId).then(function(skus) {
      // card.dataset.sku is the public Ozon product id from the URL. Seller
      // analytics may return a different internal SKU/variant id.
      if (!card.isConnected || String(card.dataset.sku || '') !== productId) return;
      var total = (Array.isArray(skus) ? skus.length : 0) + 1;
      data.sellerCount = total;
      countEl = card.querySelector('[data-seller-count]');
      if (countEl) {
        countEl.textContent = fmtInt(total);
        countEl.title = '包含当前商品卖家，已按不同在售 SKU 去重';
      }
      var cached = CACHE.get(productId);
      if (cached) cached.sellerCount = total;
    }).catch(function(error) {
      countEl = card.querySelector('[data-seller-count]');
      if (countEl) {
        countEl.textContent = '-';
        countEl.title = error && error.message ? error.message : '卖家数量读取失败';
      }
    });
  }

  function detailHtml(data, statusText) {
    var commission = commissionText(data);
    var grid = [
      gridCell('当前售价', fmtMoney(data.frontPrice, data.currency), 'dark'),
      gridCell('评分', data.rating || '-'),
      gridCell('评论数', fmtInt(data.reviews)),
      gridCell('月销量', fmtInt(data.soldCount)),
      gridCell('月销售额', fmtMoney(data.soldSum, data.currency)),
      gridCell('月销售变化', fmtPct(data.salesDynamics), clsByNumber(data.salesDynamics)),
      gridCell('平均价格', fmtMoney(data.avgPrice, data.currency), 'dark'),
      gridCell('最低售价', fmtMoney(data.minSellerPrice, data.currency), '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('平均运输时间', fmtDeliveryDays(data.avgDeliveryTime)),
      gridCell('配送方式', data.salesSchema),
      sellerOffersCell(data),
      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">熊猫ERP</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 = commissionText(data);
    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('当前售价', fmtMoney(data.frontPrice, data.currency))
      + row('评分', data.rating || '-')
      + row('评论数', fmtInt(data.reviews))
      + row('出售时间', fmtDate(data.createDate))
      + row('一级类目', data.category1)
      + row('三级类目', data.category3)
      + row('30天销量', fmtInt(data.soldCount))
      + row('30天销售额', fmtMoney(data.soldSum, data.currency))
      + row('30天销售变化', fmtPct(data.salesDynamics), clsByNumber(data.salesDynamics))
      + row('平均售价', fmtMoney(data.avgPrice, data.currency))
      + row('最低售价', fmtMoney(data.minSellerPrice, data.currency))
      + 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('平均运输时间', fmtDeliveryDays(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.__pandaSelectionData = baseData;
    card.innerHTML = detailHtml(baseData, '正在读取后台分析数据');

    // 与旧版保持同一挂载位置：商品右侧 webSale 信息区下方。
    // 该位置会随页面自然滚动，不使用悬浮固定。
    var legacyMount = document.querySelector("#layoutPage div[data-widget='webSale']");
    if (legacyMount) {
      // Ozon 会重绘 webSale 的内部内容；将卡片放在同级容器，保留旧版右侧位置
      // 的同时，不会随购买区内部刷新而被删除。
      var host = document.getElementById('panda-ozon-detail-host');
      if (!host || host.parentElement !== legacyMount.parentElement) {
        if (host) host.remove();
        host = document.createElement('div');
        host.id = 'panda-ozon-detail-host';
        host.className = 'panda-ozon-detail-host';
        legacyMount.insertAdjacentElement('afterend', host);
      }
      host.appendChild(card);
      syncSellerCount(card, baseData);
    } else {
      // 新版 Ozon 会晚于 content script 生成右侧区域。等待旧版容器出现后再插入，
      // 不能先放到正文末尾，否则卡片会落在首屏以外。
      setTimeout(mountDetail, 500);
      return;
    }

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

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

  // 由旧脚本提供的接口数据比页面解析更完整。收到后覆盖临时/后台数据，
  // 并确保页面只留下这一张新版卡片。
  window.addEventListener('panda:ozon-data', function(event) {
    if (!isProductPage()) return;
    var raw = event && event.detail && event.detail.productData;
    if (!raw) return;
    var sku = String(raw.sku || currentSku() || '');
    var card = document.getElementById('panda-ozon-detail-card');
    if (!card || card.dataset.sku !== sku) {
      mountDetail();
      card = document.getElementById('panda-ozon-detail-card');
    }
    if (!card) return;
    var pageData = readPageBasics(sku);
    card.dataset.sku = sku;
    var mergedLegacy = mergeData(pageData, legacyDetailData(raw, sku));
    card.__pandaSelectionData = mergedLegacy;
    card.innerHTML = detailHtml(mergedLegacy);
    syncSellerCount(card, mergedLegacy);
    document.querySelectorAll('.hq_main').forEach(function(node) { node.remove(); });
  });

  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*(₽|руб\.?|Р|₸|тенге|Br\.?|бел\.?\s*руб|¥|USD|\$|€)/i);
    return emptyData(sku, {
      title: text.split('\n').filter(Boolean).slice(0, 2).join(' / '),
      frontPrice: priceMatch ? priceMatch[1] : null,
      price: priceMatch ? priceMatch[1] : null,
      currency: priceMatch ? currencyCode(priceMatch[2]) : pageCurrency()
    });
  }

  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 offerDialog = event.target.closest('#panda-ozon-offer-dialog');
    if (offerDialog) {
      var offerSkus = [];
      try { offerSkus = JSON.parse(offerDialog.dataset.skus || '[]'); } catch (ignore) { offerSkus = []; }
      if (event.target === offerDialog || event.target.closest('.panda-ozon-offer-close')) {
        event.preventDefault();
        closeOfferDialog();
        return;
      }
      var offerCopy = event.target.closest('.panda-ozon-offer-copyall');
      if (offerCopy) {
        event.preventDefault();
        if (!offerSkus.length) return;
        offerCopy.disabled = true;
        writeClipboard(offerSkus.join('\n')).then(function() {
          offerCopy.textContent = '已复制 ' + offerSkus.length + ' 个 SKU';
        }).catch(function() {
          offerCopy.textContent = '复制失败，请重试';
        }).then(function() {
          setTimeout(function() {
            offerCopy.disabled = false;
            offerCopy.textContent = '复制全部 SKU';
          }, 1600);
        });
        return;
      }
      var offerDownload = event.target.closest('.panda-ozon-offer-download');
      if (offerDownload) {
        event.preventDefault();
        if (!offerSkus.length) return;
        downloadFollowSkus(offerSkus);
        offerDownload.textContent = '已下载';
        setTimeout(function() { offerDownload.textContent = '下载列表'; }, 1200);
        return;
      }
    }

    var viewOffers = event.target.closest('.panda-ozon-view-offers');
    if (viewOffers) {
      event.preventDefault();
      event.stopPropagation();
      if (viewOffers.disabled) return;
      var productId = viewOffers.dataset.productId || currentSku();
      viewOffers.disabled = true;
      showOfferDialogLoading(productId);
      fetchOtherSellerSku(productId).then(function(skus) {
        openOfferDialog(productId, skus);
      }).catch(function(error) {
        closeOfferDialog();
        var message = error && error.message ? error.message : '读取其他卖家数据失败';
        var mask = document.createElement('div');
        mask.id = 'panda-ozon-offer-dialog';
        mask.className = 'panda-ozon-offer-mask';
        mask.innerHTML = '<section class="panda-ozon-offer-dialog" role="dialog" aria-modal="true"><div class="panda-ozon-offer-head"><span>其他卖家在售 SKU</span><button type="button" class="panda-ozon-offer-close" aria-label="关闭">×</button></div><div class="panda-ozon-offer-body">' + escapeHtml(message) + '</div></section>';
        document.body.appendChild(mask);
      }).then(function() {
        viewOffers.disabled = false;
      });
      return;
    }

    var follow = event.target.closest('.panda-ozon-follow');
    if (follow) {
      event.preventDefault();
      event.stopPropagation();
      if (follow.disabled) return;
      var originalFollowText = '复制跟卖SKU';
      follow.disabled = true;
      follow.textContent = '正在获取…';
      fetchOtherSellerSku(follow.dataset.productId).then(function(skus) {
        if (skus.length > 20) {
          downloadFollowSkus(skus);
          follow.textContent = '已下载 ' + skus.length + ' 个SKU';
          return;
        }
        return writeClipboard(skus.join('\n')).then(function() {
          follow.textContent = '已复制 ' + skus.length + ' 个SKU';
        });
      }).catch(function(error) {
        follow.textContent = error && error.message ? error.message : '获取失败';
      }).then(function() {
        setTimeout(function() {
          follow.disabled = false;
          follow.textContent = originalFollowText;
        }, 1800);
      });
      return;
    }
    var copy = event.target.closest('.panda-ozon-copy');
    if (copy) {
      event.preventDefault();
      event.stopPropagation();
      var text = copy.dataset.copy || '';
      if (!text) {
        copy.textContent = '未识别 SKU';
        setTimeout(function() { copy.textContent = copy.classList.contains('panda-ozon-action') ? '复制SKU' : '复制'; }, 1200);
        return;
      }
      copy.disabled = true;
      writeClipboard(text).then(function() {
        copy.textContent = '已复制';
      }).catch(function() {
        copy.textContent = '复制失败';
      }).then(function() {
        setTimeout(function() {
          copy.disabled = false;
          copy.textContent = copy.classList.contains('panda-ozon-action') ? '复制SKU' : '复制';
        }, 1000);
      });
      return;
    }
    var quick = event.target.closest('.panda-ozon-quick');
    if (quick) {
      event.preventDefault();
      event.stopPropagation();
      var href = quick.dataset.quickUrl || QUICK_LIST_URL;
      var originalQuickText = quick.textContent;
      quick.disabled = true;
      quick.textContent = '正在采集商品…';
      // 一键上货必须先保存完整商品资料（图片、规格、货源地址），
      // 不能只把 SKU/价格带到后台，否则无法生成真实 Ozon 发布载荷。
      if (window.chrome && chrome.runtime && chrome.runtime.sendMessage) {
        var quickCard = quick.closest('.panda-ozon-card');
        var quickSku = String((quickCard && quickCard.dataset.sku) || currentSku() || '');
        var sendQuickCollection = function(insightData) {
          var packageDimensions = insightData ? {
            length: insightData.packageLength,
            width: insightData.packageWidth,
            height: insightData.packageHeight,
            weight: insightData.packageWeight,
            unit: 'mm',
            dimension_unit: 'mm',
            weight_unit: 'g',
            source: 'ozon-seller-prototype'
          } : null;
          chrome.runtime.sendMessage({
          Type: 'CollectionGoodsku',
          IsVerifyDuplicate: true,
          sourceUrl: location.href,
            openQuickListAfterCollect: true,
            sourceSku: quickSku,
            packageDimensions: packageDimensions
          }, function() {
            if (chrome.runtime.lastError) {
              quick.textContent = '采集提交失败';
              setTimeout(function() {
                quick.disabled = false;
                quick.textContent = originalQuickText;
              }, 1800);
              return;
            }
            // 采集器先确认接收，再异步写入完整图片和规格；等待落库后再打开上货页。
            setTimeout(function() {
              quick.textContent = '采集完成，打开上货页…';
              window.open(href, '_blank', 'noopener');
              quick.disabled = false;
              quick.textContent = originalQuickText;
            }, 4000);
          });
        };
        if (quickSku && !CACHE.has(quickSku)) {
          requestInsights(quickSku).then(sendQuickCollection).catch(function() { sendQuickCollection(null); });
        } else {
          sendQuickCollection(CACHE.get(quickSku) || null);
        }
      } else {
        quick.textContent = '请在插件环境中使用';
        setTimeout(function() {
          quick.disabled = false;
          quick.textContent = originalQuickText;
        }, 1800);
      }
      return;
    }
    var select = event.target.closest('.panda-ozon-select');
    if (select) {
      event.preventDefault();
      event.stopPropagation();
      if (select.disabled) return;
      var selectCard = select.closest('.panda-ozon-card');
      var selectSku = String((selectCard && selectCard.dataset.sku) || currentSku() || '');
      var originalSelectText = select.textContent;
      select.disabled = true;
      select.textContent = '正在保存…';
      var sendSelection = function(data) {
        chrome.runtime.sendMessage({ type: 'panda:saveProductSelection', snapshot: selectionSnapshot(data) }, function(response) {
          if (chrome.runtime.lastError || !response || !response.success) {
            select.textContent = response && response.message ? response.message : '加入失败';
            if (response && response.auth_required) {
              setTimeout(function() { window.open('https://sczfai.com/login.html', '_blank', 'noopener'); }, 600);
            }
          } else {
            select.classList.add('is-saved');
            select.textContent = response.created ? '已加入选品池' : '选品快照已更新';
          }
          setTimeout(function() {
            select.disabled = false;
            if (!select.classList.contains('is-saved')) select.textContent = originalSelectText;
          }, 2200);
        });
      };
      var renderedSelectionData = selectCard && selectCard.__pandaSelectionData;
      if (renderedSelectionData) sendSelection(renderedSelectionData);
      else if (selectSku && !CACHE.has(selectSku)) requestInsights(selectSku).then(function(data) { sendSelection(mergeData(readPageBasics(selectSku), data)); }).catch(function() { sendSelection(readPageBasics(selectSku)); });
      else sendSelection(mergeData(readPageBasics(selectSku), CACHE.get(selectSku) || {}));
      return;
    }
    var source = event.target.closest('.panda-ozon-source');
    if (source) {
      event.preventDefault();
      event.stopPropagation();
      var keyword = source.dataset.sourceTitle || document.querySelector('h1')?.innerText || '';
      window.open('https://s.1688.com/selloffer/offer_search.htm?keywords=' + encodeURIComponent(keyword), '_blank', 'noopener');
      return;
    }
    var collect = event.target.closest('.panda-ozon-collect');
    if (collect) {
      event.preventDefault();
      event.stopPropagation();
      if (!window.chrome || !chrome.runtime || !chrome.runtime.sendMessage) return;
      var allVariants = collect.dataset.collect === 'all';
      var originalText = collect.textContent;
      collect.disabled = true;
      collect.textContent = '正在提交…';
      chrome.runtime.sendMessage({
        // “全部变体”走 SKU 合并采集接口：源商品本身与 SkuLinks 内全部变体
        // 在同一份 skulist 数据中保存；旧 CollectionGoods 会走产品旧接口并在 Ozon 页报服务异常。
        Type: allVariants ? 'CollectionOzonAllVariants' : 'CollectionGoodsku',
        IsVerifyDuplicate: true,
        sourceUrl: location.href
      }, function() {
        collect.textContent = chrome.runtime.lastError ? '采集失败' : '已提交采集';
        setTimeout(function() {
          collect.disabled = false;
          collect.textContent = originalText;
        }, 1800);
      });
      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);
          syncSellerCount(card, data);
        }
      }).catch(function(error) {
        if (card) card.innerHTML = errorHtml(error.message, sku);
      });
    }
  }, true);

  if (TEST_MODE) {
    window.__PANDA_OZON_INSIGHTS_TEST_API__ = {
      fmtDeliveryDays: fmtDeliveryDays,
      findCommissionRate: findCommissionRate,
      commissionText: commissionText,
      normalize: normalize
    };
  }

  var lastUrl = location.href;
  setInterval(function() {
    if (location.href !== lastUrl) {
      lastUrl = location.href;
      setTimeout(boot, 600);
    } else {
      // Ozon 会在首屏完成后重绘 webSale 区域，已挂载的卡片会被替换掉；
      // 持续确认详情卡仍在页面中，丢失时从缓存数据快速恢复。
      mountDetail();
      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(function() {
      mountDetail();
      mountListCards();
    }, 500);
  });
  if (document.body) observer.observe(document.body, { childList: true, subtree: true });
})();
