import { Page } from '@playwright/test'

/**
 * Waits for the page to be fully loaded, including all DOM content and images.
 *
 * This function first waits for the 'domcontentloaded' event, ensuring that the
 * HTML document has been completely loaded and parsed. It then evaluates the
 * page's DOM and waits for all images on the page to load, resolving when all
 * images have either loaded successfully or encountered an error.
 */
export async function waitForPageLoaded(page: Page) {
  // use domcontentloaded to wait for the page to be fully loaded
  await page.waitForLoadState('domcontentloaded')

  // evaluate the page's DOM and wait for all images to be loaded
  await page.evaluate(() => {
    return Promise.all(
      Array.from(document.images).map((img) => {
        if (img.complete) {
          return
        }
        return new Promise((resolve) => {
          img.onload = img.onerror = resolve
        })
      }),
    )
  })
}
