
// ========= PDF.js setup =========
var fileName = document.getElementById("filename").value;
const url = "assets/" + fileName;
var isCompleted = false;
let pdfDoc = null,
  pageNum = 1,
  pageIsRendering = false,
  pageNumIsPending = null,
  scale = 3.0,
  canvas = document.getElementById("pdf-render"),
  ctx = canvas.getContext("2d");

pdfjsLib.GlobalWorkerOptions.workerSrc = "assets/pdfjs/pdf.worker.min.js";

// Render the page
function renderPage(num) {
  pageIsRendering = true;

  pdfDoc.getPage(num).then(page => {
    const viewport = page.getViewport({ scale });
    canvas.height = viewport.height;
    canvas.width = viewport.width;

    const renderCtx = {
      canvasContext: ctx,
      viewport
    };

    page.render(renderCtx).promise.then(() => {
      pageIsRendering = false;

      // Hide loader on first successful render
      const loader = document.getElementById("pdf-loader");
      if (loader) {
        loader.style.display = "none";
      }
      const container = document.getElementById("pdf-container");
      if (container) {
        container.style.display = "block";
      }

      if (pageNumIsPending !== null) {
        renderPage(pageNumIsPending);
        pageNumIsPending = null;
      }
    });

    document.getElementById("page-num").textContent = num;
  });

  // Save SCORM state after page change
  saveState();

  isCompleted = num === pdfDoc.numPages;

  // Update navigation button visibility
  const controls = document.getElementById("controls");
  if (controls) {
    const buttons = controls.querySelectorAll("button");
    const prevButton = buttons[0];
    const nextButton = buttons[buttons.length - 1];

    if (prevButton) {
      // Hide Previous on the first page
      prevButton.style.display = num === 1 ? "none" : "";
    }

    if (nextButton) {
      // Hide Next on the last page
      nextButton.style.display = num === pdfDoc.numPages ? "none" : "";
    }
  }

}

function queueRenderPage(num) {
  if (pageIsRendering) {
    pageNumIsPending = num;
  } else {
    renderPage(num);
  }
}

function showPage(num) {
  if (num < 1) num = 1;
  if (num > pdfDoc.numPages) num = pdfDoc.numPages;
  pageNum = num;
  queueRenderPage(pageNum);
}

function prevPage() {
  if (pageNum <= 1) return;
  showPage(pageNum - 1);
}

function nextPage() {
  if (pageNum >= pdfDoc.numPages) return;
  showPage(pageNum + 1);
}
// ========= SCORM Overrides =========
loadState = function () {

  pdfjsLib.getDocument(url).promise.then(pdfDoc_ => {
    pdfDoc = pdfDoc_;
    document.getElementById("page-count").textContent = pdfDoc.numPages;

    // Resume state (SCORM)
    let savedPage = parseInt(getValue("cmi.location")) || 1;

    if (savedPage >= pdfDoc.numPages) {
      showPage(pdfDoc.numPages);
      isCompleted = true;
    } else if (savedPage > 1) {
      let resume = confirm(
        `You previously stopped on page ${savedPage}. Do you want to resume from there?`
      );
      if (resume) {
        showPage(savedPage);
      } else {
        showPage(1);
      }
    } else {
      showPage(1);
    }
  });
};

saveState = function () {
  let courseState = {
    currentPage: pageNum,
    completedPages: []
  };
  for (let i = 1; i <= pageNum; i++) courseState.completedPages.push(i);

  setValue('cmi.suspend_data', JSON.stringify(courseState));
  setValue('cmi.location', pageNum);
  setValue("cmi.completion_status", isCompleted ? "completed" : "incomplete");
  setValue("cmi.lesson_status", isCompleted ? "completed" : "incomplete");
  setValue('cmi.progress_measure', getProgress()); // keep progress updated
  //calculateAndSetTime();
  commit();
};

getProgress = function () {
  return (pageNum / pdfDoc.numPages).toFixed(2); // SCORM expects decimal
};

