// TEMU鍚堣鍔╂墜 - 鍐呭鑴氭湰

console.log('[TEMU] content script loaded');

const temuContentScriptRuntime = window.__temuContentScriptRuntime || (window.__temuContentScriptRuntime = {
  sessionBannerTimer: null,
  frontendResetTimer: null,
  backendCleanerObserver: null,
  backendCleanerHeartbeat: null
});

function safeChromeStorageSet(values = {}, context = 'storage') {
  try {
    if (!chrome?.storage?.local) return;
    chrome.storage.local.set(values, () => {
      if (chrome.runtime?.lastError) {
        console.warn(`[TEMU] ${context} 写入失败:`, chrome.runtime.lastError.message);
      }
    });
  } catch (error) {
    console.warn(`[TEMU] ${context} 写入异常:`, error);
  }
}

function safeChromeStorageGet(keys, callback, context = 'storage') {
  try {
    if (!chrome?.storage?.local) {
      callback?.({});
      return;
    }
    chrome.storage.local.get(keys, (result) => {
      if (chrome.runtime?.lastError) {
        console.warn(`[TEMU] ${context} 读取失败:`, chrome.runtime.lastError.message);
        callback?.({});
        return;
      }
      callback?.(result || {});
    });
  } catch (error) {
    console.warn(`[TEMU] ${context} 读取异常:`, error);
    callback?.({});
  }
}

function normalizeTemuPricingId(value) {
  const text = String(value ?? '').trim();
  if (!text) return '';
  const match = text.match(/\d{5,}/);
  return match ? match[0] : text;
}

function normalizeTemuPricingMoney(value) {
  if (value === undefined || value === null || value === '') return '';
  const text = String(value).replace(/[¥￥,\s]/g, '').trim();
  if (!text || /^[-—]+$/.test(text)) return '';
  const match = text.match(/\d+(?:\.\d+)?/);
  if (!match) return '';
  const num = Number(match[0]);
  return Number.isFinite(num) && num > 0 ? num.toFixed(2) : '';
}

