// 监听来自background.js的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'GET_TAOBAO_ORDERS') {
    // 提取订单数据
    fetchTaobaoOrders().then(orders => {
      // 发送订单数据到background
      chrome.runtime.sendMessage({
        type: 'ORDER_DATA',
        platform: 'taobao',
        data: orders
      }, (response) => {
        sendResponse({ success: true, orderCount: orders.length });
      });
    }).catch(error => {
      sendResponse({ error: error.message });
    });
    
    return true;
  }
});

// 获取淘宝订单数据
async function fetchTaobaoOrders() {
  return new Promise((resolve, reject) => {
    try {
      // 淘宝订单页面的DOM结构分析
      // 等待订单列表加载完成
      setTimeout(() => {
        const orderItems = document.querySelectorAll('.js-order-item');
        const orders = [];
        
        orderItems.forEach(item => {
          const orderId = item.getAttribute('data-id') || item.querySelector('.order-info .info-title .link')?.innerText;
          const orderTime = item.querySelector('.order-info .info-title .time')?.innerText;
          const totalAmount = item.querySelector('.price-content .price-amount')?.innerText;
          
          // 获取订单中的商品
          const products = [];
          const productElements = item.querySelectorAll('.order-bd .item-bd');
          
          productElements.forEach(product => {
            const productId = product.querySelector('.item-title a')?.getAttribute('href')?.match(/id=(\d+)/)?.[1];
            const productName = product.querySelector('.item-title a')?.innerText;
            const productPrice = product.querySelector('.item-price')?.innerText;
            const productQuantity = product.querySelector('.item-amount')?.innerText;
            const productImg = product.querySelector('.item-img img')?.src;
            
            products.push({
              id: productId,
              name: productName,
              price: productPrice,
              quantity: productQuantity,
              image: productImg
            });
          });
          
          if (orderId) {
            orders.push({
              orderId,
              orderTime,
              totalAmount,
              products,
              status: item.querySelector('.order-status a')?.innerText
            });
          }
        });
        
        resolve(orders);
      }, 2000); // 等待2秒确保页面加载完成
    } catch (error) {
      reject(error);
    }
  });
}

// 自动加载更多订单（可选）
async function loadMoreOrders() {
  const loadMoreBtn = document.querySelector('.pagination-next');
  if (loadMoreBtn && !loadMoreBtn.disabled) {
    loadMoreBtn.click();
    // 等待加载完成
    await new Promise(resolve => setTimeout(resolve, 3000));
    // 递归加载更多
    await loadMoreOrders();
  }
}