// Split from public/app.js v1.7.7. Loaded by public/index.html.
function resultsView() {
  const attempts = isStaffUser() ? state.data.attempts : state.data.attempts;
  const stats = resultStats(attempts);
  const section = state.resultSection || 'quiz';
  if (isStaffUser()) {
    const manualCount = (state.data.manualResults || []).length;
    const pendingSms = (state.data.resultSmsLogs || []).filter((item) => item.status !== 'sent').length;
    return html`
      <section class="panel">
        <div class="panel-header"><div><h1>Results</h1><p class="muted">Quiz results, progress reports, manual results and result SMS exports.</p></div></div>
        <div class="result-hub-stats">
          <div class="mini-stat"><span>Average Score</span><strong>${stats.average}%</strong></div>
          <div class="mini-stat success"><span>Passed</span><strong>${stats.passed}</strong></div>
          <div class="mini-stat danger"><span>Pending Review</span><strong>${stats.pending}</strong></div>
          <div class="mini-stat"><span>Manual Records</span><strong>${manualCount}</strong></div>
        </div>
        <div class="report-hub-grid">
          ${resultHubCard('quiz', 'Quiz Results', 'Exam-wise result, answer review and export', section)}
          ${resultHubCard('progress', 'Progress Report', 'Student progress, payment, due and print/PDF', section)}
          ${resultHubCard('sms', 'Result SMS', `Template and SMS export${pendingSms ? ` · ${pendingSms} pending` : ''}`, section)}
          ${resultHubCard('omr', 'OMR', 'OMR MCQ placeholder and upload workflow', section)}
          ${resultHubCard('manual', 'Manual Results', 'Excel/CSV result upload for offline exams', section)}
        </div>
        <div class="section-tabs result-tabs">
          <button class="section-tab ${section === 'quiz' ? 'active' : ''}" data-action="set-result-section" data-section="quiz">Quiz</button>
          <button class="section-tab ${section === 'progress' ? 'active' : ''}" data-action="set-result-section" data-section="progress">Progress</button>
          <button class="section-tab ${section === 'sms' ? 'active' : ''}" data-action="set-result-section" data-section="sms">SMS</button>
          <button class="section-tab ${section === 'omr' ? 'active' : ''}" data-action="set-result-section" data-section="omr">OMR</button>
          <button class="section-tab ${section === 'manual' ? 'active' : ''}" data-action="set-result-section" data-section="manual">Manual</button>
        </div>
      </section>
      ${section === 'progress' ? progressReportView() : section === 'sms' ? resultSmsView(true) : section === 'omr' ? omrView() : section === 'manual' ? manualResultsView() : html`
        <section class="panel"><div class="panel-header"><div><h2>Quiz Results</h2><p class="muted">Use See Result for student-wise answers, or export quiz result files.</p></div></div>${quizResultsTable()}</section>
      `}
    `;
  }
  return html`
    <section class="panel">
      <div class="panel-header">
        <div>
          <h1>${isStaffUser() ? 'All Results' : 'My Results'}</h1>
          <p class="muted">${isStaffUser() ? 'Quiz performance summary and submitted exam records.' : 'Your submitted exams, scores, pass/fail status, and answer review.'}</p>
        </div>
      </div>
      <div class="stats-grid">
        <div class="stat"><span class="muted">Average Score</span><strong>${stats.average}%</strong></div>
        <div class="stat"><span class="muted">Passed</span><strong>${stats.passed}</strong></div>
        <div class="stat"><span class="muted">Pending Review</span><strong>${stats.pending}</strong></div>
      </div>
      <div class="section-tabs">
        <button class="section-tab ${state.studentResultSection !== 'progress' ? 'active' : ''}" data-action="set-student-result-section" data-section="submissions">My Submissions</button>
        <button class="section-tab ${state.studentResultSection === 'progress' ? 'active' : ''}" data-action="set-student-result-section" data-section="progress">Progress Report</button>
      </div>
    </section>
    ${isStaffUser() ? html`
      <section class="panel">
        <div class="panel-header"><h2>Quiz Results</h2></div>
        ${quizResultsTable()}
      </section>
    ` : html`
      <section class="panel">
        ${state.studentResultSection === 'progress'
          ? html`<div class="panel-header"><h2>Progress Report</h2></div>${studentProgressReportView()}`
          : html`<div class="panel-header"><h2>My Submissions</h2></div>${resultsTable([...attempts].reverse(), false)}`}
      </section>
    `}
  `;
}

