const statusElement = document.getElementById('status');
const progressElement = document.getElementById('progress');
const canvasElement = document.getElementById('canvas');
const outputElement = document.getElementById('output');
const fullscreenButton = document.getElementById('fullscreenButton');
const resizeCheckbox = document.getElementById('resize');
const pointerLockCheckbox = document.getElementById('pointerLock');

if (outputElement) {
  outputElement.value = '';
}

canvasElement.addEventListener(
  'webglcontextlost',
  (event) => {
    event.preventDefault();
    setStatus('WebGL context lost. Reload the page to restart the game.');
  },
  false
);

function setStatus(text) {
  if (!setStatus.last) {
    setStatus.last = { time: Date.now(), text: '' };
  }

  if (text === setStatus.last.text) {
    return;
  }

  const match = text?.match(/([^(]+)\((\d+(?:\.\d+)?)\/(\d+)\)/);
  const now = Date.now();

  if (match && now - setStatus.last.time < 30) {
    return;
  }

  setStatus.last.time = now;
  setStatus.last.text = text;

  if (match) {
    statusElement.textContent = match[1].trim();
    progressElement.value = Number.parseInt(match[2], 10) * 100;
    progressElement.max = Number.parseInt(match[3], 10) * 100;
    progressElement.hidden = false;
  } else {
    statusElement.textContent = text || '';
    progressElement.hidden = !text;
    if (!text) {
      progressElement.removeAttribute('value');
    }
  }
}

globalThis.Module = globalThis.Module || {};
globalThis.Module.canvas = canvasElement;
globalThis.Module.print = (...args) => {
  console.log(...args);
  if (!outputElement) {
    return;
  }
  outputElement.value += `${args.join(' ')}\n`;
  outputElement.scrollTop = outputElement.scrollHeight;
};
globalThis.Module.printErr = (...args) => {
  console.error(...args);
  if (!outputElement) {
    return;
  }
  outputElement.value += `[err] ${args.join(' ')}\n`;
  outputElement.scrollTop = outputElement.scrollHeight;
};
globalThis.Module.setStatus = setStatus;
globalThis.Module.totalDependencies = 0;
globalThis.Module.monitorRunDependencies = function (left) {
  this.totalDependencies = Math.max(this.totalDependencies, left);
  setStatus(
    left
      ? `Preparing... (${this.totalDependencies - left}/${this.totalDependencies})`
      : 'Running...'
  );
  if (!left) {
    setTimeout(() => setStatus(''), 250);
  }
};

fullscreenButton.addEventListener('click', () => {
  if (typeof globalThis.Module.requestFullscreen === 'function') {
    globalThis.Module.requestFullscreen(
      pointerLockCheckbox.checked,
      resizeCheckbox.checked
    );
  }
});

setStatus('Downloading...');

globalThis.onerror = () => {
  setStatus('Exception thrown, see JavaScript console');
};
