<%- include('partials/header', { title: 'Final Certification Exam', learnerName: learnerName }) %>

<div class="container">
  <div class="exam-header">
    <h1>Final Certification Exam</h1>
    <p class="exam-subtitle">Connecticut Elderly Services PCA Certification</p>
  </div>

  <form id="examForm" class="exam-form">
    <% sections.forEach((section, sectionIdx) => { %>
      <section class="exam-section">
        <div class="section-header">
          <h2>Section <%= section.id %>: <%= section.title %></h2>
          <p class="section-questions">(<%= section.questions.length %> questions)</p>
        </div>

        <div class="section-questions">
          <% section.questions.forEach((question, qIdx) => { %>
            <div class="exam-question">
              <p class="question-number">Q<%= sectionIdx + 1 %>.<%= qIdx + 1 %> <%= question.text %></p>
              <div class="question-options">
                <label class="radio-label">
                  <input type="radio" name="answers[<%= section.id %>-<%= qIdx %>]" value="true" required>
                  <span>True</span>
                </label>
                <label class="radio-label">
                  <input type="radio" name="answers[<%= section.id %>-<%= qIdx %>]" value="false" required>
                  <span>False</span>
                </label>
              </div>
            </div>
          <% }); %>
        </div>
      </section>
    <% }); %>

    <div class="exam-actions">
      <button type="submit" class="btn btn-success btn-large">Submit Exam</button>
      <a href="/" class="btn btn-secondary">Cancel</a>
    </div>
  </form>
</div>

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

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

  const formData = new FormData(e.target);
  const answers = {};

  for (let [key, value] of formData.entries()) {
    answers[key] = value;
  }

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

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

    if (result.passed) {
      modalBody.innerHTML = `
        <div class="result-passed">
          <h3>Congratulations!</h3>
          <p>You have successfully passed the PCA Certification Exam!</p>
          <p class="score-display">Overall Score: <strong>${result.overallScore}%</strong></p>
          <div class="section-results">
            <h4>Section Results:</h4>
            <ul>
              ${Object.entries(result.sectionScores).map(([id, section]) => `
                <li class="section-result passed">
                  <span class="checkmark">&#10003;</span>
                  <span>${section.title}: ${section.score}%</span>
                </li>
              `).join('')}
            </ul>
          </div>
          <p class="success-message">Your certificate has been generated and is ready for download.</p>
        </div>
      `;
      document.getElementById('closeModal').textContent = 'View Certificate';
      document.getElementById('closeModal').onclick = () => {
        window.location.href = '/exam/result';
      };
    } else {
      const failedSections = Object.entries(result.sectionScores)
        .filter(([id, section]) => !section.passed)
        .map(([id, section]) => `<li>${section.title} (${section.score}%)</li>`)
        .join('');

      modalBody.innerHTML = `
        <div class="result-failed">
          <h3>Exam Not Passed</h3>
          <p class="score-display">Overall Score: <strong>${result.overallScore}%</strong></p>
          <p>To pass, you must score 70% or higher in ALL sections.</p>
          <h4>Sections That Need Improvement:</h4>
          <ul>${failedSections}</ul>
          <p>Review the material for these sections and try again.</p>
        </div>
      `;
      document.getElementById('closeModal').textContent = 'View Results';
      document.getElementById('closeModal').onclick = () => {
        window.location.href = '/exam/result';
      };
    }

    modal.style.display = 'flex';
  } catch (error) {
    alert('Error submitting exam: ' + error.message);
  }
});
</script>

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