// Split from public/app.js v1.7.7. Loaded by public/index.html.
function batchesView() {
  const batches = state.data.batches || [];
  const courses = (state.data.courses || []).filter((course) => course.status === 'active');
  return html`
    <section class="panel">
      <div class="panel-header"><div><h2>Create Batch</h2><p class="muted">Organize enrolled students by course and schedule.</p></div></div>
      <form class="form-grid" data-action="add-batch">
        <div class="grid-3">
          <label class="field"><span>Batch Name *</span><input name="name" placeholder="Morning Batch" required></label>
          <label class="field"><span>Batch Code *</span><input name="code" maxlength="4" placeholder="01" required></label>
          <label class="field"><span>Course *</span><select name="courseId" required><option value="">Select course</option>${courses.map((course) => `<option value="${course.id}">${escapeHtml(course.name)}</option>`).join('')}</select></label>
        </div>
        <div class="grid-3">
          <label class="field"><span>Capacity</span><input name="capacity" type="number" min="0" placeholder="0 = unlimited"></label>
          <label class="field"><span>Roll Start</span><input name="rollStartNumber" type="number" min="1" value="1"></label>
          <label class="field"><span>Next Roll Serial</span><input name="rollNextNumber" type="number" min="1" value="1"></label>
        </div>
        <div class="grid-3">
          <label class="field"><span>Start Date</span><input name="startDate" type="date"></label>
          <label class="field"><span>End Date</span><input name="endDate" type="date"></label>
          <label class="field"><span>Roll Limit (Max 99)</span><input name="rollLimit" type="number" min="1" max="99" value="${Number(state.data.rollSettings?.rollLimit || 99)}"></label>
        </div>
        <label class="field"><span>Schedule / Time</span><input name="schedule" placeholder="Sat-Thu, 10:00 AM"></label>
        <button class="btn" type="submit">Create Batch</button>
      </form>
    </section>
    <section class="panel">
      <div class="table-wrap">
        <table>
          <thead><tr><th>Batch</th><th>Course</th><th>Roll Preview</th><th>Schedule</th><th>Students</th><th>Status</th><th>Actions</th></tr></thead>
          <tbody>${batches.map((batch) => html`
            <tr>
              <td><strong>${escapeHtml(batch.name)}</strong><br><span class="muted">Code: ${escapeHtml(batch.code || '-')} | ${escapeHtml(batch.startDate || '-')} -> ${escapeHtml(batch.endDate || '-')}</span></td>
              <td>${escapeHtml(batch.courseName)}</td>
              <td><strong>${escapeHtml(batch.rollPreview?.rollNumber || '-')}</strong><br><span class="muted">${escapeHtml(batch.rollPreview?.registrationNumber || '')}</span></td>
              <td>${escapeHtml(batch.schedule || '-')}</td>
              <td>${batch.studentCount} / ${batch.capacity || '∞'}</td>
              <td><span class="badge ${batch.status === 'active' ? 'success' : 'danger'}">${batch.status}</span></td>
              <td><div class="actions">
                <button class="btn secondary small" data-action="manage-batch-students" data-id="${batch.id}">Students</button>
                <button class="btn secondary small" data-action="edit-batch" data-id="${batch.id}">Edit</button>
                <button class="btn secondary small" data-action="toggle-batch" data-id="${batch.id}" data-status="${batch.status === 'active' ? 'inactive' : 'active'}">${batch.status === 'active' ? 'Deactivate' : 'Activate'}</button>
                <button class="btn danger small" data-action="delete-batch" data-id="${batch.id}">Delete</button>
              </div></td>
            </tr>
          `).join('') || '<tr><td colspan="7">No batches created.</td></tr>'}</tbody>
        </table>
      </div>
    </section>
    ${state.editingBatchId ? batchEditDialog() : ''}
    ${state.deletingBatchId ? batchDeleteDialog() : ''}
    ${state.managingBatchId ? batchStudentsDialog() : ''}
  `;
}

