import { test, expect } from '@playwright/test';

test('Verify all visible buttons on Links Talent website work correctly (excluding LET’S TALK)', async ({ page }) => {
  await page.goto('https://linkstalent.com', { waitUntil: 'domcontentloaded' });

  const buttonSelectors = 'button, a[role="button"], a[class*="btn"], a[href]:not([href="#"])';
  const buttons = await page.$$(buttonSelectors);

  console.log(`Found ${buttons.length} buttons/links`);

  let visibleIndex = 0;

  for (let i = 0; i < buttons.length; i++) {
    try {
      const btn = buttons[i];

      if (!(await btn.isVisible())) {
        console.log(`Skipping invisible button #${i + 1}`);
        continue;
      }

      const label = (await btn.innerText()).trim() || (await btn.getAttribute('href'));

      // Skip the "LET’S TALK" button
      if (label.toUpperCase().includes("LET'S TALK")) {
        console.log(`Skipping "LET’S TALK" button`);
        continue;
      }

      console.log(`Clicking visible button #${++visibleIndex}: "${label}"`);

      // Handle modal overlay: close modal if present
      const modalOverlay = await page.$('div.modal__overlay');
      if (modalOverlay) {
        console.log(`Modal overlay detected, closing it`);
        await page.click('div.modal__overlay'); // or close using the close button if it's available
        await page.waitForTimeout(500); // wait for modal to close
      }

      // Click the button and handle navigation
      await btn.evaluate(el => {
        if (el.tagName === 'A') el.setAttribute('target', '_self');
      });

      const [response] = await Promise.all([
        page.waitForNavigation({ waitUntil: 'load', timeout: 40000 }).catch(() => null), // Increase timeout to 40s
        btn.click()
      ]);

      if (response) {
        const status = response.status();
        console.log(` → Navigated with status: ${status}`);
        expect(status).toBeLessThan(400);
      } else {
        console.warn(` → Button "${label}" did not navigate. Possibly opens modal or uses JavaScript.`);
      }

    } catch (error) {
      console.error(` Error clicking button #${i + 1}:`, error.message);
    }
  }

  console.log(` Finished testing ${visibleIndex} visible buttons.`);
});