function parseTemuPricingTextIds(text = '') {
  const source = String(text || '');
  const pick = (patterns) => {
    for (const pattern of patterns) {
      const match = source.match(pattern);
      if (match?.[1]) return normalizeTemuPricingId(match[1]);
    }
    return '';
  };
  return {
    skuId: pick([
      /(?:productSkuId|goodsSkuId|skuId|sku_id)["'\s:=：#-]*([0-9]{5,})/i,
      /SKU(?:\s*ID)?[：:\s#]*([0-9]{5,})/i,
      /商品SKU[：:\s#]*([0-9]{5,})/i
    ]),
    skcId: pick([
      /(?:productSkcId|goodsSkcId|skcId|skc_id)["'\s:=：#-]*([0-9]{5,})/i,
      /SKC(?:\s*ID)?[：:\s#]*([0-9]{5,})/i,
      /商品SKC[：:\s#]*([0-9]{5,})/i
    ]),
    priceOrderId: pick([
      /(?:priceOrderId|price_order_id|orderId)["'\s:=：#-]*([0-9]{5,})/i,
      /核价单(?:ID|号)?[：:\s#]*([0-9]{5,})/i
    ])
  };
}

function collectTemuPricingCandidateIds(text = '') {
  return Array.from(new Set(
    (String(text || '').match(/\b[0-9]{5,}\b/g) || [])
      .map(value => normalizeTemuPricingId(value))
      .filter(Boolean)
  ));
}

function getTemuPricingRowIndex(row) {
  if (!row) return -1;
  const explicit = row.getAttribute?.('data-row-index') || row.getAttribute?.('aria-rowindex') || row.dataset?.rowIndex;
  const explicitIndex = Number(explicit);
  if (Number.isFinite(explicitIndex)) return explicitIndex;
  const parent = row.parentElement;
  if (!parent) return -1;
  const siblings = Array.from(parent.children || []).filter(el =>
    el.matches?.('[data-testid="beast-core-table-body-tr"], tr, [role="row"]')
  );
  return siblings.indexOf(row);
}

function collectTemuPricingNodeEvidence(node, maxLength = 16000) {
  if (!node) return '';
  const parts = [];
  const push = (value) => {
    const text = String(value || '').replace(/\s+/g, ' ').trim();
    if (text) parts.push(text);
  };
  const readNode = (el) => {
    if (!el) return;
    push(el.innerText || el.textContent || '');
    for (const attr of ['data-row-key', 'data-row-id', 'data-testid', 'title', 'aria-label', 'href', 'src', 'alt', 'value', 'name', 'id']) {
      push(el.getAttribute?.(attr));
    }
  };
  readNode(node);
  Array.from(node.querySelectorAll?.('[title],[aria-label],[data-row-key],[data-row-id],[data-testid],a[href],img[alt],img[src],input[value],input[name],input[id]') || [])
    .slice(0, 240)
    .forEach(readNode);
  push(node.outerHTML || '');
  return parts.join(' ').slice(0, maxLength);
}

function collectTemuPricingPeerRows(row) {
  const peers = [];
  const addPeer = (candidate) => {
    if (candidate && !peers.includes(candidate)) peers.push(candidate);
  };
  addPeer(row);

  const rowIndex = getTemuPricingRowIndex(row);
  if (rowIndex < 0) return peers;

  const bodies = Array.from(document.querySelectorAll('tbody, [role="rowgroup"], [data-testid*="table-body"], [class*="TB_body"]'));
  for (const body of bodies.slice(0, 80)) {
    const children = Array.from(body.children || []).filter(el =>
      el.matches?.('[data-testid="beast-core-table-body-tr"], tr, [role="row"]')
    );
    addPeer(children[rowIndex]);
  }
  return peers;
}

function readTemuPricingDomRowEvidence(row) {
  const peerRows = collectTemuPricingPeerRows(row);
  const evidence = peerRows.map(peer => collectTemuPricingNodeEvidence(peer)).filter(Boolean).join(' ');
  return {
    ids: parseTemuPricingTextIds(evidence),
    candidateIds: collectTemuPricingCandidateIds(evidence),
    rowIndex: getTemuPricingRowIndex(row)
  };
}

function isTemuPricingBackendPage() {
  try {
    const host = location.hostname || '';
    const url = location.href || '';
    return /agentseller|seller\.kuajingmaihuo/i.test(host)
      && /price|pricing|goods|product|professional|kiana|mms/i.test(url);
  } catch (_) {
    return false;
  }
}

function isTemuSellerBackendHost() {
  try {
    return /(agentseller(?:-[a-z]+)?\.temu\.com|seller(?:-[a-z]+)?\.temu\.com|seller\.kuajingmaihuo\.com)$/i.test(location.hostname || '');
  } catch (_) {
    return false;
  }
}

function compactCapturedProduct(item = {}) {
  const skuList = Array.isArray(item.skuList) ? item.skuList : [];
  return {
    productId: item.productId || item.spuId || item.goodsId || '',
    goodsId: item.goodsId || item.spuId || '',
    productName: item.productName || item.goodsName || item.productCNName || '',
    mainImage: item.mainImage || item.mainImageUrl || item.goodsImg || '',
    skcId: item.skcId || item.productSkcId || '',
    skcTopStatus: item.skcTopStatus ?? item.topStatus ?? '',
    skuList: skuList.slice(0, 20).map(sku => ({
      skuId: sku.skuId || sku.productSkuId || '',
      productSkuId: sku.productSkuId || sku.skuId || '',
      skuSpec: sku.skuSpec || sku.specInfo || sku.className || '',
      templateId: sku.templateId || sku.template_id || '',
      productSkuCustomizationTmpl: sku.productSkuCustomizationTmpl || sku.productSkuSaleExtAttr?.productSkuCustomizationTmpl || null
    }))
  };
}

// ========== 鎻愮ず鍑芥暟 ==========
function showSuccess(message) {
  const toast = document.createElement('div');
  toast.style.cssText = 'position:fixed;top:20px;right:20px;background:#52c41a;color:white;padding:12px 24px;border-radius:4px;z-index:999999;font-size:14px;';
  toast.textContent = '✓ ' + message;
  document.body.appendChild(toast);
  setTimeout(() => toast.remove(), 3000);
}

function showError(message) {
  const toast = document.createElement('div');
  toast.style.cssText = 'position:fixed;top:20px;right:20px;background:#ff4d4f;color:white;padding:12px 24px;border-radius:4px;z-index:999999;font-size:14px;';
  toast.textContent = '✗ ' + message;
  document.body.appendChild(toast);
  setTimeout(() => toast.remove(), 3000);
}

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

function pickFirstText(selectors = []) {
  for (const selector of selectors) {
    const el = document.querySelector(selector);
    const text = (el?.innerText || el?.textContent || '').trim();
    if (text) return text;
  }
  return '';
}

function pickFirstAttr(selectors = [], attr = 'src') {
  for (const selector of selectors) {
    const el = document.querySelector(selector);
    const value = el?.getAttribute?.(attr) || el?.[attr] || '';
    if (value) {
      try {
        return new URL(value, location.href).toString();
      } catch (_) {
        return value;
      }
    }
  }
  return '';
}

// ========== 浠?Drawer DOM 鎻愬彇 SPU ID ==========
function extractSpuIdFromDrawer() {
  // 从 Drawer 文本中查找 SPU ID
  const drawer = document.querySelector('.rocket-drawer, .ant-drawer, [class*="drawer"]');
  if (!drawer) return null;

  const text = drawer.innerText || drawer.textContent || '';
  // 匹配 SPU ID：至少 10 位数字
  const match = text.match(/SPU[：:\s]*(\d+)/i) || text.match(/\b(\d{10,})\b/);
  if (match) {
    console.log('[TEMU] 从 Drawer 提取到 SPU ID:', match[1]);
    return match[1];
  }
  return null;
}

// ========== 在合规 Drawer 中添加“保存为模板”按钮 ==========
// 合规中心不再注入底部“保存为模板”按钮，保存提醒改由中间浮层承担。

// ========== 鐩戝惉鏉ヨ嚜 background.js 鐨勬秷鎭紙webRequest 鎷︽埅鎻愮ず锛?=========
if (globalThis.chrome?.runtime?.onMessage) {
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'showSaveToast') {
      showSaveToast(request.spuId, request.taskCount);
      sendResponse({ received: true });
      return false;
    }
    if (request.action === 'collectPricingDomSnapshot') {
      try {
        const rows = extractTemuPricingRowsFromTableDom();
        if (rows.length) mergeTemuPricingCaptureRows(rows);
        sendResponse({
          success: true,
          url: location.href,
          isPricingPage: isTemuPricingBackendPage(),
          rowCount: rows.length,
          rows: rows.slice(0, 80)
        });
      } catch (error) {
        sendResponse({ success: false, error: error?.message || String(error), url: location.href });
      }
      return true;
    }
  });
}

// ========== 鎷︽埅 TEMU 鍟嗗搧鍒楄〃 pageQuery 鏁版嵁 ==========
function injectFetchInterceptor() {
  // 闃叉閲嶅娉ㄥ叆
  if (window.__temuFetchIntercepted) return;
  window.__temuFetchIntercepted = true;
  if (window.__temuFetchHooked) return;

  const script = document.createElement('script');
  script.textContent = `
    (function() {
      if (window.__temuFetchHooked) return;
      window.__temuFetchHooked = true;

      const originalFetch = window.fetch;
      const originalXhrOpen = window.XMLHttpRequest && window.XMLHttpRequest.prototype.open;
      const originalXhrSend = window.XMLHttpRequest && window.XMLHttpRequest.prototype.send;
      const readBody = (body) => {
        if (typeof body !== 'string') return null;
        try {
          return JSON.parse(body);
        } catch (_) {
          return body;
        }
      };
      const emitCapturedResponse = (url, requestBody, data) => {
        if (!url || !(url.includes('pageQuery') || url.includes('real_picture/list'))) return;
        if (url.includes('real_picture/list')) {
          if (data && data.success && data.result) {
            window.postMessage({ type: '__TEMU_LIVE_PHOTO_DATA__', url, requestBody, data: data.result }, '*');
          }
          return;
        }
        if (data && (data.result !== undefined || data.data !== undefined)) {
          window.postMessage({ type: '__TEMU_PAGE_QUERY_DATA__', url, data }, '*');
        }
      };
      if (typeof originalFetch === 'function') {
        window.fetch = async function(...args) {
          const response = await originalFetch.apply(this, args);
          try {
            const url = typeof args[0] === 'string' ? args[0] : (args[0]?.url || '');
            const requestBody = readBody(args[1]?.body || args[0]?.body || null);
            response.clone().json().then(data => emitCapturedResponse(url, requestBody, data)).catch(() => {});
          } catch(e) {}
          return response;
        };
      }
      if (typeof originalXhrOpen === 'function' && typeof originalXhrSend === 'function') {
        window.XMLHttpRequest.prototype.open = function(method, url, ...rest) {
          this.__temuCaptureUrl = typeof url === 'string' ? url : (url && url.toString ? url.toString() : '');
          return originalXhrOpen.call(this, method, url, ...rest);
        };
        window.XMLHttpRequest.prototype.send = function(body) {
          const requestBody = readBody(body);
          try {
            this.addEventListener('load', function() {
              try {
                const text = this.responseType && this.responseType !== 'text' ? '' : (this.responseText || '');
                if (!text) return;
                emitCapturedResponse(this.__temuCaptureUrl || '', requestBody, JSON.parse(text));
              } catch (_) {}
            });
          } catch (_) {}
          return originalXhrSend.call(this, body);
        };
      }
    })();
  `;
  document.documentElement.appendChild(script);
  script.remove();

}
// 鐩戝惉娉ㄥ叆鑴氭湰鍙戞潵鐨勬秷鎭紝瀛樺叆 chrome.storage
window.addEventListener('message', (event) => {
  if (event.source !== window) return;
  if (event.data?.type !== '__TEMU_PAGE_QUERY_DATA__') return;

  const { url, data } = event.data;
  console.log('[TEMU鍚堣鍔╂墜] 鎹曡幏 pageQuery 鍝嶅簲, url:', url.substring(0, 80));

  // 灏濊瘯鎻愬彇鍟嗗搧鍒楄〃鏁版嵁
  let productList = null;
  let queryType = '';

  // 鍏煎澶氱鍝嶅簲缁撴瀯
  const result = data.result || data.data;
  if (!result) return;

  // 妫€鏌ユ槸鍚︽槸鍟嗗搧鍒楄〃锛堟湁鍟嗗搧椤规暟缁勶級
  if (result.pageItems && Array.isArray(result.pageItems) && result.pageItems.length > 0) {
    productList = result.pageItems;
    queryType = 'pageItems';
  } else if (result.items && Array.isArray(result.items) && result.items.length > 0) {
    productList = result.items;
    queryType = 'items';
  } else if (result.list && Array.isArray(result.list) && result.list.length > 0) {
    productList = result.list;
    queryType = 'list';
  } else if (result.goodsList && Array.isArray(result.goodsList)) {
    productList = result.goodsList;
    queryType = 'goodsList';
  } else if (Array.isArray(result) && result.length > 0 && result[0]?.productId) {
    productList = result;
    queryType = 'array';
  }

  if (productList) {
    // 妫€鏌ョ涓€椤规槸鍚︽湁鍟嗗搧鐩稿叧瀛楁
    const firstItem = productList[0];
    const hasGoodsFields = firstItem.productId || firstItem.goodsId || firstItem.spuId ||
                          firstItem.productName || firstItem.goodsName || firstItem.title;
    if (hasGoodsFields) {
      console.log('[TEMU鍚堣鍔╂墜] 璇嗗埆涓哄晢鍝佸垪琛? queryType:', queryType, ', count:', productList.length);
      // 鎵撳嵃绗竴椤圭殑鎵€鏈夐敭鍚嶏紝鏂逛究璋冭瘯
      console.log('[TEMU鍚堣鍔╂墜] 鍟嗗搧瀛楁鍚?', Object.keys(firstItem).join(', '));
      console.log('[TEMU鍚堣鍔╂墜] 绗竴椤规暟鎹?鍓?00瀛?:', JSON.stringify(firstItem).substring(0, 500));

      const compactList = productList.slice(0, 300).map(compactCapturedProduct);
      // 瀛樺叆 chrome.storage锛氬彧淇濆瓨绮剧畝瀛楁锛岄伩鍏嶆湰鍦板瓨鍌ㄩ厤棰濆鑷存彃浠朵笉绋冲畾
      safeChromeStorageSet({
        temuCapturedProductList: {
          items: compactList,
          total: result.totalCount || result.total || productList.length,
          capturedAt: Date.now(),
          queryType: queryType,
          url: url
        }
      }, '商品列表缓存');
    }
  }
});

const TEMU_PRICING_CAPTURE_CACHE_KEY = 'temuCapturedPricingReferencePrices';
const TEMU_PRICING_CAPTURE_MAX_ITEMS = 2000;

function readTemuPricingValueFromObject(source = {}) {
  if (!source || typeof source !== 'object') return '';
  const centKeys = [
    'adjustedDeclarePrice',
    'adjustedDeclarationPrice',
    'afterAdjustDeclarePrice',
    'afterAdjustedDeclarePrice',
    'adjustAfterDeclarePrice',
    'adjustedDeclarePriceCny',
    'adjustedDeclarationPriceCny',
    'afterAdjustDeclarePriceCny',
    'referenceDeclarePrice',
    'referenceDeclarationPrice',
    'suggestSupplyPrice',
    'targetSupplyPrice'
  ];
  const yuanKeys = [
    'adjustedDeclarePriceText',
    'adjustedDeclarationPriceText',
    'afterAdjustDeclarePriceText',
    'referenceDeclarePriceText',
    'referenceDeclarationPriceText',
    'suggestSupplyPriceText',
    'targetSupplyPriceText',
    'referencePrice',
    'referencePriceValue',
    'displayPrice',
    'priceText'
  ];
  for (const key of centKeys) {
    if (source[key] === undefined || source[key] === null || source[key] === '') continue;
    const rawText = String(source[key]).trim();
    const raw = Number(rawText);
    if (Number.isFinite(raw) && raw > 0) {
      // TEMU 半托管页面/API 有时直接返回 481.81 这种元值；只有整数分值才除以 100。
      return rawText.includes('.') ? raw.toFixed(2) : (raw / 100).toFixed(2);
    }
    const normalized = normalizeTemuPricingMoney(source[key]);
    if (normalized) return normalized;
  }
  for (const key of yuanKeys) {
    const normalized = normalizeTemuPricingMoney(source[key]);
    if (normalized) return normalized;
  }
  return '';
}

function collectTemuPricingRowsFromApi(data, url = '') {
  const rows = [];
  const seen = new Set();
  const walk = (node, context = {}) => {
    if (!node || typeof node !== 'object') return;
    if (Array.isArray(node)) {
      node.slice(0, 5000).forEach(item => walk(item, context));
      return;
    }
    const nextContext = {
      priceOrderId: normalizeTemuPricingId(node.priceOrderId || node.orderId || node.id || context.priceOrderId || ''),
      skcId: normalizeTemuPricingId(node.skcId || node.goodsSkcId || node.productSkcId || node.skcIdStr || context.skcId || ''),
      skuId: normalizeTemuPricingId(node.skuId || node.productSkuId || node.goodsSkuId || node.skuIdStr || context.skuId || '')
    };
    const price = readTemuPricingValueFromObject(node);
    if (price && (nextContext.skuId || nextContext.skcId || nextContext.priceOrderId)) {
      const key = [nextContext.priceOrderId, nextContext.skcId, nextContext.skuId, price].join('|');
      if (!seen.has(key)) {
        seen.add(key);
        rows.push({
          ...nextContext,
          price,
          source: 'api',
          sourceUrl: url,
          capturedAt: Date.now()
        });
      }
    }
    Object.entries(node).forEach(([key, value]) => {
      if (!value || typeof value !== 'object') return;
      if (!/list|sku|skc|price|review|data|result|item|record|goods|product/i.test(key)) return;
      walk(value, nextContext);
    });
  };
  walk(data, {});
  return rows;
}

function mergeTemuPricingCaptureRows(newRows = []) {
  const validRows = (Array.isArray(newRows) ? newRows : []).filter(row =>
    row && row.price && (row.skuId || row.skcId || row.priceOrderId || (Array.isArray(row.candidateIds) && row.candidateIds.length))
  );
  if (!validRows.length) return;
  safeChromeStorageGet(TEMU_PRICING_CAPTURE_CACHE_KEY, (stored) => {
    const existing = stored[TEMU_PRICING_CAPTURE_CACHE_KEY];
    const rows = Array.isArray(existing?.rows) ? existing.rows : [];
    const byKey = new Map();
    [...rows, ...validRows].forEach((row) => {
      const candidateKey = Array.isArray(row.candidateIds) ? row.candidateIds.filter(Boolean).join(',') : '';
      const key = [row.priceOrderId || '', row.skcId || '', row.skuId || '', candidateKey, row.rowIndex ?? ''].join('|');
      if (!key.replace(/\|/g, '')) return;
      byKey.set(key, {
        ...byKey.get(key),
        ...row,
        candidateIds: Array.from(new Set([
          ...(byKey.get(key)?.candidateIds || []),
          ...(Array.isArray(row.candidateIds) ? row.candidateIds : [])
        ].filter(Boolean))),
        capturedAt: row.capturedAt || Date.now()
      });
    });
    const mergedRows = Array.from(byKey.values())
      .sort((a, b) => Number(b.capturedAt || 0) - Number(a.capturedAt || 0))
      .slice(0, TEMU_PRICING_CAPTURE_MAX_ITEMS);
    safeChromeStorageSet({
      [TEMU_PRICING_CAPTURE_CACHE_KEY]: {
        rows: mergedRows,
        capturedAt: Date.now()
      }
    }, '核价参考申报价缓存');
  }, '核价参考申报价缓存');
}

window.addEventListener('message', (event) => {
  if (event.source !== window) return;
  if (event.data?.type !== '__TEMU_PRICING_API_DATA__') return;
  const { url, data } = event.data;
  const rows = collectTemuPricingRowsFromApi(data, url || '');
  if (rows.length) {
    console.log('[TEMU] 捕获核价接口参考申报价:', rows.length);
    mergeTemuPricingCaptureRows(rows);
  }
});

function extractTemuPricingRowsFromTableDom() {
  if (!isTemuPricingBackendPage()) return [];
  const rows = [];
  const seen = new Set();
  const tableRows = Array.from(document.querySelectorAll('[data-testid="beast-core-table-body-tr"], tbody tr, [role="row"]'))
    .filter(row => row && row.querySelector?.('input[disabled][value], input[readonly][value], [data-testid*="inputNumber"] input[value]'));

  for (const row of tableRows.slice(0, 500)) {
    const text = String(row.innerText || row.textContent || '').replace(/\s+/g, ' ').trim();
    const evidence = readTemuPricingDomRowEvidence(row);
    const ids = evidence.ids && (evidence.ids.skuId || evidence.ids.skcId || evidence.ids.priceOrderId)
      ? evidence.ids
      : parseTemuPricingTextIds(text);
    const candidateIds = Array.from(new Set([
      ...(evidence.candidateIds || []),
      ...collectTemuPricingCandidateIds(text)
    ]));
    const inputs = Array.from(row.querySelectorAll('input[disabled][value], input[readonly][value], [data-testid*="inputNumber"] input[value]'));
    const priceInputs = inputs
      .map(input => normalizeTemuPricingMoney(input.getAttribute('value') || input.value || ''))
      .filter(Boolean);
    for (const price of priceInputs) {
      const key = [ids.priceOrderId, ids.skcId, ids.skuId, price, candidateIds.join(',')].join('|');
      if (!ids.skuId && !ids.skcId && !ids.priceOrderId && !candidateIds.length) continue;
      if (seen.has(key)) continue;
      seen.add(key);
      rows.push({
        ...ids,
        price,
        candidateIds,
        rowIndex: evidence.rowIndex,
        source: 'dom',
        sourceUrl: location.href,
        capturedAt: Date.now()
      });
    }
  }
  return rows;
}

let temuPricingDomCaptureTimer = null;
function scheduleTemuPricingDomCapture() {
  if (!isTemuPricingBackendPage()) return;
  if (temuPricingDomCaptureTimer) return;
  temuPricingDomCaptureTimer = setTimeout(() => {
    temuPricingDomCaptureTimer = null;
    const rows = extractTemuPricingRowsFromTableDom();
    if (rows.length) {
      console.log('[TEMU] 捕获核价页面参考申报价:', rows.length);
      mergeTemuPricingCaptureRows(rows);
    }
  }, 800);
}

if (isTemuPricingBackendPage()) {
  scheduleTemuPricingDomCapture();
  const pricingObserver = new MutationObserver(() => scheduleTemuPricingDomCapture());
  pricingObserver.observe(document.documentElement, { childList: true, subtree: true });
}

// 鐩戝惉瀹炴媿鍥惧垪琛ㄦ暟鎹紙浠庨〉闈?fetch 鎷︽埅锛?
window.addEventListener('message', (event) => {
  if (event.source !== window) return;
  if (event.data?.type !== '__TEMU_LIVE_PHOTO_DATA__') return;

  const { data, requestBody, url } = event.data;
  console.log('[TEMU鍚堣鍔╂墜] 鎹曡幏 real_picture/list 鍝嶅簲, items:', data?.items?.length, 'total:', data?.total);

  if (data && data.items && Array.isArray(data.items)) {
    safeChromeStorageSet({
      temuCapturedLivePhotoList: {
        items: data.items,
        total: data.total || data.items.length,
        capturedAt: Date.now(),
        requestBody: requestBody || null,
        url: url || ''
      }
    }, '实拍图列表缓存');
  }
});


// ========== TEMU 涔板椤甸噰闆嗘寜閽?==========
let buyerRawDataCache = null;

function parseBalancedObjectFromText(text, marker) {
  const idx = text.indexOf(marker);
  if (idx === -1) return null;
  const assignIndex = text.indexOf('=', idx);
  if (assignIndex === -1) return null;
  let depth = 0;
  let inString = false;
  let quote = '';
  const start = assignIndex + 1;
  for (let i = start; i < text.length; i++) {
    const ch = text[i];
    const prev = text[i - 1];
    if (inString) {
      if (ch === quote && prev !== '\\') inString = false;
      continue;
    }
    if (ch === '"' || ch === '\'') {
      inString = true;
      quote = ch;
      continue;
    }
    if (ch === '{') depth++;
    if (ch === '}') {
      depth--;
      if (depth === 0) {
        const snippet = text.slice(start, i + 1);
        try {
          return Function(`"use strict"; return (${snippet});`)();
        } catch (error) {
          return null;
        }
      }
    }
  }
  return null;
}

function extractBuyerRawDataFromScripts() {
  if (!isTemuBuyerPage()) return null;
  for (const script of Array.from(document.scripts || [])) {
    const text = script.textContent || script.innerText || '';
    if (!text.includes('window.rawData')) continue;
    const parsed = parseBalancedObjectFromText(text, 'window.rawData');
    if (parsed && typeof parsed === 'object') {
      return parsed;
    }
  }
  return null;
}

function refreshBuyerRawDataCache() {
  const parsed = extractBuyerRawDataFromScripts();
  if (parsed) {
    buyerRawDataCache = parsed;
    window.__TEMU_BUYER_RAW_DATA_CACHE__ = parsed;
    return true;
  }
  return false;
}

function isTemuBuyerPage() {
  const host = location.hostname;
  if (!host.includes('temu.com')) return false;
  if (host.includes('agentseller') || host.includes('seller.kuajingmaihuo')) return false;
  let url;
  try {
    url = new URL(location.href);
  } catch (error) {
    return false;
  }
  const path = `${url.pathname || ''}${url.search || ''}`;
  if (/login|register|auth|password|account|home/i.test(url.pathname || '')) return false;
  return /-p-\d+|-g-\d+/.test(path) || /goods_id=\d+|goodsId=\d+|item_id=\d+/.test(url.search || '');
}

function getBuyerGoodsId() {
  let url;
  try {
    url = new URL(location.href);
  } catch (error) {
    return '';
  }
  const path = `${url.pathname || ''}${url.search || ''}`;
  const match =
    path.match(/-p-(\d+)/) ||
    path.match(/-g-(\d+)/) ||
    url.search.match(/goods_id=(\d+)/) ||
    url.search.match(/goodsId=(\d+)/) ||
    url.search.match(/item_id=(\d+)/);
  return match ? match[1] : '';
}

function ensureBuyerCollectButton() {
  if (!document.body || document.getElementById('temu-buyer-collect-btn')) return;
  if (!isTemuBuyerPage()) return;

  const goodsId = getBuyerGoodsId();
  if (!goodsId) return;

  const btn = document.createElement('button');
  btn.id = 'temu-buyer-collect-btn';
  btn.type = 'button';
  btn.textContent = '全托商品采集';
  btn.style.cssText = [
    'position:fixed',
    'right:18px',
    'bottom:18px',
    'z-index:9999999',
    'padding:12px 16px',
    'border:0',
    'border-radius:999px',
    'background:linear-gradient(135deg,#18a058,#0f7a43)',
    'color:#fff',
    'font-size:14px',
    'font-weight:600',
    'box-shadow:0 10px 24px rgba(0,0,0,.18)',
    'cursor:pointer'
  ].join(';');

  const showToast = (text, error = false) => {
    const old = document.getElementById('temu-buyer-collect-toast');
    if (old) old.remove();
    const tip = document.createElement('div');
    tip.id = 'temu-buyer-collect-toast';
    tip.textContent = text;
    tip.style.cssText = [
      'position:fixed',
      'right:18px',
      'bottom:70px',
      'z-index:9999999',
      'padding:10px 14px',
      'border-radius:8px',
      `background:${error ? '#d03050' : '#1d4ed8'}`,
      'color:#fff',
      'font-size:13px',
      'box-shadow:0 8px 18px rgba(0,0,0,.16)',
      'max-width:280px',
      'line-height:1.4'
    ].join(';');
    document.body.appendChild(tip);
    setTimeout(() => tip.remove(), 3200);
  };

  btn.addEventListener('click', async () => {
    if (btn.dataset.loading === '1') return;
    btn.dataset.loading = '1';
    const originalText = btn.textContent;
    btn.textContent = '采集中...';
    btn.disabled = true;
    try {
      const resp = await chrome.runtime.sendMessage({
        action: 'COLLECT_CURRENT_TEMU_GOODS',
        url: location.href,
        goodsId,
        pageRawData: buyerRawDataCache || window.__TEMU_BUYER_RAW_DATA_CACHE__ || null
      });
      window.__TEMU_LAST_COLLECT_RESULT__ = resp || null;
      btn.dataset.lastResult = resp ? JSON.stringify(resp).slice(0, 200) : '';
      if (resp?.success) {
        showToast('采集成功，已进入采集上架流程');
      } else {
        showToast(resp?.error || '采集失败', true);
      }
    } catch (err) {
      window.__TEMU_LAST_COLLECT_RESULT__ = { success: false, error: err?.message || 'unknown' };
      btn.dataset.lastResult = err?.message || 'unknown';
      showToast(err?.message || '采集失败', true);
    } finally {
      btn.dataset.loading = '0';
      btn.disabled = false;
      btn.textContent = originalText;
    }
  });

  document.body.appendChild(btn);
}

function scheduleBuyerCollectInjector() {
  if (!isTemuBuyerPage()) return;
  refreshBuyerRawDataCache();
  ensureBuyerCollectButton();
  const observer = new MutationObserver(() => {
    refreshBuyerRawDataCache();
    ensureBuyerCollectButton();
  });
  observer.observe(document.documentElement, { childList: true, subtree: true });
  setTimeout(() => observer.disconnect(), 15000);
}

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

function isTemuLoginPage() {
  try {
    const host = location.hostname || '';
    if (host !== 'www.temu.com') return false;
    const path = location.pathname || '';
    const href = location.href || '';
    const title = document.title || '';
    const body = (document.body?.innerText || '').slice(0, 1200);
    return /login\.html|\/login\b/i.test(path) || /login\.html/i.test(href) || /鐧诲綍|璇风櫥褰晐楠岃瘉鐮亅楠岃瘉/i.test(title + body);
  } catch (error) {
    return false;
  }
}

function getTemuReturnUrl() {
  return 'https://www.temu.com/';
}

async function clearTemuCurrentPageData() {
  try { localStorage.clear(); } catch (error) {}
  try { sessionStorage.clear(); } catch (error) {}
  try {
    if ('caches' in window) {
      const keys = await caches.keys();
      await Promise.all(keys.map(key => caches.delete(key)));
    }
  } catch (error) {}
  try {
    if (navigator.serviceWorker?.getRegistrations) {
      const regs = await navigator.serviceWorker.getRegistrations();
      await Promise.all(regs.map(reg => reg.unregister().catch(() => {})));
    }
  } catch (error) {}
}

function ensureTemuSessionResetBanner() {
  if (!document.body || document.getElementById('temu-session-reset-banner')) return;
  if ((location.hostname || '') !== 'www.temu.com') return;
  if (!isTemuLoginPage()) return;

  const banner = document.createElement('div');
  banner.id = 'temu-session-reset-banner';
  banner.style.cssText = [
    'position:fixed',
    'top:16px',
    'left:50%',
    'transform:translateX(-50%)',
    'z-index:9999999',
    'width:min(560px,calc(100vw - 24px))',
    'background:#111827',
    'color:#fff',
    'border-radius:14px',
    'box-shadow:0 16px 40px rgba(0,0,0,.24)',
    'padding:14px 16px',
    'display:flex',
    'gap:12px',
    'align-items:center'
  ].join(';');
  banner.innerHTML = `
    <div style="flex:1;min-width:0;">
      <div style="font-size:14px;font-weight:700;line-height:1.4;">检测到 Temu 会话已失效</div>
      <div style="font-size:12px;line-height:1.5;color:#d1d5db;margin-top:4px;">点击“清理缓存并回首页”会清理 Temu 站点会话数据并打开 Temu 首页，然后你可以手动继续登录或浏览。</div>
    </div>
    <button type="button" id="temu-session-reset-btn" style="flex-shrink:0;padding:10px 14px;border:0;border-radius:10px;background:#22c55e;color:#fff;font-weight:700;cursor:pointer;">清理缓存并回首页</button>
  `;
  document.body.appendChild(banner);

  banner.querySelector('#temu-session-reset-btn')?.addEventListener('click', async () => {
    const btn = banner.querySelector('#temu-session-reset-btn');
    if (btn) {
      btn.disabled = true;
      btn.textContent = '处理中...';
    }
    try {
      await chrome.runtime.sendMessage({ action: 'clearTemuSession' });
      await clearTemuCurrentPageData();
      banner.remove();
      location.replace(getTemuReturnUrl());
    } catch (error) {
      if (btn) {
        btn.disabled = false;
        btn.textContent = '清理缓存并回首页';
      }
      showError(`清理失败：${error.message}`);
    }
  });
}

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

if (temuContentScriptRuntime.sessionBannerTimer) {
  clearInterval(temuContentScriptRuntime.sessionBannerTimer);
}
temuContentScriptRuntime.sessionBannerTimer = setInterval(() => {
  ensureTemuSessionResetBanner();
}, 3000);

// ========== TEMU 后台弹窗清理（白名单版，参考大白鹅逻辑） ==========
const TEMU_SAFE_POPUP_CLEANER_KEY = 'temuSafePopupCleanerEnabled';
const TEMU_SAFE_POPUP_CLEANER_POS_KEY = 'temuSafePopupCleanerPosition';
const temuSafePopupCleanerState = {
  enabled: true,
  button: null,
  dragging: false,
  dragMoved: false,
  dragStartY: 0,
  dragOriginTop: 0
};

const TEMU_SAFE_POPUP_KEYWORDS = [
  '您的商品需重新报价',
  '店铺提效，促进生意',
  '放弃流量增长机会',
  '调整申报价做出了选择',
  '接受价格调整建议做出选择',
  '加入发货台的备货单就可以正常发货',
  '享高优权益',
  '商品降价提醒',
  '商品价格调整',
  '价格调整',
  '调整报价',
  '调整价格',
  '您有即将售罄或已售罄商品',
  '立刻增长',
  '立享流量红利',
  '一键搬运商品',
  '参与活动获取权益',
  '需重新报价',
  '查看全部商品',
  '商品价格调整参考',
  '确认调整，立享权益',
  '考试',
  '您有以下待办任务需要尽快处理'
];

function isTemuBackendPage() {
  try {
    return isTemuSellerBackendHost();
  } catch (error) {
    return false;
  }
}

function isSafePopupCleanerEnabled() {
  return temuSafePopupCleanerState.enabled !== false;
}

function getNodeText(node) {
  return String(node?.innerText || node?.textContent || '').replace(/\s+/g, ' ').trim();
}

const TEMU_SAFE_POPUP_ROOT_SELECTOR = [
  '[data-testid="beast-core-modal"]',
  '[data-testid="beast-core-modal-innerWrapper"]',
  '[role="dialog"]',
  '[aria-modal="true"]',
  '[class*="modal"]',
  '[class*="Modal"]',
  '[class*="dialog"]',
  '[class*="Dialog"]'
].join(',');

const TEMU_SAFE_POPUP_CLOSE_TEXTS = new Set([
  '关闭',
  '取消',
  '我知道了',
  '知道了',
  '稍后再说',
  '暂不',
  '暂不处理',
  '暂不调整',
  '下次再说',
  '以后再说',
  '跳过',
  '忽略',
  'Close',
  'Cancel',
  'Not now',
  'Later',
  'Got it'
]);

const TEMU_SAFE_POPUP_RISKY_ACTION_RE = /确认调整|接受|同意|提交|保存|立即|立刻|马上|一键|去处理|去查看|查看全部|参与|报名|开通|升级|调整报价|重新报价|增长|权益|Confirm|Accept|Submit|Apply|Continue|OK/i;

function queryTemuPopupElements(root, selector) {
  try {
    return Array.from(root?.querySelectorAll?.(selector) || []);
  } catch (_) {
    return [];
  }
}

function isTemuBackendPopupShell(node) {
  if (!node || node.nodeType !== Node.ELEMENT_NODE) return false;
  const testId = node.getAttribute?.('data-testid') || node.dataset?.testid || '';
  return testId === 'beast-core-modal'
    || testId === 'beast-core-modal-innerWrapper'
    || node.getAttribute?.('role') === 'dialog'
    || node.getAttribute?.('aria-modal') === 'true'
    || /\b(?:modal|dialog)\b/i.test(String(node.className || ''));
}

function findTemuBackendPopupRoot(node) {
  if (!node || node.nodeType !== Node.ELEMENT_NODE) return null;
  const beastRoot = node.closest?.('[data-testid="beast-core-modal"]');
  if (beastRoot) return beastRoot;

  let current = node;
  let root = null;
  for (let depth = 0; current && current !== document.body && depth < 8; depth += 1) {
    if (isTemuBackendPopupShell(current)) root = current;
    current = current.parentElement;
  }
  return root;
}

function shouldClearTemuBackendPopup(node) {
  const text = getNodeText(node);
  if (!text) return false;
  if (node.querySelector?.('table,[role="table"],[role="grid"],input[type="checkbox"],[role="checkbox"],[aria-checked]')) return false;
  return TEMU_SAFE_POPUP_KEYWORDS.some(keyword => text.includes(keyword));
}

function isTemuElementVisible(el) {
  if (!el || el.nodeType !== Node.ELEMENT_NODE) return false;
  const rect = el.getBoundingClientRect?.();
  if (!rect || rect.width <= 0 || rect.height <= 0) return false;
  const style = window.getComputedStyle?.(el);
  return !style || (style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0');
}

function normalizeTemuPopupActionText(value) {
  return String(value || '').replace(/\s+/g, ' ').trim();
}

function readTemuPopupControlDescriptor(el) {
  return [
    normalizeTemuPopupActionText(el?.innerText || el?.textContent || ''),
    el?.getAttribute?.('aria-label') || '',
    el?.getAttribute?.('title') || '',
    el?.getAttribute?.('data-testid') || '',
    String(el?.className || '')
  ].join(' ');
}

function isTemuSafePopupCloseControl(el) {
  if (!el || el === document.body || !isTemuElementVisible(el)) return false;
  const text = normalizeTemuPopupActionText(el.innerText || el.textContent || '');
  const descriptor = readTemuPopupControlDescriptor(el);
  const matchedByText = TEMU_SAFE_POPUP_CLOSE_TEXTS.has(text);
  const matchedByAttr = /close|cancel|dismiss|关闭|取消|modal-close|icon-close/i.test(descriptor);
  if (!matchedByText && !matchedByAttr) return false;
  if (!matchedByText && text && TEMU_SAFE_POPUP_RISKY_ACTION_RE.test(text)) return false;
  if (!matchedByText && text.length > 20) return false;
  return true;
}

function clickTemuBackendPopupClose(root) {
  const controls = queryTemuPopupElements(root, [
    'button',
    '[role="button"]',
    'a',
    '[aria-label]',
    '[title]',
    '[data-testid]',
    '[class*="close"]',
    '[class*="Close"]',
    '[class*="cancel"]',
    '[class*="Cancel"]',
    'span',
    'i',
    'svg'
  ].join(',')).slice(0, 120);

  for (const el of controls) {
    const target = el.closest?.('button,[role="button"],a') || el;
    if (!isTemuSafePopupCloseControl(el) && !isTemuSafePopupCloseControl(target)) continue;
    try {
      target.click();
      return true;
    } catch (_) {}
  }
  return false;
}

function isTemuPopupMaskNode(node) {
  if (!node || node.nodeType !== Node.ELEMENT_NODE) return false;
  const testId = node.getAttribute?.('data-testid') || '';
  const className = String(node.className || '');
  return testId === 'beast-core-modal-mask'
    || (/mask|overlay|backdrop/i.test(className) && !getNodeText(node));
}

function forceHideTemuPopupElement(el) {
  if (!el || el.nodeType !== Node.ELEMENT_NODE) return;
  el.style.setProperty('display', 'none', 'important');
  el.style.setProperty('visibility', 'hidden', 'important');
  el.style.setProperty('pointer-events', 'none', 'important');
}

function clearTemuPopupPageLocks() {
  try {
    document.body.style.removeProperty('overflow');
    document.body.style.removeProperty('padding-right');
    document.documentElement.style.removeProperty('overflow');
    document.documentElement.style.removeProperty('padding-right');
  } catch (error) {}
}

function hideTemuBackendPopupMasks(root) {
  const masks = [
    root?.previousElementSibling,
    root?.nextElementSibling,
    ...Array.from(root?.parentElement?.children || []),
    ...queryTemuPopupElements(document, '[data-testid="beast-core-modal-mask"], [class*="mask"], [class*="Mask"], [class*="overlay"], [class*="Overlay"], [class*="backdrop"], [class*="Backdrop"]')
  ];
  masks.forEach(mask => {
    if (isTemuPopupMaskNode(mask)) forceHideTemuPopupElement(mask);
  });
}

function hideTemuBackendPopup(root) {
  if (!root || root.dataset?.xiaoqingwaPopupCleaned === '1') return false;
  root.dataset.xiaoqingwaPopupCleaned = '1';

  if (clickTemuBackendPopupClose(root)) {
    setTimeout(() => {
      if (root.isConnected && isTemuElementVisible(root)) {
        forceHideTemuPopupElement(root);
        hideTemuBackendPopupMasks(root);
      }
      clearTemuPopupPageLocks();
    }, 300);
    return true;
  }

  forceHideTemuPopupElement(root);
  hideTemuBackendPopupMasks(root);
  clearTemuPopupPageLocks();
  return true;
}

function scanTemuBackendPopupNode(node) {
  if (!isSafePopupCleanerEnabled() || !isTemuBackendPage() || !node || node.nodeType !== Node.ELEMENT_NODE) return 0;
  const candidates = [];
  const seen = new Set();
  const addCandidate = candidate => {
    const root = findTemuBackendPopupRoot(candidate);
    if (!root || seen.has(root)) return;
    seen.add(root);
    candidates.push(root);
  };
  if (isTemuBackendPopupShell(node)) addCandidate(node);
  queryTemuPopupElements(node, TEMU_SAFE_POPUP_ROOT_SELECTOR).forEach(addCandidate);

  let cleaned = 0;
  for (const root of candidates) {
    if (!root || root.dataset?.xiaoqingwaPopupCleaned === '1') continue;
    if (!shouldClearTemuBackendPopup(root)) continue;
    if (hideTemuBackendPopup(root)) cleaned += 1;
  }
  return cleaned;
}

function scanExistingTemuBackendPopups() {
  if (!document.body) return 0;
  return scanTemuBackendPopupNode(document.body);
}

function updateSafePopupCleanerButton() {
  const btn = temuSafePopupCleanerState.button;
  if (!btn) return;
  const enabled = isSafePopupCleanerEnabled();
  btn.textContent = enabled ? '弹窗清理：开' : '弹窗清理：关';
  btn.style.background = enabled ? '#2563eb' : '#6b7280';
}

function saveSafePopupCleanerEnabled(enabled) {
  temuSafePopupCleanerState.enabled = Boolean(enabled);
  safeChromeStorageSet({ [TEMU_SAFE_POPUP_CLEANER_KEY]: temuSafePopupCleanerState.enabled }, '后台弹窗清理开关');
  updateSafePopupCleanerButton();
  if (temuSafePopupCleanerState.enabled) scanExistingTemuBackendPopups();
}

function clampSafePopupCleanerTop(top) {
  const maxTop = Math.max(8, window.innerHeight - 44);
  return Math.max(8, Math.min(Number(top) || 150, maxTop));
}

function applySafePopupCleanerPosition(top) {
  const btn = temuSafePopupCleanerState.button;
  if (!btn) return;
  btn.style.top = `${clampSafePopupCleanerTop(top)}px`;
}

function ensureSafePopupCleanerButton() {
  if (!document.body || !isTemuBackendPage()) return;
  if (temuSafePopupCleanerState.button?.isConnected) {
    updateSafePopupCleanerButton();
    return;
  }

  const btn = document.createElement('button');
  btn.id = 'xiaoqingwa-safe-popup-cleaner-toggle';
  btn.type = 'button';
  btn.title = '只清理命中文案白名单的 TEMU 后台提示弹窗';
  btn.style.cssText = [
    'position:fixed',
    'right:-88px',
    'top:150px',
    'z-index:9999999',
    'width:132px',
    'height:34px',
    'border:0',
    'border-radius:10px 0 0 10px',
    'color:#fff',
    'font-size:13px',
    'font-weight:800',
    'box-shadow:0 12px 28px rgba(15,23,42,.22)',
    'cursor:pointer',
    'transition:right .18s ease, background .15s ease',
    'user-select:none'
  ].join(';');
  btn.addEventListener('mouseenter', () => { btn.style.right = '0px'; });
  btn.addEventListener('mouseleave', () => {
    if (!temuSafePopupCleanerState.dragging) btn.style.right = '-88px';
  });
  btn.addEventListener('pointerdown', (event) => {
    if (event.button !== 0) return;
    const rect = btn.getBoundingClientRect();
    temuSafePopupCleanerState.dragging = true;
    temuSafePopupCleanerState.dragMoved = false;
    temuSafePopupCleanerState.dragStartY = event.clientY;
    temuSafePopupCleanerState.dragOriginTop = rect.top;
    btn.setPointerCapture?.(event.pointerId);
  });
  window.addEventListener('pointermove', (event) => {
    if (!temuSafePopupCleanerState.dragging) return;
    const dy = event.clientY - temuSafePopupCleanerState.dragStartY;
    if (Math.abs(dy) > 4) temuSafePopupCleanerState.dragMoved = true;
    applySafePopupCleanerPosition(temuSafePopupCleanerState.dragOriginTop + dy);
  }, { passive: true });
  const stopDrag = () => {
    if (!temuSafePopupCleanerState.dragging) return;
    temuSafePopupCleanerState.dragging = false;
    const top = parseFloat(btn.style.top || '150') || 150;
    safeChromeStorageSet({ [TEMU_SAFE_POPUP_CLEANER_POS_KEY]: top }, '后台弹窗清理位置');
    setTimeout(() => { temuSafePopupCleanerState.dragMoved = false; }, 0);
  };
  window.addEventListener('pointerup', stopDrag, { passive: true });
  window.addEventListener('pointercancel', stopDrag, { passive: true });
  btn.addEventListener('click', (event) => {
    if (temuSafePopupCleanerState.dragMoved) {
      event.preventDefault();
      return;
    }
    saveSafePopupCleanerEnabled(!isSafePopupCleanerEnabled());
  });

  document.body.appendChild(btn);
  temuSafePopupCleanerState.button = btn;
  updateSafePopupCleanerButton();
  try {
    chrome.storage?.local?.get({ [TEMU_SAFE_POPUP_CLEANER_POS_KEY]: 150 }, (result) => {
      applySafePopupCleanerPosition(result?.[TEMU_SAFE_POPUP_CLEANER_POS_KEY] || 150);
    });
  } catch (error) {}
}

function initSafeTemuBackendPopupCleaner() {
  if (!isTemuBackendPage() || !document.body) return;
  ensureSafePopupCleanerButton();
  try {
    chrome.storage?.local?.get({ [TEMU_SAFE_POPUP_CLEANER_KEY]: true }, (result) => {
      temuSafePopupCleanerState.enabled = result?.[TEMU_SAFE_POPUP_CLEANER_KEY] !== false;
      updateSafePopupCleanerButton();
      scanExistingTemuBackendPopups();
    });
  } catch (error) {
    scanExistingTemuBackendPopups();
  }

  if (temuContentScriptRuntime.backendCleanerObserver) {
    temuContentScriptRuntime.backendCleanerObserver.disconnect();
  }
  temuContentScriptRuntime.backendCleanerObserver = new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      for (const node of mutation.addedNodes || []) {
        scanTemuBackendPopupNode(node);
      }
    }
  });
  temuContentScriptRuntime.backendCleanerObserver.observe(document.body, { childList: true, subtree: true });
}

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

if (temuContentScriptRuntime.backendCleanerHeartbeat) {
  clearInterval(temuContentScriptRuntime.backendCleanerHeartbeat);
}
temuContentScriptRuntime.backendCleanerHeartbeat = setInterval(() => {
  if (!isTemuBackendPage()) return;
  ensureSafePopupCleanerButton();
  scanExistingTemuBackendPopups();
}, 4000);

// ========== TEMU 鍓嶅彴娓呯悊缂撳瓨鎸夐挳锛堣鐩栧悗鍙扮増鏈級 ==========
function isTemuFrontendPage() {
  try {
    const host = location.hostname || '';
    if (!/(^|\.)temu\.com$/i.test(host)) return false;
    if (/(^|\.)agentseller\.temu\.com$/i.test(host)) return false;
    if (/(^|\.)seller\.kuajingmaihuo\.com$/i.test(host)) return false;
    return true;
  } catch (error) {
    return false;
  }
}

function ensureTemuFrontendCacheResetButton() {
  if (!document.body || !isTemuFrontendPage()) return;
  if (document.getElementById('temu-frontend-cache-reset-btn')) return;

  const button = document.createElement('button');
  button.id = 'temu-frontend-cache-reset-btn';
  button.type = 'button';
  button.textContent = '清理缓存';
  button.style.cssText = [
    'position:fixed',
    'right:18px',
    'bottom:18px',
    'z-index:9999999',
    'padding:10px 14px',
    'border:0',
    'border-radius:10px',
    'background:#22c55e',
    'color:#fff',
    'font-size:13px',
    'font-weight:700',
    'box-shadow:0 16px 40px rgba(0,0,0,.24)',
    'cursor:pointer'
  ].join(';');

  button.addEventListener('click', async () => {
    if (button.dataset.loading === '1') return;
    button.dataset.loading = '1';
    const originalText = button.textContent;
    button.textContent = '清理中...';
    button.disabled = true;
    try {
      await chrome.runtime.sendMessage({ action: 'clearTemuSession' });
      await clearTemuCurrentPageData();
      location.replace(getTemuReturnUrl());
    } catch (error) {
      showError(`清理失败：${error?.message || error}`);
      button.dataset.loading = '0';
      button.disabled = false;
      button.textContent = originalText;
    }
  });

  document.body.appendChild(button);
}

function initTemuFrontendCacheResetButton() {
  if (!isTemuFrontendPage()) return;
  ensureTemuFrontendCacheResetButton();
}

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

if (temuContentScriptRuntime.frontendResetTimer) {
  clearInterval(temuContentScriptRuntime.frontendResetTimer);
}
temuContentScriptRuntime.frontendResetTimer = setInterval(() => {
  initTemuFrontendCacheResetButton();
}, 3000);

function showSaveToast(spuId, taskCount) {
  const existingToast = document.getElementById('temu-save-toast');
  if (existingToast) existingToast.remove();

  if (!document.getElementById('temu-toast-style')) {
    const style = document.createElement('style');
    style.id = 'temu-toast-style';
    style.textContent = `
      @keyframes temu-toast-in {
        from { opacity: 0; transform: translate(-50%, -55%); }
        to { opacity: 1; transform: translate(-50%, -50%); }
      }
    `;
    document.head.appendChild(style);
  }

  const toast = document.createElement('div');
  toast.id = 'temu-save-toast';
  toast.style.cssText = [
    'position:fixed',
    'top:50%',
    'left:50%',
    'transform:translate(-50%,-50%)',
    'background:#fff',
    'border:1px solid #e8e8e8',
    'border-left:4px solid #037ef3',
    'border-radius:10px',
    'padding:14px 20px',
    'z-index:999999',
    'font-size:14px',
    'box-shadow:0 10px 28px rgba(15,23,42,0.18)',
    'max-width:420px',
    'min-width:300px',
    'cursor:pointer',
    'animation:temu-toast-in 0.2s ease-out'
  ].join(';');

  toast.innerHTML = `
    <div style="display:flex;align-items:center;gap:10px;line-height:1.5;">
      <span style="font-size:18px;">📝</span>
      <div>
        <div style="font-weight:600;margin-bottom:2px;">SPU ${spuId} 合规信息已提交</div>
        <div style="color:#64748b;font-size:12px;">${taskCount} 个合规项，点击可保存为模板</div>
      </div>
    </div>
  `;

  const openModal = () => {
    toast.style.display = 'none';
    const modal = document.createElement('div');
    modal.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.4);display:flex;justify-content:center;align-items:center;z-index:999999;';
    modal.innerHTML = `
      <div style="background:white;border-radius:10px;padding:24px;min-width:360px;box-shadow:0 12px 32px rgba(0,0,0,0.2);">
        <h3 style="margin:0 0 16px 0;font-size:16px;">📝 保存为模板</h3>
        <div style="margin-bottom:8px;font-size:13px;color:#666;">SPU ${spuId} · ${taskCount} 个合规项</div>
        <div style="margin-bottom:16px;">
          <input type="text" id="temu-tpl-name-input" style="width:100%;padding:8px 12px;border:1px solid #d9d9d9;border-radius:4px;font-size:14px;outline:none;" value="模板-${spuId}" />
        </div>
        <div style="display:flex;justify-content:flex-end;gap:8px;">
          <button id="temu-tpl-cancel" style="padding:6px 16px;border:1px solid #d9d9d9;border-radius:4px;background:white;cursor:pointer;font-size:14px;">取消</button>
          <button id="temu-tpl-confirm" style="padding:6px 16px;border:none;border-radius:4px;background:#037ef3;color:white;cursor:pointer;font-size:14px;">保存</button>
        </div>
      </div>
    `;
    document.body.appendChild(modal);

    const nameInput = modal.querySelector('#temu-tpl-name-input');
    nameInput.select();

    const closeModal = () => {
      modal.remove();
      toast.style.display = '';
    };

    modal.querySelector('#temu-tpl-cancel').onclick = closeModal;
    modal.onclick = (e) => { if (e.target === modal) closeModal(); };
    nameInput.addEventListener('keydown', (e) => {
      if (e.key === 'Enter') modal.querySelector('#temu-tpl-confirm').click();
    });

    modal.querySelector('#temu-tpl-confirm').onclick = () => {
      const templateName = nameInput.value.trim();
      if (!templateName) {
        nameInput.style.borderColor = 'red';
        return;
      }

      modal.remove();
      toast.style.display = '';
      toast.style.background = '#f0f7ff';
      toast.innerHTML = '<div style="padding:4px 0;">保存中...</div>';

      chrome.runtime.sendMessage({
        action: 'confirmSaveFromToast',
        templateName
      }, (response) => {
        if (chrome.runtime.lastError) {
          toast.innerHTML = '<div style="padding:4px 0;">保存失败</div>';
          return;
        }

        if (response && response.success && !response.localOnly) {
          toast.style.borderLeftColor = '#52c41a';
          const statusText = `云端保存成功：${response.templateName}（${response.taskCount}项）`;
          const warningText = response.warning
            ? `<div style="padding:2px 0 0;font-size:12px;color:#8c6d1f;">${escapeHtml(String(response.warning))}</div>`
            : '';
          toast.innerHTML = `<div style="padding:4px 0;">${statusText}</div>${warningText}`;
          setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transition = 'opacity 0.5s';
            setTimeout(() => toast.remove(), 500);
          }, 3000);
        } else {
          toast.style.borderLeftColor = '#dc2626';
          toast.innerHTML = `<div style="padding:4px 0;">${response?.error || '保存失败'}</div>`;
          setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transition = 'opacity 0.5s';
            setTimeout(() => toast.remove(), 500);
          }, 3000);
        }
      });
    };
  };

  toast.addEventListener('click', openModal);
  document.body.appendChild(toast);

  setTimeout(() => {
    if (document.body.contains(toast)) {
      toast.style.opacity = '0';
      toast.style.transition = 'opacity 0.5s';
      setTimeout(() => toast.remove(), 500);
    }
  }, 10000);
}


