/**
 * 熊猫链接采集通用工具
 * 供 1688 / 淘宝 / 拼多多内容脚本复用。
 */
(function() {
  'use strict';

  if (window.QYDZScrape) return;

  var AI_MODE_KEY = '__qydz_ai_link_scrape';
  var AI_MODE_TTL = 5 * 60 * 1000;

  function markAiLinkScrapeMode() {
    try {
      if (location.href.indexOf('_qydz_scrape=1') !== -1) {
        sessionStorage.setItem(AI_MODE_KEY, String(Date.now()));
        window.__QYDZ_AI_LINK_SCRAPE__ = true;
      } else {
        var ts = parseInt(sessionStorage.getItem(AI_MODE_KEY) || '0', 10);
        window.__QYDZ_AI_LINK_SCRAPE__ = Boolean(ts && Date.now() - ts < AI_MODE_TTL);
      }
    } catch(e) {
      window.__QYDZ_AI_LINK_SCRAPE__ = location.href.indexOf('_qydz_scrape=1') !== -1;
    }
    return window.__QYDZ_AI_LINK_SCRAPE__;
  }

  function cleanText(value, maxLen) {
    var text = String(value || '').replace(/\u00a0/g, ' ').replace(/\s+/g, ' ').trim();
    return maxLen ? text.substring(0, maxLen) : text;
  }

  function toAbsoluteUrl(url) {
    var src = String(url || '').trim();
    if (!src || src.indexOf('data:') === 0 || src.indexOf('blob:') === 0) return '';
    if (src.indexOf('//') === 0) src = location.protocol + src;
    if (/^https?:\/\//i.test(src)) return src;
    try { return new URL(src, location.href).href; } catch(e) { return ''; }
  }

  function normalizeImageUrl(url) {
    var src = toAbsoluteUrl(url);
    if (!src) return '';
    if (/sprite|icon|logo|avatar|placeholder|blank|loading/i.test(src)) return '';
    return src
      .replace(/_(?:\d+x\d+|sum)\.(jpg|jpeg|png|webp)/i, '.$1')
      .replace(/\.(?:\d+x\d+)\.(jpg|jpeg|png|webp)/i, '.$1')
      .split('?')[0];
  }

  function pushUnique(list, value) {
    if (value && list.indexOf(value) === -1) list.push(value);
  }

  function imageFromSrcset(srcset) {
    var text = String(srcset || '').trim();
    if (!text) return '';
    var best = text.split(',').map(function(item) {
      var parts = item.trim().split(/\s+/);
      return { url: parts[0], weight: parseFloat(parts[1]) || 1 };
    }).sort(function(a, b) { return b.weight - a.weight; })[0];
    return best ? best.url : '';
  }

  function collectImages(selectors, limit) {
    var images = [];
    (selectors || ['img']).forEach(function(selector) {
      document.querySelectorAll(selector).forEach(function(img) {
        var src = img.currentSrc ||
          img.getAttribute('src') ||
          img.getAttribute('data-src') ||
          img.getAttribute('data-lazy-src') ||
          img.getAttribute('data-ks-lazyload') ||
          img.getAttribute('data-img') ||
          imageFromSrcset(img.getAttribute('srcset'));
        src = normalizeImageUrl(src);
        if (!src) return;
        var w = img.naturalWidth || img.width || 0;
        var h = img.naturalHeight || img.height || 0;
        if ((w && w < 60) || (h && h < 60)) return;
        pushUnique(images, src);
      });
    });
    return images.slice(0, limit || 30);
  }

  function addProp(props, key, value) {
    var k = cleanText(key, 80).replace(/^[\s:：]+|[\s:：]+$/g, '');
    var v = cleanText(value, 200).replace(/^[\s:：]+|[\s:：]+$/g, '');
    if (!k || !v || k === v) return;
    if (/价格|优惠|购买|收藏|客服|登录|评价|销量|发货|配送|保障|服务|数量/.test(k)) return;
    if (v.length > 200 || k.length > 80) return;
    if (!props.some(function(p) { return p.key === k && p.value === v; })) props.push({ key: k, value: v });
  }

  function parsePropElement(el, props) {
    if (!el) return;
    var dt = el.querySelector('dt');
    var dd = el.querySelector('dd');
    if (dt && dd) addProp(props, dt.textContent, dd.textContent);

    var cells = el.querySelectorAll('td,th');
    if (cells.length >= 2) addProp(props, cells[0].textContent, cells[1].textContent);

    var label = el.querySelector('[class*="label"],[class*="Label"],[class*="name"],[class*="Name"],[class*="key"],[class*="Key"],.name,.label');
    var value = el.querySelector('[class*="value"],[class*="Value"],[class*="text"],[class*="Text"],[class*="content"],[class*="Content"],.value,.text');
    if (label && value && label !== value) addProp(props, label.textContent, value.textContent);

    var text = cleanText(el.textContent, 260);
    var match = text.match(/^([^:：]{1,40})[:：]\s*(.{1,200})$/);
    if (match) addProp(props, match[1], match[2]);
  }

  function collectProps(selectors, limit) {
    var props = [];
    (selectors || []).forEach(function(selector) {
      document.querySelectorAll(selector).forEach(function(el) {
        parsePropElement(el, props);
      });
    });
    return props.slice(0, limit || 80);
  }

  function collectDescription(selectors, limit) {
    var chunks = [];
    var seen = {};
    (selectors || []).forEach(function(selector) {
      document.querySelectorAll(selector).forEach(function(el) {
        var text = cleanText(el.innerText || el.textContent, 1200);
        if (!text || text.length < 8) return;
        if (/登录|注册|购物车|收藏|联系客服/.test(text) && text.length < 80) return;
        if (!seen[text]) {
          seen[text] = true;
          chunks.push(text);
        }
      });
    });
    var meta = document.querySelector('meta[name="description"],meta[property="og:description"]');
    if (meta) {
      var m = cleanText(meta.getAttribute('content'), 500);
      if (m && !seen[m]) chunks.unshift(m);
    }
    return cleanText(chunks.join('。'), limit || 2000);
  }

  function collectJsonText(patterns) {
    var chunks = [];
    document.querySelectorAll('script').forEach(function(script) {
      var text = script.textContent || '';
      patterns.forEach(function(pattern) {
        var match = text.match(pattern);
        if (match && match[1]) chunks.push(cleanText(match[1].replace(/\\n/g, ' '), 1000));
      });
    });
    return cleanText(chunks.join('。'), 2000);
  }

  function buildKeywords(title, props, description) {
    var stop = {'商品':1,'新款':1,'厂家':1,'批发':1,'淘宝':1,'天猫':1,'拼多多':1,'1688':1};
    var text = [title, description].concat((props || []).map(function(p) { return p.key + ' ' + p.value; })).join(' ');
    var words = text.match(/[a-zA-Z0-9\u4e00-\u9fa5]{2,}/g) || [];
    var result = [];
    words.forEach(function(w) {
      w = cleanText(w, 30);
      if (w && !stop[w] && result.indexOf(w) === -1) result.push(w);
    });
    return result.slice(0, 18);
  }

  function buildSellingPoints(title, props, description) {
    var points = [];
    (props || []).slice(0, 8).forEach(function(p) { points.push(p.key + ': ' + p.value); });
    if (description) {
      description.split(/[。；;.!?？\n]/).forEach(function(part) {
        var text = cleanText(part, 120);
        if (text.length >= 6 && points.indexOf(text) === -1 && points.length < 10) points.push(text);
      });
    }
    if (!points.length && title) points.push(title);
    return points.slice(0, 10);
  }

  function enrich(info, options) {
    options = options || {};
    info.images = info.images || [];
    collectImages(options.imageSelectors || [], 30).forEach(function(src) { pushUnique(info.images, src); });
    if (!info.image && info.images.length) info.image = info.images[0];

    var extraProps = collectProps(options.propSelectors || [], 80);
    info.props = info.props || [];
    extraProps.forEach(function(prop) { addProp(info.props, prop.key, prop.value); });

    var description = collectDescription(options.descriptionSelectors || [], 2000);
    if (!description && options.jsonDescriptionPatterns) description = collectJsonText(options.jsonDescriptionPatterns);
    info.description = cleanText(info.description || description, 2000);
    info.keywords = buildKeywords(info.name, info.props, info.description);
    info.selling_points = buildSellingPoints(info.name, info.props, info.description);
    return info;
  }

  window.QYDZScrape = {
    isAiLinkScrapeMode: markAiLinkScrapeMode,
    cleanText: cleanText,
    normalizeImageUrl: normalizeImageUrl,
    pushUnique: pushUnique,
    addProp: addProp,
    collectImages: collectImages,
    collectProps: collectProps,
    collectDescription: collectDescription,
    enrich: enrich,
    buildKeywords: buildKeywords,
    buildSellingPoints: buildSellingPoints
  };

  markAiLinkScrapeMode();
})();
