/* Minimal SCORM 1.2 / 2004 API wrapper.
   Finds the LMS API in the window/opener chain and exposes a single
   normalized interface used by app.js. Degrades gracefully when no
   LMS is present (e.g. opened as a plain file) so the course still works. */
(function (global) {
  "use strict";

  var API = null;
  var apiVersion = null; // "1.2" or "2004"
  var findAttempts = 0;
  var MAX_FIND_ATTEMPTS = 500;

  function findAPI(win) {
    findAttempts++;
    if (findAttempts > MAX_FIND_ATTEMPTS) return null;
    if (win.API) return { api: win.API, version: "1.2" };
    if (win.API_1484_11) return { api: win.API_1484_11, version: "2004" };
    if (win.parent && win.parent !== win) return findAPI(win.parent);
    return null;
  }

  function locateAPI() {
    var found = null;
    try {
      found = findAPI(global);
    } catch (e) { found = null; }
    if (!found && global.opener) {
      try { found = findAPI(global.opener); } catch (e) { found = null; }
    }
    return found;
  }

  var ScormAPI = {
    connected: false,

    init: function () {
      var found = locateAPI();
      if (!found) {
        this.connected = false;
        return false;
      }
      API = found.api;
      apiVersion = found.version;
      var result;
      try {
        result = apiVersion === "1.2" ? API.LMSInitialize("") : API.Initialize("");
      } catch (e) {
        this.connected = false;
        return false;
      }
      this.connected = (result === "true" || result === true);
      return this.connected;
    },

    getValue: function (key) {
      if (!this.connected) return "";
      try {
        return apiVersion === "1.2" ? API.LMSGetValue(key) : API.GetValue(key);
      } catch (e) {
        return "";
      }
    },

    setValue: function (key, value) {
      if (!this.connected) return false;
      try {
        var r = apiVersion === "1.2" ? API.LMSSetValue(key, value) : API.SetValue(key, value);
        return r === "true" || r === true;
      } catch (e) {
        return false;
      }
    },

    commit: function () {
      if (!this.connected) return false;
      try {
        apiVersion === "1.2" ? API.LMSCommit("") : API.Commit("");
        return true;
      } catch (e) {
        return false;
      }
    },

    setStatus: function (status) {
      // status: "completed" | "incomplete" | "passed" | "failed"
      if (!this.connected) return;
      if (apiVersion === "1.2") {
        this.setValue("cmi.core.lesson_status", status);
      } else {
        if (status === "completed" || status === "incomplete") {
          this.setValue("cmi.completion_status", status);
        } else {
          this.setValue("cmi.success_status", status);
          this.setValue("cmi.completion_status", "completed");
        }
      }
      this.commit();
    },

    setScore: function (raw, min, max) {
      if (!this.connected) return;
      if (apiVersion === "1.2") {
        this.setValue("cmi.core.score.raw", raw);
        this.setValue("cmi.core.score.min", min);
        this.setValue("cmi.core.score.max", max);
      } else {
        this.setValue("cmi.score.raw", raw);
        this.setValue("cmi.score.min", min);
        this.setValue("cmi.score.max", max);
        this.setValue("cmi.score.scaled", max > 0 ? (raw / max) : 0);
      }
      this.commit();
    },

    setLocation: function (loc) {
      if (!this.connected) return;
      this.setValue(apiVersion === "1.2" ? "cmi.core.lesson_location" : "cmi.location", loc);
      this.commit();
    },

    getLocation: function () {
      return this.getValue(apiVersion === "1.2" ? "cmi.core.lesson_location" : "cmi.location");
    },

    setSuspendData: function (data) {
      if (!this.connected) return;
      this.setValue("cmi.suspend_data", data);
      this.commit();
    },

    getSuspendData: function () {
      return this.getValue("cmi.suspend_data");
    },

    finish: function () {
      if (!this.connected) return;
      try {
        apiVersion === "1.2" ? API.LMSFinish("") : API.Terminate("");
      } catch (e) { /* noop */ }
    }
  };

  global.ScormAPI = ScormAPI;
})(window);
