const browser = require('../browser');

module.exports = async ({ text }) => {
  if (!text) {
    throw new Error('Texto é obrigatório');
  }

  await browser.start();
  const p = await browser.ensurePage();

  const clicked = await p.evaluate((targetText) => {
    const elements = Array.from(document.querySelectorAll(
      'a, button, input[type="submit"], input[type="button"], [role="button"], [onclick]'
    ));

    const el = elements.find(e => {
      const txt = (e.innerText || e.textContent || e.value || e.getAttribute('aria-label') || '').trim().toLowerCase();
      return txt.includes(targetText.toLowerCase());
    });

    if (el) {
      el.scrollIntoView({ behavior: 'smooth', block: 'center' });
      el.click();

      if (el.tagName === 'A' && el.href) {
        return { clicked: true, href: el.href };
      }

      return { clicked: true, href: null };
    }

    return { clicked: false, href: null };
  }, text);

  if (!clicked.clicked) {
    throw new Error(`Elemento não encontrado pelo texto: "${text}"`);
  }

  if (clicked.href) {
    try {
      await p.waitForNavigation({ timeout: 5000, waitUntil: 'domcontentloaded' });
    } catch (e) {
    }
  } else {
    await p.waitForTimeout(1000);
  }

  return {
    success: true,
    action: "smart_click",
    text,
    navigatedTo: clicked.href || null
  };
};