// ========== TEMU 官方草稿箱：一键批量上架 ==========
function isTemuProductDraftPage() {
  try {
    if (!isTemuSellerBackendHost()) return false;
    return /^\/goods\/draft(?:\/)?$/i.test(location.pathname || '');
  } catch (_) {
    return false;
  }
}

function findTemuDraftToolbarElement() {
  const actionButtons = Array.from(document.querySelectorAll('button, a, [role="button"]'));
  const byText = (text) => actionButtons.find(el => String(el.innerText || el.textContent || '').replace(/\s+/g, '').includes(text));
  const batchDeleteButton = byText('批量删除草稿');
  const createButton = byText('新建商品');
  const ref = batchDeleteButton || createButton;
  if (!ref) return null;
  const candidates = [
    ref.parentElement,
    ref.parentElement?.parentElement,
    ref.closest?.('[class*="toolbar"], [class*="action"], [class*="button"], [class*="operation"]')
  ].filter(Boolean);
  return candidates.find(el => {
    const text = String(el.innerText || el.textContent || '').replace(/\s+/g, '');
    return text.includes('新建商品') || text.includes('批量删除草稿');
  }) || ref.parentElement;
}

function getTemuDraftRowCheckbox(row) {
  if (!row) return null;
  return row.querySelector('input[type="checkbox"], [data-testid="beast-core-checkbox"], [role="checkbox"]');
}

