(function () {
  var statusEl = document.getElementById('status');
  var videoEl = document.getElementById('lessonVideo');
  var initialized = false;
  var completed = false;

  function setStatus(msg, cls) {
    if (!statusEl) return;
    statusEl.textContent = 'Status SCORM: ' + msg;
    statusEl.className = 'status' + (cls ? ' ' + cls : '');
  }

  function getAPI(win) {
    var maxTries = 500;
    var tries = 0;
    while (win && tries < maxTries) {
      if (win.API) return win.API;
      tries += 1;
      win = win.parent;
    }
    return null;
  }

  var api = getAPI(window);

  function lmsInitialize() {
    if (!api) {
      setStatus('nu am gasit API LMS (test local sau LMS fara SCORM).', 'warn');
      return false;
    }

    var ok = api.LMSInitialize('');
    if (ok === 'true') {
      initialized = true;
      setStatus('initializat.', 'ok');

      var currentStatus = api.LMSGetValue('cmi.core.lesson_status');
      if (!currentStatus || currentStatus === 'not attempted') {
        api.LMSSetValue('cmi.core.lesson_status', 'incomplete');
      }
      api.LMSCommit('');
      return true;
    }

    setStatus('initializare esuata (code ' + api.LMSGetLastError() + ').', 'warn');
    return false;
  }

  function markCompleted() {
    if (!api || !initialized || completed) return;

    api.LMSSetValue('cmi.core.lesson_status', 'completed');
    api.LMSSetValue('cmi.core.score.raw', '100');
    api.LMSCommit('');
    completed = true;
    setStatus('finalizat si salvat.', 'ok');
  }

  function lmsFinish() {
    if (!api || !initialized) return;
    api.LMSCommit('');
    api.LMSFinish('');
    initialized = false;
  }

  if (videoEl) {
    videoEl.addEventListener('ended', markCompleted);
  }

  window.addEventListener('load', lmsInitialize);
  window.addEventListener('beforeunload', lmsFinish);
})();