function batchFields(batch = {}) {
  const courses = state.data.courses || [];
  return html`
    <div class="grid-2">
      <label class="field"><span>Batch Name *</span><input name="name" value="${escapeHtml(batch.name || '')}" required></label>
      <label class="field"><span>Batch Code *</span><input name="code" value="${escapeHtml(batch.code || '')}" maxlength="4" required></label>
    </div>
    <div class="grid-2">
      <label class="field"><span>Course *</span><select name="courseId" required>${courses.map((course) => `<option value="${course.id}" ${course.id === batch.courseId ? 'selected' : ''}>${escapeHtml(course.name)}</option>`).join('')}</select></label>
      <label class="field"><span>Capacity</span><input name="capacity" type="number" min="0" value="${Number(batch.capacity || 0)}"></label>
    </div>
    <div class="grid-2">
      <label class="field"><span>Start Date</span><input name="startDate" type="date" value="${escapeHtml(batch.startDate || '')}"></label>
      <label class="field"><span>End Date</span><input name="endDate" type="date" value="${escapeHtml(batch.endDate || '')}"></label>
    </div>
    <div class="grid-2">
      <label class="field"><span>Schedule / Time</span><input name="schedule" value="${escapeHtml(batch.schedule || '')}"></label>
      <label class="field"><span>Roll Limit (Max 99)</span><input name="rollLimit" type="number" min="1" max="99" value="${Number(batch.rollLimit || state.data.rollSettings?.rollLimit || 99)}"></label>
    </div>
    <div class="grid-2">
      <label class="field"><span>Roll Start</span><input name="rollStartNumber" type="number" min="1" value="${Number(batch.rollStartNumber || 1)}"></label>
      <label class="field"><span>Next Roll Serial</span><input name="rollNextNumber" type="number" min="1" value="${Number(batch.rollNextNumber || batch.rollStartNumber || 1)}"></label>
    </div>
  `;
}

function batchEditDialog() {
  const batch = (state.data.batches || []).find((item) => item.id === state.editingBatchId);
  if (!batch) return '';
  return html`<div class="modal-backdrop"><section class="modal-card">
    <div class="panel-header"><div><h2>Edit Batch</h2><p class="muted">${escapeHtml(batch.courseName)}</p></div><button class="btn secondary small" data-action="close-batch-edit">Close</button></div>
    <form class="form-grid" data-action="edit-batch" data-id="${batch.id}">${batchFields(batch)}<button class="btn" type="submit">Save Batch</button></form>
  </section></div>`;
}

function batchDeleteDialog() {
  const batch = (state.data.batches || []).find((item) => item.id === state.deletingBatchId);
  if (!batch) return '';
  return html`<div class="modal-backdrop"><section class="modal-card">
    <h2>Delete Batch?</h2><p class="muted">${escapeHtml(batch.name)} will be permanently deleted. A batch with students cannot be deleted.</p>
    <div class="actions"><button class="btn danger" data-action="confirm-delete-batch" data-id="${batch.id}">Delete</button><button class="btn secondary" data-action="close-batch-delete">Cancel</button></div>
  </section></div>`;
}

function batchStudentsDialog() {
  const batch = (state.data.batches || []).find((item) => item.id === state.managingBatchId);
  if (!batch) return '';
  const students = (state.data.students || []).filter((student) => (student.courseIds || []).includes(batch.courseId));
  return html`<div class="modal-backdrop"><section class="modal-card modal-wide">
    <div class="panel-header"><div><h2>${escapeHtml(batch.name)} Students</h2><p class="muted">Select enrolled ${escapeHtml(batch.courseName)} students for this batch.</p></div><button class="btn secondary small" data-action="close-batch-students">Close</button></div>
    <form class="form-grid" data-action="save-batch-students" data-id="${batch.id}">
      <div class="batch-student-grid">${students.map((student) => {
        const checked = (student.batchEnrollments || []).some((item) => item.batchId === batch.id);
        return `<label class="check-card"><input type="checkbox" name="studentIds" value="${student.id}" ${checked ? 'checked' : ''}><span><strong>${escapeHtml(student.name)}</strong><small>${escapeHtml(student.rollNumber)}</small></span></label>`;
      }).join('') || '<p class="muted">No students are enrolled in this course.</p>'}</div>
      <button class="btn" type="submit">Save Batch Students</button>
    </form>
  </section></div>`;
}

