export async function runFetch1688Token(data, broadcastToExtension, respond) {
  try {
    // 找到已有的 1688 标签页，或创建新的
    let tab = null;
    let createdTab = false;
    const existingTabs = await chrome.tabs.query({});
    tab = existingTabs.find(t => t.url && t.url.includes("1688.com"));

    if (!tab) {
      broadcastToExtension({
        type: "system",
        text: "🔑 正在获取 1688 token... 打开 1688.com 页面"
      });
      tab = await chrome.tabs.create({ url: "https://www.1688.com/", active: true });
      createdTab = true;
      await new Promise((resolve) => {
        const timeout = setTimeout(() => resolve(), 20000);
        function listener(tabId, info) {
          if (tabId === tab.id && info.status === "complete") {
            chrome.tabs.onUpdated.removeListener(listener);
            clearTimeout(timeout);
            setTimeout(resolve, 5000); // 等页面 JS 完成
          }
        }
        chrome.tabs.onUpdated.addListener(listener);
      });
    }

    // 直接从页面 document.cookie 读取 token（绕过 chrome.cookies API 的域名问题）
    const cookieResults = await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      world: "MAIN",
      func: () => {
        const cookies = {};
        document.cookie.split(';').forEach(c => {
          const [k, ...v] = c.trim().split('=');
          if (k) cookies[k] = v.join('=');
        });
        return cookies;
      }
    });

    const allCookies = cookieResults?.[0]?.result || {};
    const tkValue = allCookies['_m_h5_tk'] || '';
    const tkEncValue = allCookies['_m_h5_tk_enc'] || '';

    if (createdTab && tab) {
      try { await chrome.tabs.remove(tab.id); } catch (_) {}
    }

    if (tkValue) {
      const result = {
        _m_h5_tk: tkValue,
        _m_h5_tk_enc: tkEncValue,
        all_cookies: allCookies,
        expires: null,
      };
      broadcastToExtension({
        type: "system",
        text: `✅ 1688 token 获取成功: ${tkValue.substring(0, 20)}...`
      });
      respond(result);
    } else {
      broadcastToExtension({
        type: "system",
        text: "❌ 未能获取 1688 token。请先在浏览器中访问 1688.com 并登录。"
      });
      respond(null, "Failed to get _m_h5_tk cookie. Please visit 1688.com in browser first.");
    }
  } catch (e) {
    respond(null, `fetch_1688_token error: ${e.message}`);
  }
}
