(() => {
  const OZ = 'https://sczfai.com';
  const OZAPI = 'https://sczfai.com/api';
  const SELLER = 'https://seller.ozon.ru';

  // [path, host, description, method?]
  const ENDPOINTS = [
    ['/Shops/lists', OZAPI, '店铺列表'],
    ['/PriceCalculator/calculate', OZAPI, '售价计算'],
    ['/PriceCalculator/getWeight', OZAPI, '重量'],
    ['/PriceCalculator/weightskuinfo', OZAPI, 'SKU 重量'],
    ['/PriceCalculator/pushSkus', OZAPI, '推 SKU'],
    ['/PriceCalculator/addSku', OZAPI, '加 SKU'],
    ['/PriceCalculator/skusList', OZAPI, 'SKU 列表'],
    ['/PriceCalculator/itemList', OZAPI, '商品列表'],
    ['/PriceCalculator/getLogisticsGroups', OZAPI, '物流分组'],
    ['/PriceCalculator/getLogisticsMethods?group_id=0', OZAPI, '物流方式'],
    ['/CollectBox/getGoodsInfo', OZAPI, '查询商品'],
    ['/CollectBox/Edit', OZAPI, '保存产品'],
    ['/CollectBox/Editskus', OZAPI, '保存 SKU'],
    ['/CollectBox/SaveProduct', OZAPI, '采集保存'],
    ['/CollectBox/UploadImageToOssByUrl', OZAPI, '图片上传'],
    ['/CollectBox/VerifyDuplicate', OZAPI, '查重'],
    ['/CollectBox/GetSourceUrlEntity', OZ, 'URL 取数据（客户提过 404）'],
    ['/OrderMatch/matchDomesticOrder', OZAPI, '匹配单订单'],
    ['/OrderMatch/batchMatchDomesticOrder', OZAPI, '批量匹配订单'],
  ];

  const $ = (id) => document.getElementById(id);
  const classForStatus = (s) => {
    if (s === 'NET' || s === 'TIMEOUT') return 's-net';
    if (s === 'pending') return 's-pending';
    const n = +s;
    if (n >= 500) return 's-5xx';
    if (n >= 400) return 's-4xx';
    if (n >= 200 && n < 400) return 's-200';
    return 's-net';
  };

  // 统一超时包装：任何 Promise 超过 ms 毫秒未完成就返回 fallback
  function withTimeout(p, ms, fallback) {
    return Promise.race([
      p,
      new Promise((r) => setTimeout(() => r(fallback), ms)),
    ]);
  }

  // 不带 credentials: 'include'，避免与服务端 ACAO:* 冲突导致 CORS preflight 失败。
  // 诊断只看 HTTP 状态码是否可达，不需要带登录态。
  function probe(url, method = 'POST') {
    const ac = new AbortController();
    const to = setTimeout(() => ac.abort(), 8000);
    const opts = { method, signal: ac.signal };
    if (method === 'POST') {
      opts.headers = { 'Content-Type': 'application/json' };
      opts.body = '{}';
    }
    return fetch(url, opts)
      .then((r) => {
        clearTimeout(to);
        return { status: r.status, ok: r.ok };
      })
      .catch((e) => {
        clearTimeout(to);
        const isAbort = e && (e.name === 'AbortError' || /aborted/i.test(e.message || ''));
        return { status: isAbort ? 'TIMEOUT' : 'NET', error: (e && e.message) || String(e) };
      });
  }

  function cookiesGetAll(query) {
    return withTimeout(
      new Promise((resolve) => {
        try {
          chrome.cookies.getAll(query, (c) => {
            const le = chrome.runtime && chrome.runtime.lastError;
            if (le) resolve({ _err: le.message });
            else resolve(c || []);
          });
        } catch (e) {
          resolve({ _err: (e && e.message) || String(e) });
        }
      }),
      3000,
      { _err: 'timeout(3s)' }
    );
  }

  function tabsQuery(q) {
    return withTimeout(
      new Promise((resolve) => {
        try {
          chrome.tabs.query(q, (t) => {
            const le = chrome.runtime && chrome.runtime.lastError;
            if (le) resolve({ _err: le.message });
            else resolve(t || []);
          });
        } catch (e) {
          resolve({ _err: (e && e.message) || String(e) });
        }
      }),
      3000,
      { _err: 'timeout(3s)' }
    );
  }

  function simplifyCookie(c) {
    return {
      name: c.name,
      value_preview: typeof c.value === 'string'
        ? (c.value.length > 40 ? c.value.slice(0, 40) + `…(len=${c.value.length})` : c.value)
        : c.value,
      domain: c.domain,
      path: c.path,
      secure: c.secure,
      httpOnly: c.httpOnly,
      sameSite: c.sameSite,
      session: c.session,
      partitionKey: c.partitionKey || null,
    };
  }

  // 在目标站已打开的标签里读 document.cookie / localStorage / sessionStorage
  async function inspectTab(host) {
    const tabsOrErr = await tabsQuery({ url: host + '/*' });
    if (!Array.isArray(tabsOrErr)) return { ok: false, reason: 'tabs.query: ' + tabsOrErr._err };
    if (!tabsOrErr.length) return { ok: false, reason: '无打开的标签页' };
    const tab = tabsOrErr[0];
    try {
      const exec = chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: () => {
          const snap = (s) => {
            const out = {};
            try {
              for (let i = 0; i < s.length; i++) {
                const k = s.key(i);
                const v = s.getItem(k);
                out[k] = typeof v === 'string' && v.length > 60 ? v.slice(0, 60) + `…(len=${v.length})` : v;
              }
            } catch (e) { out.__err = String(e); }
            return out;
          };
          return {
            url: location.href,
            cookie: document.cookie || '',
            localStorage: snap(localStorage),
            sessionStorage: snap(sessionStorage),
          };
        },
      });
      const res = await withTimeout(exec, 8000, { _timeout: true });
      if (res && res._timeout) return { ok: false, reason: 'scripting.executeScript 超时(8s)', tabUrl: tab.url };
      const first = Array.isArray(res) ? res[0] : null;
      if (!first || !first.result) return { ok: false, reason: '无返回结果', tabUrl: tab.url };
      return { ok: true, tabUrl: tab.url, ...first.result };
    } catch (e) {
      return { ok: false, reason: 'scripting 失败: ' + ((e && e.message) || String(e)), tabUrl: tab.url };
    }
  }

  async function checkLogin() {
    const out = $('out-login');
    out.textContent = '检查中…';
    const hosts = [OZ, OZAPI, SELLER];
    const report = {};

    // 全域探测：若 cookie API 本身就有问题，这里能看出来
    const allCookies = await cookiesGetAll({});
    report.__sanity_check = Array.isArray(allCookies)
      ? {
          total_cookies_extension_can_see: allCookies.length,
          sample_domains: Array.from(new Set(allCookies.slice(0, 200).map((c) => c.domain))).slice(0, 20),
        }
      : { err: allCookies._err };

    // 按域名反查（不用 url，可绕过 scheme/path 匹配怪象）
    const byDomainHqozon = await cookiesGetAll({ domain: 'sczfai.com' });
    const byDomainOzonRu = await cookiesGetAll({ domain: 'ozon.ru' });
    report.__by_domain = {
      'sczfai.com': Array.isArray(byDomainHqozon) ? byDomainHqozon.map(simplifyCookie) : { err: byDomainHqozon._err },
      'ozon.ru': Array.isArray(byDomainOzonRu) ? byDomainOzonRu.map(simplifyCookie) : { err: byDomainOzonRu._err },
    };

    for (const host of hosts) {
      out.textContent = '检查中… ' + host;
      const section = {};

      const raw = await cookiesGetAll({ url: host });
      if (Array.isArray(raw)) section.cookies = raw.map(simplifyCookie);
      else section.cookies_err = raw._err;

      // CHIPS / 分区 cookie；老 Chrome 可能不支持 partitionKey，失败也不要紧
      const part = await cookiesGetAll({ url: host, partitionKey: { topLevelSite: host } });
      if (Array.isArray(part)) section.cookies_partitioned = part.map(simplifyCookie);
      else section.cookies_partitioned_err = part._err;

      section.tab = await inspectTab(host);
      report[host] = section;
    }

    const ozCookies = report[OZ].cookies || [];
    const hasTokenCookie = ozCookies.some((c) => c.name === 'token');
    const ozTab = report[OZ].tab || {};
    const tabLocal = ozTab.localStorage || {};
    const localKeys = Object.keys(tabLocal);
    const suspectLocal = localKeys.filter((k) => /token|auth|jwt|user/i.test(k));
    const tabCookie = typeof ozTab.cookie === 'string' ? ozTab.cookie : null;

    let verdict;
    if (hasTokenCookie) {
      verdict = '✅ sczfai.com 的 token cookie 已找到（扩展可正常鉴权）';
    } else if (suspectLocal.length) {
      verdict =
        '⚠️ 扩展读不到 token cookie，但目标标签页 localStorage 有疑似鉴权字段：' +
        suspectLocal.join(', ') +
        '\n   → 站点很可能把 token 存在 localStorage 而非 cookie，chrome.cookies.get 取不到。';
    } else if (tabCookie && tabCookie.length > 0) {
      verdict =
        '⚠️ 扩展 chrome.cookies 读不到 cookie，但目标标签页 document.cookie 非空：\n   ' +
        tabCookie +
        '\n   → 疑似 Chrome 分区（CHIPS）或 host 权限问题。';
    } else if (ozTab.ok === false) {
      verdict =
        '⚠️ sczfai.com 无 token cookie。标签页状态：' +
        ozTab.reason +
        '\n   → 请点 "打开 sczfai.com" 登录后再点 "检查登录"。';
    } else {
      verdict = '⚠️ sczfai.com 无 token cookie，标签页 cookie 与 localStorage 都为空。';
    }

    out.textContent = verdict + '\n\n' + JSON.stringify(report, null, 2);
  }

  async function scanAPIs() {
    const tbody = $('out-api');
    const progress = $('api-progress');
    tbody.innerHTML = '';
    const rows = ENDPOINTS.map(([p, host, desc]) => {
      const tr = document.createElement('tr');
      tr.innerHTML = `<td>${host}${p}</td><td class="status s-pending">…</td><td>${desc}</td><td class="err"></td>`;
      tbody.appendChild(tr);
      return tr;
    });

    let done = 0;
    progress.textContent = `0 / ${ENDPOINTS.length}`;
    await Promise.all(
      ENDPOINTS.map(async ([p, host, _desc, method], i) => {
        const res = await probe(host + p, method || 'POST');
        const status = res.status;
        const cell = rows[i].querySelector('.status');
        cell.textContent = status;
        cell.className = `status ${classForStatus(status)}`;
        const errCell = rows[i].querySelector('.err');
        if (res.error) errCell.textContent = res.error;
        done += 1;
        progress.textContent = `${done} / ${ENDPOINTS.length}`;
      })
    );
    progress.textContent = `完成 ${done} / ${ENDPOINTS.length}`;
  }

  function scanEnv() {
    const out = $('out-env');
    const mv = chrome.runtime.getManifest ? chrome.runtime.getManifest() : {};
    const info = {
      manifest_version: mv.manifest_version,
      extension_version: mv.version,
      host_permissions_hqozon: (mv.host_permissions || []).filter((p) => p.includes('hqozon')),
      host_permissions_ozon_ru: (mv.host_permissions || []).filter((p) => p.includes('ozon.ru')),
      ua: navigator.userAgent,
      xlsx_loaded: typeof XLSX !== 'undefined' ? `v${XLSX.version || '?'}` : '❌ 未加载',
      jquery_loaded: typeof jQuery !== 'undefined' ? `v${jQuery.fn.jquery}` : '❌ 未加载',
      eval5_loaded: typeof eval5 !== 'undefined' ? '✅' : '❌',
      layui_loaded: typeof layui !== 'undefined' ? '✅' : '❌',
    };
    out.textContent = JSON.stringify(info, null, 2);
  }

  function collectCopy() {
    return [
      '# 登录',
      $('out-login').textContent,
      '',
      '# 接口扫描',
      Array.from($('out-api').querySelectorAll('tr'))
        .map((tr) => Array.from(tr.children).map((td) => td.textContent).join('\t'))
        .join('\n'),
      '',
      '# 环境',
      $('out-env').textContent,
    ].join('\n');
  }

  document.addEventListener('DOMContentLoaded', () => {
    $('btn-login').addEventListener('click', checkLogin);
    $('btn-api').addEventListener('click', scanAPIs);
    $('btn-env').addEventListener('click', scanEnv);
    $('btn-open-oz').addEventListener('click', () => {
      chrome.tabs.create({ url: OZ });
    });
    $('btn-copy').addEventListener('click', async () => {
      await navigator.clipboard.writeText(collectCopy());
      $('btn-copy').textContent = '已复制';
      setTimeout(() => ($('btn-copy').textContent = '复制结果'), 1500);
    });
    scanEnv();
  });
})();