function resultHubCard(sectionKey, title, body, activeSection) {
  return html`
    <button class="report-hub-card ${activeSection === sectionKey ? 'active' : ''}" data-action="set-result-section" data-section="${sectionKey}">
      <strong>${escapeHtml(title)}</strong>
      <span>${escapeHtml(body)}</span>
    </button>
  `;
}

function studentProgressReportView() {
  const report = state.data.progressReport;
  if (!report) return '<p class="muted">No progress data available yet.</p>';
  return progressReportCard({
    student: state.user,
    attempts: report.attempts || [],
    manual: report.manualResults || [],
    finance: state.data.finance || {},
    summary: {
      average: report.summary?.average || 0,
      best: report.summary?.best || 0,
    },
  });
}

function progressReportView() {
  const search = String(state.progressSearch || '').trim().toLowerCase();
  const allStudents = state.data.students || [];
  const students = search
    ? allStudents.filter((student) => [student.name, student.rollNumber, student.studentMobile, student.mobile]
        .some((value) => String(value || '').toLowerCase().includes(search)))
    : allStudents;
  const selectedId = state.progressStudentId || students[0]?.id || '';
  const report = selectedId ? buildProgressReport(selectedId) : null;
  return html`
    <section class="panel">
      <div class="panel-header"><div><h2>Progress Report</h2><p class="muted">Search any student progress, payment, due and discount summary.</p></div></div>
      <div class="grid-2">
        <label class="field"><span>Search by roll / mobile / name</span><input data-progress-search value="${escapeHtml(state.progressSearch || '')}" placeholder="Type name, roll or mobile"></label>
        <label class="field"><span>Student</span><select data-progress-student><option value="">Select student</option>${students.map((student) => `<option value="${student.id}" ${student.id === selectedId ? 'selected' : ''}>${escapeHtml(student.name)} (${escapeHtml(student.rollNumber || student.studentMobile || '-')})</option>`).join('')}</select></label>
      </div>
      ${report ? progressReportCard(report) : '<p class="muted">Select a student to view progress.</p>'}
    </section>
  `;
}

function buildProgressReport(studentId) {
  const student = (state.data.students || []).find((item) => item.id === studentId);
  if (!student) return null;
  const attempts = (state.data.attempts || []).filter((attempt) => attempt.studentId === studentId);
  const manual = (state.data.manualResults || []).filter((result) => result.studentId === studentId || result.roll === student.rollNumber || result.mobile === student.studentMobile);
  const marks = [...attempts.map((attempt) => Number(attempt.earned ?? attempt.correct ?? 0)), ...manual.map((item) => Number(item.mark || 0))];
  return { student, attempts, manual, finance: student.finance || {}, summary: { total: marks.length, best: marks.length ? Math.max(...marks) : 0, average: marks.length ? Math.round(marks.reduce((sum, mark) => sum + mark, 0) / marks.length) : 0 } };
}

