// helper.js
// 将函数挂到 globalThis，background.js 可以直接调用
globalThis.getButtonPosition = async function getButtonPosition(tabId, selector, options = {}) {
  const {
    timeout = 15000,
    pollInterval = 500,
    world = 'ISOLATED' // or 'MAIN'
  } = options;

  const sleep = ms => new Promise(res => setTimeout(res, ms));
  const start = Date.now();

  try {
    while (Date.now() - start < timeout) {
      const results = await chrome.scripting.executeScript({
        target: { tabId },
        func: (sel) => {
          try {
            const el = document.querySelector(sel);
            if (!el) return null;
            const r = el.getBoundingClientRect();
            return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
          } catch (e) {
            // 在页面上下文捕获错误并返回 null
            return null;
          }
        },
        args: [selector],
        world
      });

      const value = results?.[0]?.result ?? null;
      if (value) {
        console.debug('[helper.getButtonPosition] found', selector, value);
        return value;
      }

      await sleep(pollInterval);
    }

    console.warn('[helper.getButtonPosition] timeout, not found:', selector);
    return null;
  } catch (err) {
    console.error('[helper.getButtonPosition] error:', err);
    return null;
  }
};
