// Split from public/app.js v1.7.7. Loaded by public/index.html.
function activeView() {
  if (state.takingQuiz) return examView();
  if (!state.user) return loginView();
  if (isStaffUser()) {
    const views = {
      overview: adminOverview,
      managers: managersView,
      sessions: sessionsView,
      courses: coursesView,
      students: studentsView,
      messages: messagesView,
      teachers: teachersView,
      employees: employeesView,
      payments: paymentsView,
      resultSms: resultSmsView,
      recordedClasses: recordedClassesView,
      institute: instituteView,
      quizzes: quizzesView,
      results: resultsView,
      quizSubmissions: quizSubmissionHistoryView,
      resultReview: resultReviewView,
      analytics: analyticsView,
      ...(state.user.role === 'admin' ? { activity: activityView } : {}),
      profile: profileView,
    };
    const viewAllowed = state.view === 'payments'
      ? ['payments', 'studentPayments', 'teacherPayments', 'employeePayments', 'referencePayments', 'otherPayments'].some((permission) => canAccessMenu(permission))
      : state.view === 'overview' || canAccessMenu(state.view);
    if (!views[state.view] || !viewAllowed) state.view = 'overview';
    return shell((views[state.view] || adminOverview)());
  }
  const views = {
    overview: studentOverview,
    exams: studentExams,
    results: resultsView,
    lecture: lectureView,
    payments: myPaymentView,
    resultReview: resultReviewView,
    profile: profileView,
  };
  return shell((views[state.view] || studentOverview)());
}

function render() {
  const institute = state.institute || state.data?.institute || {};
  if (institute.name) document.title = institute.name;
  const favicon = document.querySelector('link[rel="icon"]');
  if (favicon && institute.faviconDataUrl) favicon.setAttribute('href', institute.faviconDataUrl);
  app.innerHTML = activeView();
  decorateTables();
  decorateForms();
  decorateActions();
  decorateEmptyStates();
  startTimerIfNeeded();
}

function decorateTables() {
  document.querySelectorAll('.table-wrap table').forEach((table) => {
    const headers = [...table.querySelectorAll('thead th')].map((header) => header.textContent.trim());
    table.querySelectorAll('tbody tr').forEach((row) => {
      [...row.children].forEach((cell, index) => {
        if (cell.tagName !== 'TD') return;
        const label = headers[index] || '';
        if (label) cell.dataset.label = label;
      });
    });
  });
}

function decorateForms() {
  document.querySelectorAll('.field').forEach((field) => {
    const control = field.querySelector('input, select, textarea');
    const label = field.querySelector('span');
    if (!control) return;
    field.classList.toggle('required-field', Boolean(control.required && label && !label.textContent.includes('*')));
    field.classList.toggle('readonly-field', Boolean(control.readOnly || control.disabled));
    if (control.required) control.setAttribute('aria-required', 'true');
    if (control.placeholder && !control.title) control.title = control.placeholder;
  });
}

function decorateActions() {
  document.querySelectorAll('a[href*="/api/export"], a[href*="/api/backup"], button[data-action="download-report"]').forEach((action) => {
    action.classList.add('export-action');
    const text = action.textContent.trim();
    if (/pdf/i.test(text)) action.dataset.format = 'PDF';
    else if (/excel|xlsx/i.test(text)) action.dataset.format = 'Excel';
    else if (/csv/i.test(text)) action.dataset.format = 'CSV';
    else if (/json|backup|session/i.test(text)) action.dataset.format = 'Backup';
  });
}

function decorateEmptyStates() {
  document.querySelectorAll('td[colspan]').forEach((cell) => {
    const text = cell.textContent.trim();
    if (!/^No\s/i.test(text) || cell.querySelector('.empty-state')) return;
    cell.innerHTML = `<div class="empty-state">${escapeHtml(text)}</div>`;
  });
}

function collectQuizForm(form) {
  const formData = new FormData(form);
  const questions = [];
  const questionCards = [...form.querySelectorAll('[data-question-index]')];
  for (const card of questionCards) {
    const index = Number(card.dataset.questionIndex);
    const type = formData.get(`q_${index}_type`) || 'mcq';
    const optionCount = type === 'true_false' ? 2 : type === 'mcq' ? 4 : 0;
    const options = Array.from({ length: optionCount }, (_, optionIndex) => formData.get(`q_${index}_option_${optionIndex}`) || '');
    const correctIndex = Number(formData.get(`q_${index}_correct`) ?? 0);
    questions.push({
      type,
      text: formData.get(`q_${index}_text`),
      options,
      correctIndex,
      correctText: type === 'short' ? formData.get(`q_${index}_correctText`) : '',
      points: formData.get(`q_${index}_points`),
      explanation: formData.get(`q_${index}_explanation`),
    });
  }
  return {
    title: formData.get('title'),
    category: formData.get('category'),
    description: formData.get('description'),
    durationMinutes: formData.get('durationMinutes'),
    passMark: formData.get('passMark'),
    negativeMarking: formData.get('negativeMarking'),
    retakeLimit: formData.get('retakeLimit'),
    scheduleStart: formData.get('scheduleStart'),
    scheduleEnd: formData.get('scheduleEnd'),
    randomizeQuestions: formData.get('randomizeQuestions') === 'on',
    randomizeAnswers: formData.get('randomizeAnswers') === 'on',
    certificateEnabled: formData.get('certificateEnabled') === 'on',
    resultVisibility: formData.get('resultVisibility'),
    status: formData.get('status'),
    assignedCourseIds: formData.getAll('assignedCourseIds'),
    questions,
  };
}

function snapshotQuiz(quiz) {
  const normalizedQuestions = (quiz.questions || []).map((question) => ({
    type: question.type || 'mcq',
    text: question.text || '',
    options: (question.options || []).map((option) => String(option ?? '')),
    correctIndex: Number(question.correctIndex || 0),
    correctText: question.correctText || '',
    points: String(question.points || 1),
    explanation: question.explanation || question.tag || '',
  }));
  return JSON.stringify({
    title: quiz.title || '',
    category: quiz.category || '',
    description: quiz.description || '',
    durationMinutes: String(quiz.durationMinutes || 30),
    passMark: String(quiz.passMark || 50),
    negativeMarking: String(quiz.negativeMarking || 0),
    retakeLimit: String(quiz.retakeLimit || 0),
    scheduleStart: quiz.scheduleStart || '',
    scheduleEnd: quiz.scheduleEnd || '',
    randomizeQuestions: Boolean(quiz.randomizeQuestions),
    randomizeAnswers: Boolean(quiz.randomizeAnswers),
    certificateEnabled: quiz.certificateEnabled !== false,
    resultVisibility: quiz.resultVisibility || 'immediate',
    status: quiz.status || 'published',
    assignedCourseIds: quiz.assignedCourseIds || [],
    questions: normalizedQuestions,
  });
}

function syncEditingQuizFromForm() {
  const form = document.querySelector('[data-action="save-quiz"]');
  if (!form) return;
  const formData = new FormData(form);
  state.editingQuiz = {
    id: formData.get('id') || state.editingQuiz?.id || '',
    ...collectQuizForm(form),
  };
}