function isTemuDraftRowSelected(row) {
  const input = row?.querySelector?.('input[type="checkbox"]');
  if (input?.checked) return true;
  const checkbox = getTemuDraftRowCheckbox(row);
  if (!checkbox) return false;
  const checkedAttr = checkbox.getAttribute?.('data-checked') || checkbox.getAttribute?.('aria-checked');
  if (String(checkedAttr).toLowerCase() === 'true') return true;
  return /\bchecked\b|CBX_checked|is-checked/i.test(String(checkbox.className || ''));
}

function extractTemuDraftIdFromRow(row) {
  if (!row) return '';
  const cells = Array.from(row.children || []);
  const secondCellText = String(
    cells[1]?.querySelector?.('span')?.textContent ||
    cells[1]?.textContent ||
    ''
  ).trim();
  const secondCellMatch = secondCellText.match(/\b(\d{6,})\b/);
  if (secondCellMatch) return secondCellMatch[1];
  const fromAttrs = [
    row.getAttribute?.('data-row-key'),
    row.getAttribute?.('data-row-id'),
    row.dataset?.rowKey,
    row.dataset?.rowId
  ].map(value => String(value || '').trim()).find(value => /^\d{6,}$/.test(value));
  if (fromAttrs) return fromAttrs;
  const hrefText = Array.from(row.querySelectorAll?.('a[href]') || [])
    .map(a => a.getAttribute('href') || '')
    .join(' ');
  const hrefMatch = hrefText.match(/productDraftId[=/%3D]+(\d{6,})/i);
  if (hrefMatch) return hrefMatch[1];
  const rowText = String(row.innerText || row.textContent || '').replace(/\s+/g, ' ').trim();
  const textMatch = rowText.match(/^\D*(\d{6,})\b/);
  return textMatch ? textMatch[1] : '';
}

