const $ = (id) => document.getElementById(id);
let currentJob = null;

async function loadStatus(){
  const r = await fetch('/api/status');
  const j = await r.json();
  $('status').textContent = `${j.chamber} ${j.version} · bundled registered inputs ready`;
}

$('validate').onclick = async () => {
  $('validation').textContent = 'Validating…';
  const r = await fetch('/api/validate', {method:'POST'});
  const j = await r.json();
  $('validation').textContent = JSON.stringify(j, null, 2);
};

$('run').onclick = async () => {
  const fd = new FormData();
  fd.append('signature_permutations', $('sigPerm').value);
  fd.append('target_permutations', $('targetPerm').value);
  fd.append('bootstrap', $('bootstrap').value);
  if ($('radial').files[0]) fd.append('radial_file', $('radial').files[0]);
  if ($('signatures').files[0]) fd.append('signature_file', $('signatures').files[0]);
  if ($('config').files[0]) fd.append('config_file', $('config').files[0]);
  $('run').disabled = true;
  $('message').textContent = 'QUEUING';
  const r = await fetch('/api/jobs', {method:'POST', body:fd});
  const j = await r.json();
  if (!r.ok){ $('message').textContent = JSON.stringify(j); $('run').disabled=false; return; }
  currentJob = j.id;
  poll();
};

async function poll(){
  const r = await fetch(`/api/jobs/${currentJob}`);
  const j = await r.json();
  $('bar').style.width = `${Math.round((j.progress || 0)*100)}%`;
  $('message').textContent = `${j.state} · ${j.message}`;
  if (j.state === 'COMPLETE'){
    $('run').disabled = false;
    $('resultPanel').classList.remove('hidden');
    $('verdict').textContent = `${j.result.protocol_status} · ${j.result.verdict}`;
    const c = j.result.comparison;
    $('comparison').innerHTML = `<pre>M2 galaxy-balanced RMSE: ${c.baseline_galaxy_balanced_rmse.toFixed(8)}\nM_IP galaxy-balanced RMSE: ${c.structural_galaxy_balanced_rmse.toFixed(8)}\nDelta (M2 − M_IP): ${c.delta_galaxy_balanced_rmse.toFixed(8)}\nRelative improvement: ${(100*c.relative_rmse_improvement).toFixed(4)}%\nSignature-null p: ${c.signature_null_p_value.toFixed(6)}\nTarget-null p: ${c.target_null_p_value.toFixed(6)}</pre>`;
    $('download').href = `/api/jobs/${currentJob}/download`;
  } else if (j.state === 'FAILED'){
    $('run').disabled = false;
  } else {
    setTimeout(poll, 900);
  }
}
loadStatus();