function studentCoursesDialog() {
  const student = (state.data.students || []).find((item) => item.id === state.editingStudentCoursesId);
  const courses = (state.data.courses || []).filter((course) => course.status === 'active');
  if (!student) return '';
  return html`
    <div class="modal-backdrop">
      <section class="modal-card">
        <div class="panel-header">
          <div>
            <h2>Student Courses</h2>
            <p class="muted">Enroll ${escapeHtml(student.name)} in one or more courses.</p>
          </div>
          <button class="btn secondary small" type="button" data-action="close-student-courses">Close</button>
        </div>
        <form class="form-grid" data-action="save-student-courses" data-id="${student.id}">
          ${courseMultiSelect({
            courses,
            selectedCourseIds: student.courseIds || [],
            inputName: 'courseIds',
            label: 'Courses',
            helpText: 'Select the student’s enrolled courses.',
          })}
          <button class="btn" type="submit">Save Enrollment</button>
        </form>
      </section>
    </div>
  `;
}

function coursesView() {
  const courses = state.data.courses || [];
  const section = state.coursesSection || 'courses';
  return html`
    <section class="panel">
      <div class="panel-header">
        <div>
          <h1>Courses</h1>
          <p class="muted">Create courses, enroll students, and control course-based quiz access.</p>
        </div>
      </div>
      <div class="section-tabs">
        <button class="section-tab ${section === 'courses' ? 'active' : ''}" data-action="set-courses-section" data-section="courses">Courses</button>
        <button class="section-tab ${section === 'batches' ? 'active' : ''}" data-action="set-courses-section" data-section="batches">Batches</button>
        <button class="section-tab ${section === 'subjects' ? 'active' : ''}" data-action="set-courses-section" data-section="subjects">Subjects</button>
        <button class="section-tab ${section === 'roll' ? 'active' : ''}" data-action="set-courses-section" data-section="roll">Roll Settings</button>
      </div>
    </section>
    ${section === 'batches' ? batchesView() : section === 'subjects' ? subjectsView() : section === 'roll' ? rollSettingsView() : html`
    <section class="panel">
      <form class="form-grid" data-action="add-course">
        <div class="grid-3">
          <label class="field"><span>Course Name</span><input name="name" placeholder="e.g. Medical Admission" required></label>
          <label class="field"><span>Course Code *</span><input name="code" maxlength="4" placeholder="01" required></label>
          <label class="field"><span>Description</span><input name="description" placeholder="Short course description"></label>
        </div>
        <div class="grid-3">
          <label class="field"><span>Default Course Fee</span><input name="defaultFee" type="number" min="0" step="0.01" placeholder="0"></label>
        </div>
        <button class="btn" type="submit">Add Course</button>
      </form>
    </section>
    <section class="panel">
      <div class="table-wrap">
        <table>
          <thead><tr><th>Course</th><th>Code</th><th>Default Fee</th><th>Students</th><th>Quizzes</th><th>Status</th><th>Actions</th></tr></thead>
          <tbody>
            ${courses.map((course) => {
              const studentCount = (state.data.students || []).filter((student) => (student.courseIds || []).includes(course.id)).length;
              const quizCount = (state.data.quizzes || []).filter((quiz) => (quiz.assignedCourseIds || []).includes(course.id)).length;
              return html`
                <tr>
                  <td><strong>${escapeHtml(course.name)}</strong><br><span class="muted">${escapeHtml(course.description || '')}</span></td>
                  <td>${escapeHtml(course.code || '-')}</td>
                  <td>${formatMoney(course.defaultFee)}</td>
                  <td>${studentCount}</td>
                  <td>${quizCount}</td>
                  <td><span class="badge ${course.status === 'active' ? 'success' : 'danger'}">${course.status}</span></td>
                  <td><div class="actions">
                    <button class="btn secondary small" data-action="open-course-edit" data-id="${course.id}">Edit</button>
                    <button class="btn secondary small" data-action="toggle-course" data-id="${course.id}" data-status="${course.status === 'active' ? 'inactive' : 'active'}">${course.status === 'active' ? 'Deactivate' : 'Activate'}</button>
                    <button class="btn danger small" data-action="delete-course" data-id="${course.id}">Delete</button>
                  </div></td>
                </tr>
              `;
            }).join('')}
          </tbody>
        </table>
      </div>
    </section>
    ${state.editingCourseId ? courseEditDialog() : ''}
    ${state.deletingCourseId ? courseDeleteDialog() : ''}
    `}
  `;
}

