// Minimal SCORM 1.2 API wrapper (Apache-2.0 / pipwerks-inspired)
var SCORM = (function () {
  var api = null;

  function findAPI(win) {
    var depth = 0;
    while (win && win.API == null && depth < 500) {
      if (win.parent && win.parent !== win) {
        win = win.parent;
        depth++;
      } else {
        break;
      }
    }
    if (win && win.API) return win.API;
    if (win && win.opener) return findAPI(win.opener);
    return null;
  }

  function init() {
    api = findAPI(window);
    if (!api) {
      console.warn("[SCORM] LMS API not found — running standalone");
      return false;
    }
    var r = api.LMSInitialize("");
    return r === "true";
  }

  function get(key) {
    if (!api) return "";
    return api.LMSGetValue(key);
  }

  function set(key, value) {
    if (!api) return false;
    var r = api.LMSSetValue(key, String(value));
    return r === "true";
  }

  function commit() {
    if (!api) return false;
    return api.LMSCommit("") === "true";
  }

  function finish() {
    if (!api) return false;
    var r = api.LMSFinish("") === "true";
    api = null;
    return r;
  }

  function isReviewMode() {
    return get("cmi.core.lesson_mode") === "review";
  }

  return { init: init, get: get, set: set, commit: commit, finish: finish, isReviewMode: isReviewMode };
})();
