async function firstVisibleTextFromLocators(page, locators, timeoutMs) {
  const selectors = (locators || []).filter(Boolean);
  if (selectors.length === 0) {
    throw new Error('No priceLocators configured for this marketplace yet');
  }

  const deadline = Date.now() + (Number(timeoutMs) || 20000);
  let lastErr = null;

  for (const sel of selectors) {
    const remaining = Math.max(250, deadline - Date.now());
    try {
      const locator = page.locator(sel).first();
      await locator.waitFor({ state: 'visible', timeout: remaining });
      const txt = await locator.innerText();
      if (txt && String(txt).trim()) return String(txt).trim();
    } catch (err) {
      lastErr = err;
    }
  }

  const msg = lastErr && typeof lastErr === 'object' && 'message' in lastErr ? String(lastErr.message) : String(lastErr);
  throw new Error(`Price not found by locators. Last error: ${msg}`.slice(0, 500));
}

module.exports = { firstVisibleTextFromLocators };