function collectSelectedTemuDraftIds() {
  if (!isTemuProductDraftPage()) return [];
  const stickyRows = Array.from(document.querySelectorAll('tbody > tr > td'))
    .filter(cell => Array.from(cell.classList || []).some(cls => String(cls).includes('TB_leftSticky_')))
    .filter(cell => cell.querySelector?.('label[data-checked="true"], [aria-checked="true"], input[type="checkbox"]:checked'))
    .map(cell => cell.parentElement)
    .filter(Boolean);
  const fallbackRows = Array.from(document.querySelectorAll('tr[data-testid="beast-core-table-body-tr"], tr, [role="row"]'))
    .filter(row => {
      const text = String(row.innerText || row.textContent || '').trim();
      if (!text || /SPU\s*ID|商品名称|商品分类|修改时间/.test(text) && !/编辑|删除草稿/.test(text)) return false;
      return row.querySelector?.('input[type="checkbox"], [data-testid="beast-core-checkbox"], [role="checkbox"]');
    });
  const rows = stickyRows.length ? stickyRows : fallbackRows;
  return Array.from(new Set(rows
    .filter(isTemuDraftRowSelected)
    .map(extractTemuDraftIdFromRow)
    .filter(id => /^\d{6,}$/.test(id))));
}

function isTemuRuntimeReconnectError(error) {
  const text = typeof error === 'string'
    ? error
    : (error?.message || error?.error || String(error || ''));
  return /Extension context invalidated|Execution plugin is not connected|Receiving end does not exist|Could not establish connection|消息发送失败|插件通信不可用|插件通信失败|background 响应超时/i.test(text);
}

