<%- include('../partials/header', { title: module.title, learnerName: learnerName }) %>

<div class="container">
  <div class="progress-section">
    <div class="progress-info">
      <span class="progress-text">Module <%= moduleNum %> of <%= totalModules %></span>
      <span class="progress-percentage"><%= progress %>% Complete</span>
    </div>
    <div class="progress-bar">
      <div class="progress-fill" style="width: <%= progress %>%"></div>
    </div>
  </div>

  <div class="module-layout">
    <aside class="module-sidebar">
      <div class="modules-nav">
        <h4>Training Modules</h4>
        <ul class="modules-list">
          <% for (let i = 1; i <= totalModules; i++) { %>
            <li class="module-nav-item <%= i === moduleNum ? 'active' : '' %> <%= completedModules.includes(i) ? 'completed' : '' %>">
              <% if (completedModules.includes(i)) { %>
                <a href="/modules/<%= i %>"><span class="checkmark">&#10003;</span> Module <%= i %></a>
              <% } else if (i === moduleNum) { %>
                <span><strong>Module <%= i %> (Current)</strong></span>
              <% } else if (i === Math.min(...completedModules.concat([0])) + 1 || completedModules.length === 0 && i === 1 || i <= completedModules.length + 1) { %>
                <a href="/modules/<%= i %>">Module <%= i %></a>
              <% } else { %>
                <span class="locked">Module <%= i %> 🔒</span>
              <% } %>
            </li>
          <% } %>
        </ul>
      </div>
    </aside>

    <main class="module-content">
      <article class="lesson">
        <header class="lesson-header">
          <h1><%= module.title %></h1>
        </header>

        <div class="lesson-body">
          <%- module.lesson %>
        </div>

        <section class="knowledge-check">
          <h3>Knowledge Check — <%= module.questions.length %> Questions</h3>
          <p class="check-note">Answer the following questions to test your understanding. You must score 70% or higher to complete this module.</p>

          <form id="quizForm" class="quiz-form">
            <div class="questions-container">
              <% module.questions.forEach((question, index) => { %>
                <div class="question-item">
                  <p class="question-text"><%= index + 1 %>. <%= question.text %></p>
                  <div class="question-options">
                    <label class="radio-label">
                      <input type="radio" name="answers[<%= index %>]" value="true" required>
                      <span>True</span>
                    </label>
                    <label class="radio-label">
                      <input type="radio" name="answers[<%= index %>]" value="false" required>
                      <span>False</span>
                    </label>
                  </div>
                </div>
              <% }); %>
            </div>

            <div class="quiz-actions">
              <button type="submit" class="btn btn-primary">Submit Quiz</button>
            </div>
          </form>

          <% if (isCompleted) { %>
            <div class="completion-badge">
              <p>&#10003; Module Complete</p>
            </div>
          <% } %>
        </section>
      </article>
    </main>
  </div>
</div>

<div id="quizResultModal" class="modal" style="display: none;">
  <div class="modal-content">
    <div id="modalBody"></div>
    <div class="modal-actions">
      <button id="closeModal" class="btn btn-primary">Close</button>
    </div>
  </div>
</div>

<script>
document.getElementById('quizForm').addEventListener('submit', async (e) => {
  e.preventDefault();

  const formData = new FormData(e.target);
  const answers = {};
  for (let [key, value] of formData.entries()) {
    const match = key.match(/answers\[(\d+)\]/);
    if (match) {
      answers[match[1]] = value;
    }
  }

  try {
    const response = await fetch('/modules/<%= moduleNum %>/submit', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ answers })
    });

    const result = await response.json();
    const modal = document.getElementById('quizResultModal');
    const modalBody = document.getElementById('modalBody');

    if (result.passed) {
      modalBody.innerHTML = `
        <div class="result-passed">
          <h3>&#127881; Great Work!</h3>
          <p>You passed with a score of <strong>${result.score}%</strong></p>
          <p>${result.correct} out of ${result.total} correct</p>
        </div>
      `;
      modal.style.display = 'flex';
      setTimeout(() => {
        window.location.href = '/modules/<%= moduleNum %>/complete';
      }, 2000);
    } else {
      modalBody.innerHTML = `
        <div class="result-failed">
          <h3>Not Quite There Yet</h3>
          <p>You scored <strong>${result.score}%</strong></p>
          <p>${result.correct} out of ${result.total} correct</p>
          <p>You need 70% to pass. Please review the lesson above and try again.</p>
        </div>
      `;
      modal.style.display = 'flex';
    }
  } catch (error) {
    alert('Error submitting quiz: ' + error.message);
  }
});

document.getElementById('closeModal').addEventListener('click', () => {
  document.getElementById('quizResultModal').style.display = 'none';
});
</script>

<%- include('../partials/footer') %>