function subjectsView() {
  const subjects = state.data.subjects || [];
  return html`
    <section class="panel">
      <div class="panel-header"><div><h2>Subjects</h2><p class="muted">Manage subject names for teacher and lecture organization.</p></div></div>
      <form class="form-grid" data-action="add-subject">
        <div class="grid-2">
          <label class="field"><span>Subject Name *</span><input name="name" required placeholder="Physics"></label>
          <label class="field"><span>Code</span><input name="code" placeholder="PHY"></label>
        </div>
        <button class="btn" type="submit">Add Subject</button>
      </form>
    </section>
    <section class="panel"><div class="table-wrap"><table><thead><tr><th>Subject</th><th>Code</th><th>Status</th><th>Actions</th></tr></thead><tbody>${subjects.map((subject) => `<tr><td>${escapeHtml(subject.name)}</td><td>${escapeHtml(subject.code || '-')}</td><td><span class="badge ${subject.status === 'inactive' ? 'danger' : 'success'}">${escapeHtml(subject.status || 'active')}</span></td><td><div class="actions"><button class="btn secondary small" data-action="edit-subject" data-id="${subject.id}">Edit</button><button class="btn secondary small" data-action="toggle-subject" data-id="${subject.id}" data-status="${subject.status === 'inactive' ? 'active' : 'inactive'}">${subject.status === 'inactive' ? 'Activate' : 'Deactivate'}</button></div></td></tr>`).join('') || '<tr><td colspan="4">No subjects yet.</td></tr>'}</tbody></table></div></section>
    ${state.editingSubjectId ? subjectEditDialog() : ''}
  `;
}

function rollSettingsView() {
  const settings = state.data.rollSettings || {};
  const preview = settings.preview || {};
  return html`
    <section class="panel">
      <div class="panel-header"><div><h2>Roll Auto Generation</h2><p class="muted">New student roll is generated automatically when roll field is blank.</p></div></div>
      <form class="form-grid" data-action="save-roll-settings">
        <div class="grid-3">
          <label class="field"><span>Admission Year</span><input name="year" type="number" min="2000" max="2100" value="${Number(settings.year || new Date().getFullYear())}" data-roll-setting-input></label>
          <label class="field"><span>Roll First 2 Digits</span><input name="rollPrefix" maxlength="2" value="${escapeHtml(settings.rollPrefix || String(settings.year || new Date().getFullYear()).slice(-2))}" data-roll-setting-input></label>
          <label class="field"><span>Default Roll Limit</span><input name="rollLimit" type="number" min="1" max="99" value="${Number(settings.rollLimit || 99)}" data-roll-setting-input></label>
        </div>
        <input name="serialPadding" type="hidden" value="2" data-roll-setting-input>
        <div class="grid-2">
          <div class="finance-card"><span>Roll Preview</span><strong data-roll-preview="roll">${escapeHtml(preview.rollNumber || '-')}</strong></div>
          <div class="finance-card"><span>Registration Preview</span><strong data-roll-preview="registration">${escapeHtml(preview.registrationNumber || '-')}</strong></div>
        </div>
        <button class="btn" type="submit">Save Roll Settings</button>
      </form>
    </section>
  `;
}

