/* Basit SCORM 1.2 API sarmalayıcı — LMS'in window/parent/opener zincirindeki
   API nesnesini bulur, durumu (lesson_status) ve skoru güvenle gönderir.
   LMS yoksa (ör. masaüstünde test) sessizce no-op çalışır. */
(function (w) {
  var API = null, found = false, startTs = Date.now();

  function findAPI(win) {
    var tries = 0;
    while (win && !win.API && win.parent && win.parent !== win && tries < 12) {
      tries++; win = win.parent;
    }
    return win && win.API ? win.API : null;
  }
  function getAPI() {
    if (found) return API;
    found = true;
    try { API = findAPI(w); } catch (e) { API = null; }
    if (!API && w.opener) { try { API = findAPI(w.opener); } catch (e) {} }
    return API;
  }
  function two(n) { return (n < 10 ? '0' : '') + n; }
  function sessionTime() {
    var s = Math.floor((Date.now() - startTs) / 1000);
    return two(Math.floor(s / 3600)) + ':' + two(Math.floor((s % 3600) / 60)) + ':' + two(s % 60);
  }

  var SCORM = {
    available: function () { return !!getAPI(); },
    init: function () {
      var a = getAPI(); if (!a) return false;
      try {
        a.LMSInitialize('');
        if (a.LMSGetValue('cmi.core.lesson_status') === 'not attempted') {
          a.LMSSetValue('cmi.core.lesson_status', 'incomplete');
        }
        a.LMSCommit('');
        return true;
      } catch (e) { return false; }
    },
    set: function (k, v) { var a = getAPI(); if (!a) return; try { a.LMSSetValue(k, String(v)); } catch (e) {} },
    commit: function () { var a = getAPI(); if (!a) return; try { a.LMSCommit(''); } catch (e) {} },
    complete: function (score) {
      var a = getAPI(); if (!a) return false;
      try {
        if (typeof score === 'number') {
          a.LMSSetValue('cmi.core.score.raw', String(score));
          a.LMSSetValue('cmi.core.score.min', '0');
          a.LMSSetValue('cmi.core.score.max', '100');
        }
        a.LMSSetValue('cmi.core.session_time', sessionTime());
        a.LMSSetValue('cmi.core.lesson_status', 'completed');
        a.LMSCommit('');
        return true;
      } catch (e) { return false; }
    },
    finish: function () { var a = getAPI(); if (!a) return; try { a.LMSSetValue('cmi.core.session_time', sessionTime()); a.LMSCommit(''); a.LMSFinish(''); } catch (e) {} }
  };

  w.SCORM = SCORM;
  w.addEventListener('unload', function () { SCORM.finish(); });
})(window);