function getTemuRuntimeReconnectMessage(featureName = '当前功能') {
  return `${featureName}连接已失效。通常是小青蛙助手刚更新或重载后，当前 TEMU 页面还连着旧插件脚本；请刷新 TEMU 草稿箱页面后重试。如果仍失败，请在 Chrome 扩展管理页重新加载“小青蛙助手”。`;
}

function sendTemuDraftPublishMessage(payload) {
  return new Promise((resolve, reject) => {
    let runtime = null;
    try {
      runtime = globalThis.chrome?.runtime || null;
    } catch (error) {
      reject(new Error(isTemuRuntimeReconnectError(error) ? getTemuRuntimeReconnectMessage('一键批量上架') : (error?.message || String(error))));
      return;
    }
    if (!runtime?.sendMessage) {
      reject(new Error(getTemuRuntimeReconnectMessage('一键批量上架')));
      return;
    }
    try {
      runtime.sendMessage(payload, (response) => {
        let lastError = null;
        try {
          lastError = runtime.lastError || null;
        } catch (error) {
          lastError = error;
        }
        if (lastError) {
          const rawMessage = lastError.message || String(lastError) || '插件通信失败';
          reject(new Error(isTemuRuntimeReconnectError(rawMessage) ? getTemuRuntimeReconnectMessage('一键批量上架') : rawMessage));
          return;
        }
        resolve(response || {});
      });
    } catch (error) {
      reject(new Error(isTemuRuntimeReconnectError(error) ? getTemuRuntimeReconnectMessage('一键批量上架') : (error?.message || String(error))));
    }
  });
}