function updateRollPreview() {
  const form = document.querySelector('[data-action="save-roll-settings"]');
  if (!form) return;
  const year = String(Math.floor(Number(form.elements.year?.value || new Date().getFullYear())) || new Date().getFullYear());
  const prefix = String(form.elements.rollPrefix?.value || year.slice(-2)).replace(/[^a-zA-Z0-9]+/g, '').toUpperCase().padStart(2, '0').slice(-2);
  const padding = 2;
  const batch = (state.data.batches || []).find((item) => item.status === 'active') || (state.data.batches || [])[0] || {};
  const course = (state.data.courses || []).find((item) => item.id === batch.courseId)
    || (state.data.courses || []).find((item) => item.status === 'active')
    || (state.data.courses || [])[0]
    || {};
  const courseCode = String(course.code || '01').replace(/[^a-zA-Z0-9]+/g, '').toUpperCase().padStart(2, '0');
  const batchCode = String(batch.code || '01').replace(/[^a-zA-Z0-9]+/g, '').toUpperCase().padStart(2, '0');
  const serial = String(batch.rollNextNumber || batch.rollStartNumber || 1).padStart(padding, '0');
  const rollTarget = document.querySelector('[data-roll-preview="roll"]');
  const registrationTarget = document.querySelector('[data-roll-preview="registration"]');
  if (rollTarget) rollTarget.textContent = `${prefix}${batchCode}${serial}`;
  if (registrationTarget) registrationTarget.textContent = `${year}${courseCode}${batchCode}${serial}`;
}

function courseEditDialog() {
  const course = (state.data.courses || []).find((item) => item.id === state.editingCourseId);
  if (!course) return '';
  return html`<div class="modal-backdrop"><section class="modal-card">
    <div class="panel-header"><div><h2>Edit Course</h2><p class="muted">Update the course without browser prompts.</p></div><button class="btn secondary small" data-action="close-course-edit">Close</button></div>
    <form class="form-grid" data-action="edit-course" data-id="${course.id}">
      <label class="field"><span>Course Name *</span><input name="name" value="${escapeHtml(course.name)}" required></label>
      <label class="field"><span>Course Code *</span><input name="code" maxlength="4" value="${escapeHtml(course.code || '')}" required></label>
      <label class="field"><span>Description</span><textarea name="description">${escapeHtml(course.description || '')}</textarea></label>
      <label class="field"><span>Default Course Fee</span><input name="defaultFee" type="number" min="0" step="0.01" value="${Number(course.defaultFee || 0)}"></label>
      <button class="btn" type="submit">Save Course</button>
    </form>
  </section></div>`;
}

function subjectEditDialog() {
  const subject = (state.data.subjects || []).find((item) => item.id === state.editingSubjectId);
  if (!subject) return '';
  return html`<div class="modal-backdrop"><section class="modal-card">
    <div class="panel-header"><div><h2>Edit Subject</h2><p class="muted">${escapeHtml(subject.name)}</p></div><button class="btn secondary small" data-action="close-subject-edit">Close</button></div>
    <form class="form-grid" data-action="edit-subject" data-id="${subject.id}">
      <label class="field"><span>Subject Name *</span><input name="name" value="${escapeHtml(subject.name)}" required></label>
      <label class="field"><span>Code</span><input name="code" value="${escapeHtml(subject.code || '')}"></label>
      <button class="btn" type="submit">Save Subject</button>
    </form>
  </section></div>`;
}

function courseDeleteDialog() {
  const course = (state.data.courses || []).find((item) => item.id === state.deletingCourseId);
  if (!course) return '';
  return html`<div class="modal-backdrop"><section class="modal-card">
    <h2>Delete Course?</h2><p class="muted">${escapeHtml(course.name)} can only be deleted when it has no students, quizzes, batches or payments. Otherwise deactivate it.</p>
    <div class="actions"><button class="btn danger" data-action="confirm-delete-course" data-id="${course.id}">Delete</button><button class="btn secondary" data-action="close-course-delete">Cancel</button></div>
  </section></div>`;
}