function progressReportCard(report) {
  return html`
    <div class="finance-summary">
      <div class="finance-card"><span>Average Mark</span><strong>${escapeHtml(String(report.summary.average || 0))}</strong></div>
      <div class="finance-card"><span>Best Mark</span><strong>${escapeHtml(String(report.summary.best || 0))}</strong></div>
      ${financeCard('Paid', report.finance.totalPaid)}
      ${financeCard('Due', report.finance.totalDue, 'danger')}
      ${financeCard('Discount', report.finance.totalDiscount)}
    </div>
    <div class="actions">
      <button class="btn secondary small" data-action="print-progress-report" data-id="${report.student.id}">Print</button>
      <a class="btn secondary small" href="/api/students/${encodeURIComponent(report.student.id)}/progress.pdf" target="_blank">PDF</a>
    </div>
    <div class="table-wrap"><table><thead><tr><th>Exam</th><th>Subject</th><th>Mark</th><th>Negative Mark</th><th>Position</th><th>Highest</th><th>Exam Date</th></tr></thead><tbody>
      ${report.attempts.map((attempt) => `<tr><td>${escapeHtml(attempt.quizTitle)}</td><td>-</td><td>${escapeHtml(String(attempt.earned ?? attempt.correct ?? 0))}</td><td>${escapeHtml(String(attempt.negativeMark ?? 0))}</td><td>-</td><td>${escapeHtml(String(attempt.total ?? '-'))}</td><td>${formatDate(attempt.submittedAt || attempt.createdAt)}</td></tr>`).join('')}
      ${report.manual.map((item) => `<tr><td>${escapeHtml(item.examName)}</td><td>${escapeHtml(item.subject || '-')}</td><td>${escapeHtml(String(item.mark || 0))}</td><td>${escapeHtml(String(item.negativeMark ?? '-'))}</td><td>${escapeHtml(item.position || '-')}</td><td>${escapeHtml(String(item.highest || '-'))}</td><td>${formatDate(item.examDate || item.createdAt)}</td></tr>`).join('')}
      ${!report.attempts.length && !report.manual.length ? '<tr><td colspan="7">No result records yet.</td></tr>' : ''}
    </tbody></table></div>
  `;
}

function manualResultsView() {
  const results = state.data.manualResults || [];
  const courses = state.data.courses || [];
  const batches = state.data.batches || [];
  return html`
    <section class="panel">
      <div class="panel-header"><div><h2>Manual Result Upload</h2><p class="muted">Upload OMR/manual marks by CSV. These records will be available for Result SMS and progress reports.</p></div></div>
      <form class="form-grid" data-action="upload-manual-results">
        <div class="grid-3">
          <label class="field"><span>Exam Name *</span><input name="examName" placeholder="Class Test: GK-07" required></label>
          <label class="field"><span>Course</span><select name="courseId"><option value="">No course filter</option>${courses.map((course) => `<option value="${course.id}">${escapeHtml(course.name)}</option>`).join('')}</select></label>
          <label class="field"><span>Batch</span><select name="batchId"><option value="">No batch filter</option>${batches.map((batch) => `<option value="${batch.id}">${escapeHtml(batch.name)}</option>`).join('')}</select></label>
        </div>
        <label class="field"><span>Subject</span><input name="subject" placeholder="GK"></label>
        <label class="field"><span>CSV Rows</span><textarea name="csv" rows="6" placeholder="01700000000,Student Name,ROLL-01,Batch Name,College Name,GK,35,2,1,35"></textarea></label>
        <p class="muted">Column order: mobile, name, roll, batch, college, subject, mark, negative mark, position, highest.</p>
        <button class="btn" type="submit">Upload Manual Results</button>
      </form>
    </section>
    <section class="panel">
      <div class="panel-header"><h2>Manual Results</h2></div>
      <div class="table-wrap"><table><thead><tr><th>Exam</th><th>Name</th><th>Roll</th><th>Subject</th><th>Mark</th><th>Position</th></tr></thead><tbody>${results.map((item) => `<tr><td>${escapeHtml(item.examName)}</td><td>${escapeHtml(item.name)}</td><td>${escapeHtml(item.roll)}</td><td>${escapeHtml(item.subject)}</td><td>${escapeHtml(String(item.mark))}</td><td>${escapeHtml(item.position || '-')}</td></tr>`).join('') || '<tr><td colspan="6">No manual results yet.</td></tr>'}</tbody></table></div>
    </section>
  `;
}

