/* Minimal SCORM 1.2 API wrapper */
var API = null;

function findAPI(win) {
  var attempts = 0;
  while (win.API == null && win.parent != null && win.parent != win) {
    attempts++;
    if (attempts > 50) return null;
    win = win.parent;
  }
  return win.API;
}

function getAPI() {
  if (API != null) return API;
  API = findAPI(window);
  if (API == null && window.opener != null) {
    API = findAPI(window.opener);
  }
  return API;
}

var scormInitialized = false;

function scormInit() {
  var api = getAPI();
  if (api == null) return false;
  var result = api.LMSInitialize('');
  scormInitialized = (result == 'true' || result == true);
  if (scormInitialized) {
    api.LMSSetValue('cmi.core.lesson_status', 'incomplete');
    api.LMSCommit('');
  }
  return scormInitialized;
}

function scormSetProgress(slideIndex, totalSlides) {
  var api = getAPI();
  if (api == null || !scormInitialized) return;
  var score = Math.round((slideIndex / totalSlides) * 100);
  api.LMSSetValue('cmi.core.score.raw', String(score));
  if (slideIndex >= totalSlides) {
    api.LMSSetValue('cmi.core.lesson_status', 'completed');
  }
  api.LMSCommit('');
}

function scormFinish() {
  var api = getAPI();
  if (api == null || !scormInitialized) return;
  api.LMSFinish('');
}

window.addEventListener('beforeunload', scormFinish);
