/* rg-shim.js — client-side replacement for the rg-study PHP session layer.
 *
 * The original tasks (gitlab.unige.ch/bavelierlab/rg-study) injected PHP
 * session values ($pxperdeg, $monitorsize, $testmode, $stage, $token) into
 * the task JS via code.php wrappers, and saved data to MySQL via save.php.
 * This shim reproduces the same globals from URL parameters plus a
 * localStorage calibration record, and replaces the server save with a
 * JSON file download. Task behavior is otherwise untouched.
 *
 * URL parameters (same names as the original study):
 *   ?token=...&stage=pre-test|post-test&testmode=true&task=<calibration target>
 * Calibration values arrive either as URL params (?monitorsize=&pxperdeg=,
 * sent by the calibration form via GET) or from localStorage
 * ("rg-calibration", written by calibration/calibrationcode.js).
 */
window.RG = (function () {
  var params = new URLSearchParams(window.location.search);
  var cal = {};
  try {
    cal = JSON.parse(localStorage.getItem("rg-calibration") || "{}");
  } catch (e) {
    cal = {};
  }
  function num(value, fallback) {
    var n = parseFloat(value);
    return isNaN(n) ? fallback : n;
  }
  var pxperdeg = num(params.get("pxperdeg") !== null ? params.get("pxperdeg") : cal.pxperdeg, -1);
  var monitorsize = num(params.get("monitorsize") !== null ? params.get("monitorsize") : cal.monitorsize, -1);
  var stage = params.get("stage") || "";
  var token = params.get("token") || "";
  var testmode = params.get("testmode") === "true" ? 1 : 0;
  return {
    token: token,
    stage: stage,
    testmode: testmode,
    pxperdeg: pxperdeg,
    monitorsize: monitorsize,
    // Mimics the PHP $_SESSION subset the task code consumed.
    session: {
      token: token,
      stage: stage,
      monitorsize: monitorsize,
      pxperdeg: pxperdeg
    },
    // Replaces save.php / savePractice.php: download the data as JSON.
    saveJSON: function (filename, data) {
      var blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
      var a = document.createElement("a");
      a.href = URL.createObjectURL(blob);
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      setTimeout(function () {
        URL.revokeObjectURL(a.href);
        a.remove();
      }, 1000);
    },
    // Replaces addcalibration.php: persist calibration client-side.
    saveCalibration: function (data) {
      try {
        localStorage.setItem("rg-calibration", JSON.stringify(data));
      } catch (e) {
        // sandboxed context without storage: the calibration form still
        // carries the values to the task page via GET parameters.
      }
    },
    // Replaces the server-built redirect of calibration/index.php.
    calibrationTarget: function (defaultTask) {
      var task = params.get("task") || defaultTask;
      var target = "../" + task;
      if (stage) {
        target += "?stage=" + encodeURIComponent(stage);
      }
      return target;
    },
    // Query string carrying calibration values across task pages
    // (the PHP session used to do this implicitly).
    calQuery: function () {
      return "&monitorsize=" + encodeURIComponent(monitorsize) +
        "&pxperdeg=" + encodeURIComponent(pxperdeg);
    }
  };
})();