function resultSmsView() {
  const quizzes = state.data.quizzes || [];
  const courses = state.data.courses || [];
  const batches = state.data.batches || [];
  const filters = currentReportFilters('result-sms');
  const previewRows = resultSmsPreviewRows(filters).slice(0, 8);
  const template = state.resultSmsTemplate || state.institute?.smsSettings?.templates?.resultSms || 'Result of {exam}; {subject}; Name: {name}; Roll: {roll}; Mark: {mark}; Neg: {negativeMark}; Position: {position}; Highest: {highest}.';
  return html`
    <section class="panel">
      <div class="panel-header"><div><h1>Result SMS</h1><p class="muted">Customize SMS format and export result SMS for manual sending.</p></div></div>
      <form class="form-grid" data-export-form="result-sms">
        <div class="grid-3">
          <label class="field"><span>Quiz / Exam</span><select name="quizId"><option value="">All results</option>${quizzes.map((quiz) => `<option value="${quiz.id}" ${filters.quizId === quiz.id ? 'selected' : ''}>${escapeHtml(quiz.title)}</option>`).join('')}</select></label>
          <label class="field"><span>Exam Name</span><input name="examName" placeholder="Manual exam name" value="${escapeHtml(filters.examName || '')}"></label>
          <label class="field"><span>Course</span><select name="courseId"><option value="">All courses</option>${courses.map((course) => `<option value="${course.id}" ${filters.courseId === course.id ? 'selected' : ''}>${escapeHtml(course.name)}</option>`).join('')}</select></label>
        </div>
        <label class="field"><span>Batch</span><select name="batchId"><option value="">All batches</option>${batches.map((batch) => `<option value="${batch.id}" ${filters.batchId === batch.id ? 'selected' : ''}>${escapeHtml(batch.name)}</option>`).join('')}</select></label>
        <label class="field"><span>SMS Template</span><textarea name="template" rows="4">${escapeHtml(template)}</textarea></label>
        <p class="muted">Available fields: {exam}, {subject}, {name}, {roll}, {mobile}, {batch}, {college}, {mark}, {negativeMark}, {position}, {highest}</p>
        <button class="btn" type="button" data-action="download-report" data-report="result-sms" data-format="csv">Export Result SMS CSV</button>
        <button class="btn secondary" type="button" data-action="send-result-sms">Send Result SMS</button>
      </form>
    </section>
    <section class="panel">
      <div class="panel-header"><div><h2>Result Sheet Preview</h2><p class="muted">Preview mobile, roll, batch, mark, negative mark and position before export.</p></div></div>
      <div class="table-toolbar"><div><strong>${previewRows.length}</strong><span class="muted">preview rows</span>${reportFilterSummary(filters, { quizId: 'Quiz', examName: 'Exam', courseId: 'Course', batchId: 'Batch' })}</div></div>
      <div class="table-wrap"><table class="smart-table"><thead><tr><th>Mobile</th><th>Name</th><th>Roll</th><th>Batch</th><th>Mark</th><th>(-) Mark</th><th>Position</th><th>Subject</th></tr></thead><tbody>
        ${previewRows.map((row) => `<tr><td>${escapeHtml(row.mobile)}</td><td>${escapeHtml(row.name)}</td><td>${escapeHtml(row.roll)}</td><td>${escapeHtml(row.batch)}</td><td>${escapeHtml(String(row.mark))}</td><td>${escapeHtml(String(row.negativeMark || ''))}</td><td>${escapeHtml(String(row.position || '-'))}</td><td>${escapeHtml(row.subject || '-')}</td></tr>`).join('') || '<tr><td colspan="8">No result rows match this filter.</td></tr>'}
      </tbody></table></div>
    </section>
  `;
}

