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');

outputElement.value = '';

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

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

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

  const match = text && 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');
    }
  }
}

var Module = {
  canvas: canvasElement,
  print: (...args) => {
    console.log(...args);
    outputElement.value += `${args.join(' ')}\n`;
    outputElement.scrollTop = outputElement.scrollHeight;
  },
  printErr: (...args) => {
    console.error(...args);
    outputElement.value += `[err] ${args.join(' ')}\n`;
    outputElement.scrollTop = outputElement.scrollHeight;
  },
  setStatus,
  totalDependencies: 0,
  monitorRunDependencies(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 Module.requestFullscreen === 'function') {
    Module.requestFullscreen(false, false);
  }
});

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