const puppeteer = require('puppeteer');
const fs = require('fs');
const path = require('path');

// Helper function for waiting
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

async function captureAuthenticationTab() {
  // Create the screenshots directory
  const screenshotsDir = path.join(__dirname, 'screenshots');
  if (!fs.existsSync(screenshotsDir)) {
    fs.mkdirSync(screenshotsDir, { recursive: true });
  }

  // Launch the browser
  const browser = await puppeteer.launch({
    headless: 'new',
    args: ['--no-sandbox', '--disable-setuid-sandbox'],
  });

  const page = await browser.newPage();
  await page.setViewport({ width: 1280, height: 800 });

  // Create a simple test HTML file
  const testHtml = `
    <!DOCTYPE html>
    <html>
    <head>
      <title>JSON:API Explorer Test</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <script>
        // Mock the Drupal settings
        window.drupalSettings = {
          jsonapi_explorer: {
            base_url: 'https://example.com/jsonapi/'
          }
        };
      </script>
    </head>
    <body>
      <div id="jsonapi-explorer-root" data-base-url="https://example.com/jsonapi/">
        <div class="loading">Loading...</div>
      </div>
      <script src="./build/static/js/main.js"></script>
    </body>
    </html>
  `;

  // Write the test HTML file
  const testHtmlPath = path.join(__dirname, 'test-auth.html');
  fs.writeFileSync(testHtmlPath, testHtml);

  try {
    console.log('Loading test page...');
    await page.goto(`file://${testHtmlPath}`, { waitUntil: 'networkidle0' });

    // Wait for the app to initialize
    await page.waitForSelector('.explorer-toolbar-button', { timeout: 10000 });
    console.log('App loaded');

    // Click on the Authentication tab
    console.log('Clicking on the Authentication tab...');
    await page.evaluate(() => {
      // Find the main tabs
      const tabs = document.querySelectorAll('.tabs__tab');
      // Click on the Authentication tab (usually the second one)
      if (tabs.length > 1) {
        tabs[1].querySelector('button').click();
      }
    });

    // Wait for the auth section to be visible
    await wait(1000);

    // No need to open details since we removed it
    await page.evaluate(() => {
      console.log('Auth section should be visible by default now');
    });

    // Wait for all content to render
    await wait(1000);

    // Take a screenshot
    console.log('Taking screenshot...');
    await page.screenshot({
      path: path.join(screenshotsDir, 'auth-tab.png'),
      fullPage: true
    });

    // Now click on the code examples tab
    console.log('Clicking on the Build Query tab and then the Code Examples tab...');
    await page.evaluate(() => {
      // First click on Build Query tab (first tab)
      const tabs = document.querySelectorAll('.tabs__tab');
      if (tabs.length > 0) {
        tabs[0].querySelector('button').click();
      }

      // Then find and click on the code examples tab (</> tab)
      setTimeout(() => {
        const codeTabs = document.querySelectorAll('.query-panel-tab');
        const codeTab = Array.from(codeTabs).find(tab => tab.textContent.includes('</>'));
        if (codeTab) {
          codeTab.click();
        }
      }, 500);
    });

    // Wait for the code tab to be visible
    await wait(1500);

    // Take a screenshot
    console.log('Taking code examples tab screenshot...');
    await page.screenshot({
      path: path.join(screenshotsDir, 'code-examples-tab.png'),
      fullPage: true
    });

    console.log('Screenshots captured successfully');
  } catch (error) {
    console.error('Error capturing screenshots:', error);
  } finally {
    // Clean up
    if (fs.existsSync(testHtmlPath)) {
      fs.unlinkSync(testHtmlPath);
    }
    await browser.close();
  }
}

captureAuthenticationTab().catch(console.error);
