<!DOCTYPE HTML>
<meta charset=utf-8>
<title>Largest Contentful Paint: largest image is reported.</title>

<body>
  <script src="/resources/testharness.js"></script>
  <script src="/resources/testharnessreport.js"></script>
  <script src="resources/largest-contentful-paint-helpers.js"></script>
  <!-- There is some text and some images. We care about lcp-133x106.png being reported, as it is the largest. -->
  <p>This is some text! :)</p>
  <img src='' id='lcp1' />
  <img src='' id='lcp2' />
  <img src='' id='lcp3' />
  <p>More text!</p>
  <script>
    // Add listener for load event that is fired when image is loaded.
    function image_load_promise(image_element) {
      return new Promise(resolve => {
        image_element.addEventListener('load', resolve);
      });
    }

    promise_test(async (t) => {
      assert_implements(window.LargestContentfulPaint, "LargestContentfulPaint is not implemented");

      let promise = image_load_promise(document.getElementById('lcp1'));
      document.getElementById('lcp1').src = '/images/lcp-100x50.png';
      await promise;

      const beforeLoad = performance.now();

      promise = image_load_promise(document.getElementById('lcp2'));
      document.getElementById('lcp2').src = '/images/lcp-133x106.png';
      await promise;

      promise = image_load_promise(document.getElementById('lcp3'));
      document.getElementById('lcp3').src = '/images/lcp-100x50-alt.png';
      await promise;

      const observer = new PerformanceObserver(
        t.step_func(entryList => {
          entryList.getEntries().forEach(entry => {
            // The text or other image could be reported as LCP if it is rendered before the larger image.
            if (entry.id !== 'lcp2')
              return;

            const url = window.location.origin + '/images/lcp-133x106.png';
            const size = 133 * 106;
            checkImage(entry, url, 'lcp2', size, beforeLoad);
            t.done();
          })
        })
      );
      observer.observe({ type: 'largest-contentful-paint', buffered: true });
    }, 'Largest Contentful Paint: largest image is reported.');
  </script>
</body>
