/**
 * 拼多多产品页面采集脚本
 */
(function() {
  'use strict';

  if (!location.href.includes('yangkeduo.com') && !location.href.includes('pinduoduo.com') && !location.href.includes('pifa.pinduoduo.com')) {
    return;
  }

  console.log('🛒 [熊猫] 拼多多采集脚本已加载:', location.href);
  var U = window.QYDZScrape || {
    cleanText: function(v, n) { var t = String(v || '').replace(/\s+/g, ' ').trim(); return n ? t.substring(0, n) : t; },
    normalizeImageUrl: function(v) { return String(v || '').split('?')[0]; },
    pushUnique: function(list, v) { if (v && list.indexOf(v) === -1) list.push(v); },
    addProp: function(list, k, v) { if (k && v) list.push({ key: String(k).trim(), value: String(v).trim() }); },
    enrich: function(info) { return info; },
    buildKeywords: function() { return []; },
    buildSellingPoints: function(title) { return title ? [title] : []; },
    isAiLinkScrapeMode: function() { return location.href.indexOf('_qydz_scrape=1') !== -1; }
  };

  function showToast(msg, bgColor) {
    var el = document.createElement('div');
    el.style.cssText = 'position:fixed;top:20px;right:20px;z-index:999999;background:' + (bgColor || '#e02e24') + ';color:#fff;padding:12px 24px;border-radius:8px;font-size:14px;font-family:Microsoft YaHei,sans-serif;box-shadow:0 6px 20px rgba(0,0,0,.2);transition:opacity .3s;max-width:360px;font-weight:500';
    el.textContent = msg;
    document.body.appendChild(el);
    setTimeout(function() { el.style.opacity = '0'; setTimeout(function() { el.remove(); }, 300); }, 3000);
  }

  function addFloatingButton() {
    if (document.getElementById('qydz-collect-btn')) return;
    var btn = document.createElement('div');
    btn.id = 'qydz-collect-btn';
    var pandaIcon = '';
    try { pandaIcon = '<img src="' + chrome.runtime.getURL('img/icon_16.png') + '" alt="" style="width:18px;height:18px;border-radius:4px;vertical-align:-4px;margin-right:6px;">'; } catch (e) {}
    btn.innerHTML = pandaIcon + '熊猫';
    btn.style.cssText = 'position:fixed;bottom:30px;right:30px;z-index:999999;background:linear-gradient(135deg,#e02e24,#c0392b);color:#fff;padding:12px 20px;border-radius:50px;font-size:15px;font-family:Microsoft YaHei,sans-serif;cursor:pointer;box-shadow:0 4px 15px rgba(224,46,36,.4);transition:all .3s;font-weight:600';
    btn.onmouseover = function(){ this.style.transform = 'translateY(-2px)'; };
    btn.onmouseout = function(){ this.style.transform = ''; };
    btn.onclick = function() {
      showToast('⏳ 正在采集...', '#e02e24');
      var info = extractProductInfo();
      if (info.name && info.name.length >= 2) sendToServer(info);
      else showToast('❌ 未能提取到商品信息', '#e74c3c');
    };
    document.body.appendChild(btn);
  }

  function extractProductInfo() {
    var info = { name: '', price: '', image: '', images: [], platform: 'pdd', url: location.href, sku: '', props: [], description: '', selling_points: [], keywords: [] };

    try {
      var scripts = document.querySelectorAll('script');
      for (var i = 0; i < scripts.length; i++) {
        var text = scripts[i].textContent || scripts[i].innerHTML || '';
        if (text.indexOf('window.rawData=') !== -1) {
          var m = text.match(/window\.rawData\s*=\s*(\{.+?\});/s);
          if (m) {
            try {
              var d = JSON.parse(m[1]);
              if (d.goods) d = d.goods;
              if (d.goodsName) info.name = d.goodsName.trim();
              if (d.goodsDesc) {
                info.name = info.name || d.goodsDesc.trim();
                info.description = U.cleanText(d.goodsDesc, 2000);
              }
              if (d.minGroupPrice) info.price = '¥' + (String(d.minGroupPrice / 100) || '0');
              if (d.maxGroupPrice && d.maxGroupPrice > d.minGroupPrice) {
                info.price = '¥' + (d.minGroupPrice / 100).toFixed(2) + ' - ¥' + (d.maxGroupPrice / 100).toFixed(2);
              }
              if (d.topGallery && Array.isArray(d.topGallery)) {
                d.topGallery.forEach(function(img) {
                  var url = U.normalizeImageUrl(img.url || img.preview || img);
                  if (url) U.pushUnique(info.images, url);
                });
                if (info.images.length) info.image = info.images[0];
              }
              if (d.detailGallery && Array.isArray(d.detailGallery)) {
                d.detailGallery.forEach(function(img) {
                  var url = U.normalizeImageUrl(img.url || img.preview || img);
                  if (url) U.pushUnique(info.images, url);
                });
              }
              if (d.goodsID || d.goodsId) info.sku = 'PDD-' + (d.goodsID || d.goodsId);
              if (d.skuList) {
                d.skuList.forEach(function(sku) {
                  if (sku.specs) U.addProp(info.props, '规格', Array.isArray(sku.specs) ? sku.specs.join('/') : sku.specs);
                  if (sku.thumbUrl) U.pushUnique(info.images, U.normalizeImageUrl(sku.thumbUrl));
                });
              }
              var attrs = d.goodsProperty || d.goodsPropertyList || d.properties || d.params || d.attrs;
              if (Array.isArray(attrs)) {
                attrs.forEach(function(attr) {
                  U.addProp(info.props, attr.key || attr.name || attr.pname || attr.title, attr.value || attr.vname || attr.text);
                });
              } else if (attrs && typeof attrs === 'object') {
                Object.keys(attrs).forEach(function(key) { U.addProp(info.props, key, attrs[key]); });
              }
              if (info.name) break;
            } catch(e) {}
          }
        }
      }
    } catch(e) {}

    if (!info.name) {
      var titleEl = document.querySelector('.goods-name') || document.querySelector('[class*="goods-name"]') || document.querySelector('.goods-title') || document.querySelector('[class*="title"] h1') || document.querySelector('h1') || document.querySelector('[data-testid="goods-title"]');
      if (titleEl) info.name = titleEl.textContent.trim().replace(/\s+/g, ' ');
    }
    if (!info.name) { var t = document.title || ''; info.name = t.replace(/[——\-–].*$/, '').replace(/拼多多/g, '').trim(); if (info.name.length < 3) info.name = ''; }
    if (!info.price) {
      var priceEl = document.querySelector('[class*="price"] [class*="current"], .goods-price, [class*="Price"] [class*="current"], .price, [class*="goods-price"]');
      if (priceEl) { var raw = priceEl.textContent.replace(/[^\d.]/g, ''); if (raw && parseFloat(raw) > 0) info.price = '¥' + parseFloat(raw).toFixed(2); }
    }
    if (!info.image) {
      var imgs = document.querySelectorAll('.goods-image img, [class*="gallery"] img, .swiper-slide img, [class*="banner"] img');
      for (var j = 0; j < imgs.length; j++) { var src = imgs[j].getAttribute('src') || imgs[j].getAttribute('data-src') || ''; if (src && src.startsWith('http') && !src.includes('data:image') && !src.includes('icon')) { src = src.split('?')[0]; if (!info.image) info.image = src; if (info.images.indexOf(src) === -1) info.images.push(src); } }
    }
    U.enrich(info, {
      imageSelectors: [
        '.goods-image img',
        '[class*="gallery"] img',
        '.swiper-slide img',
        '[class*="banner"] img',
        '[class*="main"] img',
        'img[src*="pinduoduo.com"]',
        'img[src*="pddpic.com"]'
      ],
      propSelectors: [
        '[class*="sku"] [class*="item"]',
        '[class*="spec"] [class*="item"]',
        '[class*="attribute"] li',
        '[class*="property"] li',
        '[class*="param"] li',
        '[class*="goods"] [class*="property"]',
        'table tr'
      ],
      descriptionSelectors: [
        '.goods-detail',
        '.goods-desc',
        '[class*="goods-desc"]',
        '[class*="description"]',
        '[class*="Description"]',
        '[class*="detail"]'
      ],
      jsonDescriptionPatterns: [
        /"goodsDesc"\s*:\s*"([^"]{20,2000})"/,
        /"description"\s*:\s*"([^"]{20,2000})"/,
        /"desc"\s*:\s*"([^"]{20,2000})"/
      ]
    });
    var idMatch = location.href.match(/goods[_\s]?[=:]?\s*(\d{8,})/) || location.href.match(/goods_id=(\d+)/);
    if (!info.sku) info.sku = 'PDD-' + (idMatch ? idMatch[1] : Date.now().toString(36));
    console.log('[熊猫] 拼多多产品提取:', info);
    return info;
  }

  function sendToServer(info) {
    if (typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.sendMessage) {
      chrome.runtime.sendMessage({ action: 'forwardScrapeData', data: info }, function(response) {
        if (response && response.success) {
          console.log('[熊猫] ✅ 通过扩展后台发送成功');
          showToast('✅ 采集成功: ' + info.name.substring(0, 25), '#1ab394');
        } else {
          showToast('⚠️ 服务器暂不可用，已保存到本地', '#f39c12');
          try { var items = JSON.parse(localStorage.getItem('pending_scraped_products') || '[]'); items.push(info); localStorage.setItem('pending_scraped_products', JSON.stringify(items.slice(-50))); } catch(e) {}
        }
      });
    } else {
      var apiUrl = 'https://sczfai.com/api/scrape-from-extension';
      doSend(apiUrl, info);
    }
  }

  function doSend(apiUrl, info) {
    fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(info) })
      .then(function(r) { return r.json(); })
      .then(function(d) {
        if (d && d.code === 1) { console.log('[熊猫] ✅ 已发送'); showToast('✅ 采集成功: ' + info.name.substring(0, 25), '#1ab394'); }
        else showToast('⚠️ ' + (d && d.msg ? d.msg : '未知错误'), '#f39c12');
      }).catch(function() {
        showToast('⚠️ 服务器连接失败，已保存到本地', '#f39c12');
        try { var items = JSON.parse(localStorage.getItem('pending_scraped_products') || '[]'); items.push(info); localStorage.setItem('pending_scraped_products', JSON.stringify(items.slice(-50))); } catch(e) {}
      });
  }

  function autoCollectWithRetry() {
    if (window.__QYDZ_PDD_AUTO_COLLECT_SENT__) return;
    if (history.replaceState && location.href.indexOf('_qydz_scrape=1') !== -1) {
      var cleanUrl = location.href.replace(/[?&]_qydz_scrape=1/, '');
      history.replaceState(null, '', cleanUrl);
    }
    showToast('⏳ 熊猫正在自动采集商品资料...', '#e02e24');
    var attempts = 0;
    var delays = [600, 1800, 3500, 6000, 9000];
    function run() {
      attempts++;
      var info = extractProductInfo();
      if (info.name && info.name.length >= 2) {
        window.__QYDZ_PDD_AUTO_COLLECT_SENT__ = true;
        sendToServer(info);
      } else if (attempts < delays.length) {
        setTimeout(run, delays[attempts]);
      } else {
        showToast('⚠️ 页面资料还未加载完整，请稍后点右下角熊猫按钮重试', '#f39c12');
      }
    }
    setTimeout(run, delays[0]);
  }

  if (typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.onMessage) {
    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
      if (request && request.action === 'scrapeProduct') { var info = extractProductInfo(); if (info.name) sendToServer(info); sendResponse({ success: !!info.name, data: info }); return true; }
      if (request && request.Type === 'GetPinDuoDuoText') {
        var info = extractProductInfo();
        sendResponse({ isLinkCollect: true, Info: { name: info.name, image: info.images, offers: { price: parseFloat((info.price || '0').replace(/[^\d.]/g, '')) || 0 }, props: info.props, description: info.description, selling_points: info.selling_points }, Url: info.url, Skus: [{ Price: parseFloat((info.price || '0').replace(/[^\d.]/g, '')) || 0, SkuCode: info.sku, Property: '[]', Currency: 'CNY', VariantImageUrl: info.image }] });
        return true;
      }
    });
  }

  setTimeout(function() {
    if (U.isAiLinkScrapeMode && U.isAiLinkScrapeMode()) {
      autoCollectWithRetry();
    }
    addFloatingButton();
  }, 500);
})();