function ensureTemuDraftPublishPanel() {
  let panel = document.getElementById('temu-draft-publish-panel');
  if (panel) return panel;
  panel = document.createElement('div');
  panel.id = 'temu-draft-publish-panel';
  panel.style.cssText = [
    'position:fixed',
    'right:22px',
    'top:86px',
    'z-index:9999999',
    'width:360px',
    'max-width:calc(100vw - 44px)',
    'background:#fff',
    'border:1px solid rgba(15,23,42,.12)',
    'border-radius:12px',
    'box-shadow:0 18px 48px rgba(15,23,42,.18)',
    'font-size:13px',
    'line-height:1.5',
    'color:#1f2937',
    'overflow:hidden',
    'display:none'
  ].join(';');
  document.body.appendChild(panel);
  return panel;
}

function renderTemuDraftPublishPanel(state = {}) {
  const panel = ensureTemuDraftPublishPanel();
  const status = state.status || 'running';
  const title = state.title || (status === 'running' ? '正在批量上架草稿' : '批量上架结果');
  const message = state.message || '';
  const results = Array.isArray(state.results) ? state.results : [];
  const resultHtml = results.length ? `
    <div style="max-height:220px;overflow:auto;border-top:1px solid #eef2f7;margin-top:10px;padding-top:8px;">
      ${results.map(item => {
        const ok = item?.success;
        const color = ok ? '#059669' : '#dc2626';
        const suffix = ok
          ? (item.productId ? `发布成功，Product ID ${escapeHtml(item.productId)}` : '发布成功')
          : escapeHtml(item?.error || '发布失败');
        return `<div style="display:flex;gap:8px;margin:5px 0;">
          <span style="color:${color};font-weight:700;">${ok ? '✓' : '✗'}</span>
          <span style="min-width:86px;color:#475569;">${escapeHtml(item?.productDraftId || '')}</span>
          <span style="flex:1;color:${color};">${suffix}</span>
        </div>`;
      }).join('')}
    </div>
  ` : '';
  const closeButton = status === 'running' ? '' : '<button id="temu-draft-publish-close" type="button" style="border:1px solid #d1d5db;border-radius:6px;background:#fff;padding:5px 10px;cursor:pointer;">关闭</button>';
  const refreshButton = status === 'success' || status === 'partial'
    ? '<button id="temu-draft-publish-refresh" type="button" style="border:0;border-radius:6px;background:#0f766e;color:#fff;padding:5px 10px;cursor:pointer;">刷新草稿箱</button>'
    : '';
  panel.innerHTML = `
    <div style="padding:12px 14px;background:#f8fafc;border-bottom:1px solid #e5e7eb;display:flex;align-items:center;justify-content:space-between;gap:10px;">
      <div style="font-weight:700;">${escapeHtml(title)}</div>
      <div style="font-size:12px;color:#64748b;">小青蛙助手</div>
    </div>
    <div style="padding:12px 14px;">
      <div style="color:${status === 'failed' ? '#dc2626' : '#334155'};">${escapeHtml(message)}</div>
      ${resultHtml}
      <div style="display:flex;justify-content:flex-end;gap:8px;margin-top:12px;">${closeButton}${refreshButton}</div>
    </div>
  `;
  panel.style.display = 'block';
  panel.querySelector('#temu-draft-publish-close')?.addEventListener('click', () => {
    panel.style.display = 'none';
  });
  panel.querySelector('#temu-draft-publish-refresh')?.addEventListener('click', () => {
    location.reload();
  });
  return panel;
}

