var API = null;
var sessionStartTime = null;
var lmsTotalTime = "PT0H0M0S"; // cached LMS total time (read-only in 2004)
var timeUpdateInterval = null; // Stores the periodic time update interval ID

function findAPI(win) {
  while (win.API_1484_11 != null && win.API_1484_11 !== undefined) {
    return win.API_1484_11;
  }
  if (win.parent != null && win.parent != win) return findAPI(win.parent);
  if (win.opener != null) return findAPI(win.opener);
  return null;
}

function initSCORM() {
  API = findAPI(window);
  if (API) {
    API.Initialize("");
    sessionStartTime = new Date();

    // Fetch and cache LMS total_time (read-only) for reference/analytics
    var tt = getValue("cmi.total_time") || "PT0H0M0S";
    if (isValidIsoDuration(tt)) {
      lmsTotalTime = tt;
    }

    loadState();

    // Start periodic time tracking (updates every 15 seconds)
    startPeriodicTimeTracking();
  }
}

function setValue(key, value) {
  if (API) API.SetValue(key, value);
}

function getValue(key) {
  if (API) return API.GetValue(key);
  return "";
}

function getLastError() {
  if (API) return API.GetLastError();
  return "0";
}

function commit() {
  if (API) API.Commit("");
}

// Returns cached LMS total time (unchanged by content; read-only in 2004)
function getTotalTime() {
  return lmsTotalTime;
}

// Common time calculation (SCORM 2004)
function calculateAndSetTime() {
  if (!API || !sessionStartTime) return;
  try {
    var now = new Date();
    var sessionTimeMs = now - sessionStartTime;
    var sessionTime = msToSCORMTime(sessionTimeMs);
    // Set session time for this attempt
    setValue("cmi.session_time", sessionTime);
    safeMirrorTotalTime();

    // Call saveState() only if user is on last page (completed)
    if (window.isCompleted && typeof saveState === 'function') {
      saveState();
    }
  } catch (error) {
    // Silently handle errors (LMS may reject updates after completion)
    console.log('Time update error (continuing):', error.message);
  }
}

// Start periodic time tracking (updates every 15 seconds)
function startPeriodicTimeTracking() {
  // Prevent duplicate timers
  if (timeUpdateInterval !== null) {
    console.log('Periodic time tracking already started');
    return;
  }

  // Only start if SCORM is initialized and session start time is set
  if (!API || !sessionStartTime) {
    console.log('Cannot start periodic time tracking - SCORM not initialized or session start time not set');
    return;
  }

  // Start interval: update time every 15 seconds (15000ms)
  timeUpdateInterval = setInterval(function () {
    if (API && sessionStartTime) {
      // Update session time
      calculateAndSetTime();
      // Commit to LMS
      commit();
    }
  }, 15000); // 15 seconds

  console.log('Periodic time tracking started (15-second interval)');
}

// Stop periodic time tracking
function stopPeriodicTimeTracking() {
  if (timeUpdateInterval !== null) {
    clearInterval(timeUpdateInterval);
    timeUpdateInterval = null;

    // Final time update before stopping
    if (API && sessionStartTime) {
      calculateAndSetTime();
      commit();
    }

    console.log('Periodic time tracking stopped');
  }
}

// Try to mirror LMS total_time back (will be ignored by LMS if read-only)
function safeMirrorTotalTime() {
  if (!API) return;
  var tt = getValue("cmi.total_time") || lmsTotalTime;
  if (!isValidIsoDuration(tt)) return;
  setValue("cmi.total_time", tt);
  // If LMS rejects (read-only), it will set an error; we ignore and keep cached value
  var err = getLastError();
  if (err !== "0") {
    // Revert to cached value just to be safe
    lmsTotalTime = tt;
  }
}

function completeSCORM() {
  if (API) {
    // Stop periodic time tracking
    stopPeriodicTimeTracking();

    calculateAndSetTime();
    saveState();

    if (window.isCompleted) {
      setValue("cmi.completion_status", "completed");
      setValue("cmi.exit", "normal");
    } else {
      setValue("cmi.completion_status", "incomplete");
      setValue("cmi.exit", "suspend");
    }

    commit();
    API.Terminate("");
  }
}

// Convert ms to SCORM 2004 duration (PT#H#M#S)
function msToSCORMTime(ms) {
  var totalSeconds = Math.floor(ms / 1000);
  var hours = Math.floor(totalSeconds / 3600);
  var minutes = Math.floor((totalSeconds % 3600) / 60);
  var seconds = totalSeconds % 60;
  return "PT" + hours + "H" + minutes + "M" + seconds + "S";
}

// Validate ISO-8601-like duration used by SCORM 2004 (simple check)
function isValidIsoDuration(s) {
  return /^PT\d+H\d+M\d+S$/.test(s);
}

// Placeholders (overridden by page.js)
function loadState() { }
function saveState() { }
function getProgress() { return "0"; }

window.onload = initSCORM;
window.addEventListener('beforeunload', completeSCORM);