function resultSmsPreviewRows(filters = {}) {
  const quizRows = (state.data.attempts || []).map((attempt) => {
    const student = (state.data.students || []).find((item) => item.id === attempt.studentId) || {};
    const quiz = (state.data.quizzes || []).find((item) => item.id === attempt.quizId) || {};
    return {
      quizId: attempt.quizId,
      exam: attempt.quizTitle || quiz.title || '',
      courseIds: student.courseIds || quiz.assignedCourseIds || [],
      batchIds: (student.batchEnrollments || []).map((item) => item.batchId),
      mobile: student.studentMobile || attempt.mobile || '',
      name: attempt.studentName || student.name || '',
      roll: student.rollNumber || attempt.roll || '',
      batch: studentBatchNames(student),
      subject: primaryQuizCategory(quiz),
      mark: attempt.earned ?? attempt.correct ?? 0,
      negativeMark: attempt.negativeMark ?? attempt.negative ?? '',
      position: '-',
    };
  });
  const manualRows = (state.data.manualResults || []).map((item) => ({
    quizId: '',
    exam: item.examName || '',
    courseIds: [item.courseId].filter(Boolean),
    batchIds: [item.batchId].filter(Boolean),
    mobile: item.mobile || '',
    name: item.name || '',
    roll: item.roll || '',
    batch: item.batch || batchName(item.batchId),
    subject: item.subject || '',
    mark: item.mark || 0,
    negativeMark: item.negativeMark || '',
    position: item.position || '-',
  }));
  return [...quizRows, ...manualRows].filter((row) => {
    if (filters.quizId && row.quizId !== filters.quizId) return false;
    if (filters.examName && !String(row.exam || '').toLowerCase().includes(String(filters.examName).toLowerCase())) return false;
    if (filters.courseId && !(row.courseIds || []).includes(filters.courseId)) return false;
    if (filters.batchId && !(row.batchIds || []).includes(filters.batchId)) return false;
    return true;
  });
}

function omrView() {
  return html`
    <section class="panel">
      <div class="panel-header">
        <div>
          <h1>OMR</h1>
          <p class="muted">OMR module placeholder.</p>
        </div>
      </div>
    </section>
  `;
}

function recordedClassesView() {
  const items = state.data.recordedClasses || [];
  const courses = state.data.courses || [];
  const batches = state.data.batches || [];
  return html`
    <section class="panel">
      <div class="panel-header"><div><h1>Recorded Classes</h1><p class="muted">Publish video classes by course or batch with student watermark protection.</p></div></div>
      <form class="form-grid" data-action="add-recorded-class">
        <div class="grid-3">
          <label class="field"><span>Title *</span><input name="title" required></label>
          <label class="field"><span>Subject</span><input name="subject"></label>
          <label class="field"><span>Status</span><select name="status"><option value="published">Published</option><option value="draft">Draft</option></select></label>
        </div>
        <label class="field"><span>Video URL *</span><input name="videoUrl" placeholder="YouTube embed/private/unlisted link" required></label>
        <div class="grid-3">
          <label class="field"><span>Visibility</span><select name="visibility"><option value="assigned">Selected course/batch only</option><option value="all">All students</option></select></label>
          <label class="field"><span>Course</span><select name="courseIds"><option value="">Select course</option>${courses.map((course) => `<option value="${course.id}">${escapeHtml(course.name)}</option>`).join('')}</select></label>
          <label class="field"><span>Batch</span><select name="batchIds"><option value="">No batch</option>${batches.map((batch) => `<option value="${batch.id}">${escapeHtml(batch.name)}</option>`).join('')}</select></label>
        </div>
        <label class="field"><span>Note</span><input name="note"></label>
        <button class="btn" type="submit">Add Recorded Class</button>
      </form>
    </section>
    <section class="panel"><div class="table-wrap"><table><thead><tr><th>Title</th><th>Subject</th><th>Courses</th><th>Batches</th><th>Status</th></tr></thead><tbody>${items.map((item) => `<tr><td>${escapeHtml(item.title)}</td><td>${escapeHtml(item.subject || '-')}</td><td>${escapeHtml(courseNames(item.courseIds)) || '-'}</td><td>${escapeHtml((item.batchIds || []).map((id) => (state.data.batches || []).find((batch) => batch.id === id)?.name).filter(Boolean).join(', ')) || '-'}</td><td><span class="badge">${escapeHtml(item.status)}</span></td></tr>`).join('') || '<tr><td colspan="5">No recorded classes yet.</td></tr>'}</tbody></table></div></section>
  `;
}
