/**
 * 淘宝/天猫产品页面采集脚本
 * 运行在用户真实浏览器中
 */
(function() {
  'use strict';

  if (!location.href.includes('item.taobao.com') && !location.href.includes('detail.tmall.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 || '#ff4400') + ';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';
    btn.innerHTML = '🐼 熊猫';
    btn.style.cssText = 'position:fixed;bottom:30px;right:30px;z-index:999999;background:linear-gradient(135deg,#ff4400,#e63e00);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(255,68,0,.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('⏳ 正在采集...', '#ff4400');
      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: 'taobao', 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 || '';
        var m = text.match(/TShop\.Setup\s*=\s*(\{.+?\});/s) || text.match(/_DATA_\s*=\s*(\{.+?\});/s);
        if (m) {
          try {
            var d = JSON.parse(m[1]);
            if (d.item) d = d.item;
            if (d.title) info.name = d.title.trim();
            if (d.price) info.price = '¥' + String(d.price).replace(/[^\d.]/g, '');
            if (d.images) {
              d.images.forEach(function(img) {
                var url = typeof img === 'string' ? img : (img.url || img.src || '');
                url = U.normalizeImageUrl(url);
                if (url) U.pushUnique(info.images, url);
              });
              if (info.images.length) info.image = info.images[0];
            }
            var attrs = d.attrs || d.attributes || d.props || d.params || d.itemProperties;
            if (Array.isArray(attrs)) {
              attrs.forEach(function(attr) {
                if (!attr) return;
                if (typeof attr === 'string') {
                  var parts = attr.split(/[:：]/);
                  if (parts.length >= 2) U.addProp(info.props, parts[0], parts.slice(1).join(':'));
                } else {
                  U.addProp(info.props, attr.key || attr.name || attr.title || attr.attrName, attr.value || attr.text || attr.attrValue);
                }
              });
            } else if (attrs && typeof attrs === 'object') {
              Object.keys(attrs).forEach(function(key) { U.addProp(info.props, key, attrs[key]); });
            }
            var desc = d.desc || d.description || d.detail || d.itemDesc;
            if (desc && !info.description) info.description = U.cleanText(String(desc).replace(/<[^>]+>/g, ' '), 2000);
            if (info.name) break;
          } catch(e) {}
        }
        var gm = text.match(/g_config\s*=\s*(\{.+?\});/s);
        if (gm && !info.name) { try { var gd = JSON.parse(gm[1]); if (gd.title || gd.itemTitle) info.name = (gd.title || gd.itemTitle || '').trim(); } catch(e) {} }
      }
    } catch(e) {}
    if (!info.name) {
      var titleEl = document.querySelector('.tb-main-title') || document.querySelector('[data-spm="1000983"]') || document.querySelector('.ItemTitle h1') || document.querySelector('h1[data-spm]') || document.querySelector('#J_Title h3') || document.querySelector('.main-title') || document.querySelector('h1');
      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('.tm-price') || document.querySelector('#J_StrPrice') || document.querySelector('[class*="Price"] [class*="current"]') || document.querySelector('.tb-rmb-num') || document.querySelector('#J_PromoPrice .tb-rmb-num');
      if (priceEl) { var raw = priceEl.textContent.replace(/[^\d.]/g, ''); if (raw && parseFloat(raw) > 0) info.price = '¥' + parseFloat(raw).toFixed(2); }
    }
    if (!info.image) {
      var mainImg = document.querySelector('#J_ImgBooth') || document.querySelector('[data-role="main-img"]') || document.querySelector('.tb-pic img') || document.querySelector('[class*="gallery"] img');
      if (mainImg) { var src = mainImg.getAttribute('src') || mainImg.getAttribute('data-src') || ''; if (src && src.startsWith('http')) { src = src.replace(/\.\d+x\d+\.(jpg|png)/, '.$1').split('?')[0]; if (!src.startsWith('http')) src = 'https:' + src; info.image = src; info.images.push(src); } }
    }
    U.enrich(info, {
      imageSelectors: [
        '#J_UlThumb img',
        '#J_ImgBooth',
        '.tb-pic img',
        '.tb-gallery img',
        '[class*="gallery"] img',
        '[class*="mainPic"] img',
        '[class*="PicGallery"] img',
        'img[src*="alicdn.com"]'
      ],
      propSelectors: [
        '#attributes li',
        '.attributes-list li',
        '.tm-attributes-list li',
        '#J_AttrUL li',
        '.tb-prop',
        '.tb-sku dl',
        '[class*="sku"] [class*="item"]',
        '[class*="attribute"] li',
        '[class*="property"] li',
        '[class*="param"] li',
        'table tr'
      ],
      descriptionSelectors: [
        '#J_DivItemDesc',
        '#description',
        '#desc',
        '.tb-detail-content',
        '.descV8-container',
        '[class*="description"]',
        '[class*="Description"]',
        '[class*="detail-content"]'
      ],
      jsonDescriptionPatterns: [
        /"description"\s*:\s*"([^"]{20,2000})"/,
        /"desc"\s*:\s*"([^"]{20,2000})"/,
        /"itemDesc"\s*:\s*"([^"]{20,2000})"/
      ]
    });
    var idMatch = location.href.match(/[?&]id=(\d+)/);
    info.sku = 'TB-' + (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(x) {}
        }
      });
    } else {
      doSendDirect(info);
    }
  }

  function doSendDirect(info) {
    fetch('https://sczfai.com/api/scrape-from-extension', {
      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(e) {
        console.log('[熊猫] 发送失败，存本地:', e.message);
        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(x) {}
      });
  }

  function autoCollectWithRetry() {
    if (window.__QYDZ_TB_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('⏳ 熊猫正在自动采集商品资料...', '#ff4400');
    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_TB_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 === 'GetTaoBaoText') {
        var info = extractProductInfo();
        sendResponse({ isLinkCollect: true, box: { boxInfo: { Title: info.name, ImageUrl: info.images.join('|'), SourceUrl: info.url, SourcePlatform: 2, Parameters: JSON.stringify(info.props), BriefDescription: (info.selling_points || []).join('；'), DetailedDescription: info.description || '' }, variants: [{ 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);
})();
