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

test('Verify all visible buttons on Links Talent website are working', async ({ page }) => {
  // Navigate to the homepage
  await page.goto('https://linkstalent.com', { waitUntil: 'domcontentloaded' });

  // Select all clickable buttons and links that look like buttons
  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];

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

      // Get the button's text or href to identify it
      const label = (await btn.innerText()).trim() || (await btn.getAttribute('href'));

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

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

      // Handle potential modal or in-page actions
      const modalOverlay = await page.$('div.modal__overlay');
      if (modalOverlay) {
        console.log(`Modal overlay detected, closing it`);
        await page.click('div.modal__overlay'); // Close modal if it's visible
        await page.waitForTimeout(500); // Wait for modal to close
      }

      // Ensure the button opens in the same tab
      await btn.evaluate(el => {
        if (el.tagName === 'A') el.setAttribute('target', '_self');
      });

      // Click and handle navigation
      const [response] = await Promise.all([
        page.waitForNavigation({ waitUntil: 'load', timeout: 30000 }).catch(() => null), // Wait for navigation with a timeout
        btn.click()
      ]);

      if (response) {
        const status = response.status();
        console.log(` → Navigated with status: ${status}`);
        expect(status).toBeLessThan(400); // Fail if the status is 404 or higher
      } 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.`);
});
