(function () {
  "use strict";

  var COMPLETE_THRESHOLD = 0.9; // mark complete once 90% of the video has been watched

  var videoEl = document.getElementById("video");
  var progressFillEl = document.getElementById("progress-fill");
  var progressLabelEl = document.getElementById("progress-label");
  var statusLineEl = document.getElementById("status-line");

  var maxWatchedSeconds = 0;
  var courseCompleted = false;
  var lastPersist = 0;

  function formatTime(sec) {
    sec = Math.floor(sec || 0);
    var m = Math.floor(sec / 60);
    var s = sec % 60;
    return m + ":" + (s < 10 ? "0" : "") + s;
  }

  function updateProgressUI() {
    var duration = videoEl.duration || 0;
    var pct = duration ? Math.min(100, Math.round((maxWatchedSeconds / duration) * 100)) : 0;
    progressFillEl.style.width = pct + "%";
    progressLabelEl.textContent = pct + "% vizionat (" + formatTime(maxWatchedSeconds) + " / " + formatTime(duration) + ")";
  }

  function markCourseComplete() {
    if (!courseCompleted) {
      courseCompleted = true;
      ScormAPI.setStatus("completed");
      statusLineEl.classList.add("completed");
    }
  }

  function persistState(force) {
    var now = Date.now();
    if (!force && now - lastPersist < 2000) return;
    lastPersist = now;
    ScormAPI.setLocation(String(Math.floor(videoEl.currentTime || 0)));
    try {
      ScormAPI.setSuspendData(JSON.stringify({
        maxWatchedSeconds: maxWatchedSeconds,
        currentTime: videoEl.currentTime || 0
      }));
    } catch (e) { /* noop */ }
  }

  function restoreState() {
    var raw = ScormAPI.getSuspendData();
    if (raw) {
      try {
        var data = JSON.parse(raw);
        if (data && typeof data.maxWatchedSeconds === "number") {
          maxWatchedSeconds = data.maxWatchedSeconds;
        }
        return data;
      } catch (e) { /* ignore malformed data */ }
    }
    return null;
  }

  function init() {
    ScormAPI.init();
    if (ScormAPI.connected) {
      var status = ScormAPI.getValue("cmi.core.lesson_status") || ScormAPI.getValue("cmi.completion_status");
      if (status === "completed" || status === "passed") {
        courseCompleted = true;
        statusLineEl.classList.add("completed");
      } else {
        ScormAPI.setStatus("incomplete");
      }
    }

    var saved = restoreState();
    var resumeTarget = (saved && typeof saved.currentTime === "number" && saved.currentTime > 1 && !courseCompleted)
      ? saved.currentTime
      : null;

    var resumeAttempts = 0;
    var MAX_RESUME_ATTEMPTS = 5;

    function tryResumeSeek() {
      if (resumeTarget === null || !videoEl.duration) return;
      if (resumeAttempts >= MAX_RESUME_ATTEMPTS) {
        resumeTarget = null; // give up rather than retry forever if the browser won't honor the seek
        return;
      }
      resumeAttempts++;
      var target = Math.min(resumeTarget, Math.max(0, videoEl.duration - 1));
      videoEl.currentTime = target;
    }

    videoEl.addEventListener("loadedmetadata", function () {
      updateProgressUI();
      tryResumeSeek();
    });
    videoEl.addEventListener("canplay", tryResumeSeek);
    videoEl.addEventListener("play", tryResumeSeek);
    videoEl.addEventListener("seeked", function () {
      if (resumeTarget !== null && Math.abs(videoEl.currentTime - resumeTarget) < 1.5) {
        resumeTarget = null;
      }
    });

    videoEl.addEventListener("timeupdate", function () {
      if (videoEl.currentTime > maxWatchedSeconds) {
        maxWatchedSeconds = videoEl.currentTime;
      }
      updateProgressUI();
      persistState(false);
      var duration = videoEl.duration || 0;
      if (duration && maxWatchedSeconds / duration >= COMPLETE_THRESHOLD) {
        markCourseComplete();
      }
    });

    videoEl.addEventListener("ended", function () {
      maxWatchedSeconds = videoEl.duration || maxWatchedSeconds;
      updateProgressUI();
      markCourseComplete();
      persistState(true);
    });

    videoEl.addEventListener("pause", function () {
      persistState(true);
    });

    window.addEventListener("beforeunload", function () {
      persistState(true);
      ScormAPI.commit();
      ScormAPI.finish();
    });
  }

  document.addEventListener("DOMContentLoaded", init);
})();
