---
/**
 * The Travelpayouts Emerald script that turns the site's affiliate links into tracked ones. Deferred off the critical
 * path: it loads on the first interaction, or once the page is idle after load. `trs` is the site's Travelpayouts id.
 */
import { EMERALD_ORIGIN } from './resources.ts';

interface Props {
  trs: string;
}

const { trs } = Astro.props;
const emeraldOrigin = EMERALD_ORIGIN;
---

<script is:inline define:vars={{ trs, emeraldOrigin }}>
  (function () {
    if (!/^\d+$/.test(trs)) return;
    var loaded = false;
    function loadAffiliate() {
      if (loaded) return;
      loaded = true;
      var script = document.createElement('script');
      script.async = 1;
      script.src = emeraldOrigin + '/' + btoa(trs) + '.js?t=' + trs;
      document.head.appendChild(script);
    }
    var opts = { once: true, passive: true, capture: true };
    ['pointerdown', 'keydown', 'touchstart', 'scroll'].forEach(function (evt) {
      window.addEventListener(evt, loadAffiliate, opts);
    });
    window.addEventListener('load', function () {
      if ('requestIdleCallback' in window) {
        requestIdleCallback(loadAffiliate, { timeout: 5000 });
      } else {
        setTimeout(loadAffiliate, 4000);
      }
    });
  })();
</script>
