Numbas.addExtension('iframe-resize', ['jme'], function (extension) {
  // Poll for element height changes
  function onElementHeightChange(elm, callback) {
    var lastHeight = elm.clientHeight;

    (function run() {
      var newHeight = elm.clientHeight;

      if (lastHeight !== newHeight) {
        lastHeight = newHeight;
        callback();
      }

      if (elm.onElementHeightChangeTimer) {
        clearTimeout(elm.onElementHeightChangeTimer);
      }
      elm.onElementHeightChangeTimer = setTimeout(run, 200);
    })();
  }
  
   // Derive the parent page's origin (recipient window's origin)
  var parentOrigin = (function () {
    try {
      return new URL(document.referrer).origin || '*';
    } catch (e) {
      return '*'; // fallback if referrer is empty or malformed
    }
  })();

  var allowlist = new Set([
    'https://lti.chirun.org.uk',
    'https://numbas.mathcentre.ac.uk'
  ]);
  if (!allowlist.has(parentOrigin)) {
    return;
  }


  onElementHeightChange(document.body, function () {
    var documentHeight = Math.max(
      document.body.scrollHeight,
      document.documentElement.scrollHeight,
      document.body.offsetHeight,
      document.documentElement.offsetHeight,
      document.body.clientHeight,
      document.documentElement.clientHeight
    );

    var pass_data = {
      height: documentHeight
      // latestScore: Numbas.exam.score / Numbas.exam.mark
    };

    console.log('sending new height: ' + documentHeight);
    parent.postMessage(JSON.stringify(pass_data), allowlist.has(parentOrigin) ? parentOrigin : '*');
  });
});