async function handleTemuDraftBatchPublish(button) {
  if (button?.dataset.loading === '1') return;
  const productDraftIds = collectSelectedTemuDraftIds();
  if (!productDraftIds.length) {
    showError('请先勾选要发布的草稿');
    return;
  }
  const originalText = button.textContent;
  button.dataset.loading = '1';
  button.disabled = true;
  button.textContent = `发布中 ${productDraftIds.length} 条...`;
  renderTemuDraftPublishPanel({
    status: 'running',
    message: `正在按 TEMU 官方接口逐条发布 ${productDraftIds.length} 条草稿，请不要关闭当前页面。`
  });
  const progressTaskId = `temu-draft-publish-${Date.now()}-${Math.random().toString(36).slice(2)}`;
  try {
    const response = await sendTemuDraftPublishMessage({
      action: 'BATCH_PUBLISH_TEMU_DRAFTS',
      params: { productDraftIds, progressTaskId }
    });
    const successCount = Number(response?.successCount || 0);
    const failCount = Number(response?.failCount || 0);
    const status = response?.success ? 'success' : (response?.partialSuccess ? 'partial' : 'failed');
    const message = response?.success
      ? `发布完成：成功 ${successCount} 条。`
      : response?.partialSuccess
        ? `发布完成：成功 ${successCount} 条，失败 ${failCount} 条。失败原因见下方 TEMU 返回。`
        : `发布失败：${response?.error || 'TEMU 未返回成功结果'}`;
    renderTemuDraftPublishPanel({
      status,
      title: '批量上架结果',
      message,
      results: response?.results || []
    });
    if (response?.success) {
      showSuccess(`草稿发布完成：${successCount} 条`);
      setTimeout(() => location.reload(), 1800);
    } else {
      showError(response?.error || '草稿发布失败');
    }
  } catch (error) {
    renderTemuDraftPublishPanel({
      status: 'failed',
      title: '批量上架失败',
      message: error?.message || String(error)
    });
    showError(error?.message || '草稿发布失败');
  } finally {
    button.dataset.loading = '0';
    button.disabled = false;
    button.textContent = originalText;
  }
}

function ensureTemuDraftBatchPublishButton() {
  if (!document.body) return;
  const existing = document.getElementById('temu-draft-batch-publish-btn');
  if (!isTemuProductDraftPage()) {
    existing?.remove();
    return;
  }
  const toolbar = findTemuDraftToolbarElement();
  if (!toolbar) return;
  if (existing && toolbar.contains(existing)) return;
  existing?.remove();

  const sourceButton = Array.from(document.querySelectorAll('button'))
    .find(btn => String(btn.innerText || btn.textContent || '').replace(/\s+/g, '').includes('新建商品'));
  const button = document.createElement('button');
  button.id = 'temu-draft-batch-publish-btn';
  button.type = 'button';
  button.textContent = '小青蛙一键批量上架';
  if (sourceButton?.className) button.className = sourceButton.className;
  button.style.cssText = [
    'margin-left:8px',
    'background:#0f766e',
    'border-color:#0f766e',
    'color:#fff',
    'font-weight:600',
    'cursor:pointer'
  ].join(';');
  button.addEventListener('click', () => handleTemuDraftBatchPublish(button));
  toolbar.appendChild(button);
}

function initTemuDraftBatchPublishButton() {
  ensureTemuDraftBatchPublishButton();
  if (temuContentScriptRuntime.temuDraftPublishObserver) {
    temuContentScriptRuntime.temuDraftPublishObserver.disconnect();
  }
  if (document.body) {
    temuContentScriptRuntime.temuDraftPublishObserver = new MutationObserver(() => {
      clearTimeout(temuContentScriptRuntime.temuDraftPublishTimer);
      temuContentScriptRuntime.temuDraftPublishTimer = setTimeout(ensureTemuDraftBatchPublishButton, 300);
    });
    temuContentScriptRuntime.temuDraftPublishObserver.observe(document.body, { childList: true, subtree: true });
  }
}

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

if (temuContentScriptRuntime.temuDraftPublishHeartbeat) {
  clearInterval(temuContentScriptRuntime.temuDraftPublishHeartbeat);
}
temuContentScriptRuntime.temuDraftPublishHeartbeat = setInterval(ensureTemuDraftBatchPublishButton, 3000);
