// Split from public/app.js v1.7.7. Loaded by public/index.html.
function messagesView() {
  const courses = state.data.courses || [];
  const batches = state.data.batches || [];
  const students = state.data.students || [];
  const notifications = state.data.notifications || [];
  const section = state.messageSection || 'general';
  return html`
    <section class="panel">
      <div class="panel-header">
        <div>
          <h1>Messages</h1>
          <p class="muted">Send profile notifications and optional SMS to students.</p>
        </div>
      </div>
      <div class="section-tabs">
        <button class="section-tab ${section === 'general' ? 'active' : ''}" data-action="set-message-section" data-section="general">General Message</button>
        <button class="section-tab ${section === 'due' ? 'active' : ''}" data-action="set-message-section" data-section="due">Due Reminder</button>
        ${canAccessMenu('resultSms') ? `<button class="section-tab ${section === 'resultSms' ? 'active' : ''}" data-action="set-message-section" data-section="resultSms">Result SMS</button>` : ''}
      </div>
    </section>
    ${section === 'due' ? dueReminderView() : section === 'resultSms' ? (canAccessMenu('resultSms') ? resultSmsView() : '<section class="panel"><p class="muted">You do not have Result SMS permission.</p></section>') : html`
    <section class="panel">
      <form class="form-grid" data-action="send-notification">
        <div class="grid-3">
          <label class="field"><span>Audience</span>
            <select name="audienceType">
              <option value="all">All active students</option>
              <option value="course">By course</option>
              <option value="batch">By batch</option>
              <option value="selected">Selected students</option>
            </select>
          </label>
          ${messageMultiSelect('Courses', 'courseIds', courses.map((course) => ({ id: course.id, name: `${course.name} (${course.code || '-'})` })), 'Select courses')}
          ${messageMultiSelect('Batches', 'batchIds', batches.map((batch) => ({ id: batch.id, name: `${batch.name} (${batch.code || '-'})` })), 'Select batches')}
        </div>
        ${messageMultiSelect('Selected Students', 'studentIds', students.map((student) => ({ id: student.id, name: `${student.name} - ${student.rollNumber || student.studentMobile}` })), 'Select students')}
        <label class="field"><span>Title *</span><input name="title" placeholder="Class notice" required></label>
        <label class="field"><span>Message *</span><textarea name="body" rows="5" placeholder="Write your notification message" required></textarea></label>
        <label class="field checkbox-line"><input name="sendSms" type="checkbox"> <span>Also send mobile SMS using active SMS gateway</span></label>
        <button class="btn" type="submit">Send Message</button>
      </form>
    </section>
    `}
    <section class="panel">
      <div class="panel-header"><h2>Recent Messages</h2></div>
      <div class="table-wrap"><table><thead><tr><th>Title</th><th>Audience</th><th>Recipients</th><th>SMS</th><th>Sent At</th></tr></thead><tbody>
        ${notifications.map((item) => `<tr><td><strong>${escapeHtml(item.title)}</strong><br><span class="muted">${escapeHtml(item.body)}</span></td><td>${escapeHtml(item.audienceType || 'all')}${item.courseIds?.length ? ` (${item.courseIds.length} courses)` : ''}${item.batchIds?.length ? ` (${item.batchIds.length} batches)` : ''}</td><td>${Number(item.recipientIds?.length || 0)}</td><td>${item.sendSms ? `${Number(item.smsSent || 0)} sent` : 'Off'}</td><td>${formatDate(item.createdAt)}</td></tr>`).join('') || '<tr><td colspan="5">No messages sent yet.</td></tr>'}
      </tbody></table></div>
    </section>
  `;
}

function messageMultiSelect(label, inputName, items, placeholder = 'Select items') {
  return html`<div class="field message-select-field"><span>${escapeHtml(label)}</span>
    <div class="multi-select message-multi-select" data-message-dropdown>
      <button class="multi-select-trigger" type="button" data-action="toggle-message-dropdown" aria-expanded="false">
        <span data-message-summary data-placeholder="${escapeHtml(placeholder)}">${escapeHtml(placeholder)}</span>
        <span class="multi-select-arrow" aria-hidden="true">⌄</span>
      </button>
      <div class="multi-select-menu" hidden>
        ${items.length ? items.map((item) => `<button class="multi-select-option" type="button" data-action="toggle-message-option" data-name="${escapeHtml(item.name)}" aria-pressed="false"><input type="hidden" name="${escapeHtml(inputName)}" value="${escapeHtml(item.id)}" disabled data-message-value><span class="multi-select-check" aria-hidden="true">✓</span><span>${escapeHtml(item.name)}</span></button>`).join('') : '<p class="muted multi-select-empty">No item found.</p>'}
      </div>
    </div>
  </div>`;
}

function dueReminderView() {
  const students = (state.data.students || []).filter((student) => Number(student.finance?.totalDue || 0) > 0);
  const courses = state.data.courses || [];
  const batches = state.data.batches || [];
  const totalDue = students.reduce((sum, student) => sum + Number(student.finance?.totalDue || 0), 0);
  const template = 'Dear {name}, your due amount is Tk {due}. Please pay soon. - {institute}';
  return html`
    <section class="panel">
      <div class="panel-header"><div><h2>Due Reminder</h2><p class="muted">Send profile notifications and optional SMS to students with outstanding dues.</p></div></div>
      <div class="finance-summary">
        ${metricCard('Due Students', String(students.length))}
        ${financeCard('Total Due', totalDue, 'danger')}
      </div>
      <form class="form-grid" data-action="send-due-reminders">
        <div class="grid-3">
          ${messageMultiSelect('Courses', 'courseIds', courses.map((course) => ({ id: course.id, name: `${course.name} (${course.code || '-'})` })), 'All courses')}
          ${messageMultiSelect('Batches', 'batchIds', batches.map((batch) => ({ id: batch.id, name: `${batch.name} (${batch.code || '-'})` })), 'All batches')}
          <label class="field"><span>Minimum Due</span><input name="minDue" type="number" min="0" step="1" placeholder="0"></label>
        </div>
        <label class="field"><span>Title</span><input name="title" value="Payment Due Reminder"></label>
        <label class="field"><span>Message Template</span><textarea name="template" rows="4">${escapeHtml(template)}</textarea></label>
        <p class="muted">Available fields: {name}, {roll}, {mobile}, {due}, {institute}</p>
        <label class="field checkbox-line"><input name="sendSms" type="checkbox"> <span>Also send mobile SMS using active SMS gateway</span></label>
        <button class="btn" type="submit">Send Due Reminder</button>
      </form>
    </section>
    <section class="panel">
      <div class="panel-header"><div><h2>Due Preview</h2><p class="muted">Students currently matching due reminder condition before filters.</p></div></div>
      <div class="table-wrap"><table><thead><tr><th>Student</th><th>Roll</th><th>Mobile</th><th>Courses</th><th>Total Due</th></tr></thead><tbody>
        ${students.slice(0, 12).map((student) => `<tr><td>${escapeHtml(student.name)}</td><td>${escapeHtml(student.rollNumber || '-')}</td><td>${escapeHtml(student.studentMobile || student.mobile || '-')}</td><td>${escapeHtml(courseNames(student.courseIds) || '-')}</td><td><strong>${formatMoney(student.finance?.totalDue || 0)}</strong></td></tr>`).join('') || '<tr><td colspan="5">No due students found.</td></tr>'}
      </tbody></table></div>
    </section>
  `;
}

function teachersView() {
  const teachers = state.data.teachers || [];
  return html`
    <section class="panel">
      <div class="panel-header"><div><h1>Teachers</h1><p class="muted">Create teacher profiles for class and payment tracking.</p></div></div>
      <form class="form-grid" data-action="add-teacher">
        <div class="grid-3">
          <label class="field"><span>Name *</span><input name="name" placeholder="Teacher name" required></label>
          <label class="field"><span>Mobile *</span><input name="mobile" placeholder="01XXXXXXXXX" required></label>
          <label class="field"><span>Email</span><input name="email" type="email" placeholder="teacher@example.com"></label>
        </div>
        <div class="grid-3">
          <label class="field"><span>Subject</span><input name="subject" placeholder="Subject name"></label>
          <label class="field"><span>Default Rate / Class</span><input name="rate" type="number" min="0" step="0.01" placeholder="0"></label>
          <label class="field"><span>Note</span><input name="note" placeholder="Optional note"></label>
        </div>
        <button class="btn" type="submit">Add Teacher</button>
      </form>
    </section>
    <section class="panel">
      <div class="panel-header"><h2>Teacher List</h2></div>
      <div class="table-wrap"><table><thead><tr><th>Name</th><th>Mobile</th><th>Subject</th><th>Rate</th><th>Status</th><th>Actions</th></tr></thead><tbody>
        ${teachers.map((teacher) => `<tr><td>${escapeHtml(teacher.name)}<br><span class="muted">${escapeHtml(teacher.email || '-')}</span></td><td>${escapeHtml(teacher.mobile)}</td><td>${escapeHtml(teacher.subject || '-')}</td><td>${formatMoney(teacher.rate)}</td><td><span class="badge ${teacher.status === 'active' ? 'success' : 'danger'}">${teacher.status}</span></td><td><div class="actions"><button class="btn secondary small" data-action="edit-teacher" data-id="${teacher.id}">Edit</button><button class="btn secondary small" data-action="toggle-teacher" data-id="${teacher.id}" data-status="${teacher.status === 'active' ? 'inactive' : 'active'}">${teacher.status === 'active' ? 'Deactivate' : 'Activate'}</button></div></td></tr>`).join('') || '<tr><td colspan="6">No teachers yet.</td></tr>'}
      </tbody></table></div>
    </section>
    ${state.editingTeacherId ? teacherEditDialog() : ''}
  `;
}

function teacherEditDialog() {
  const teacher = (state.data.teachers || []).find((item) => item.id === state.editingTeacherId);
  if (!teacher) return '';
  return html`<div class="modal-backdrop"><section class="modal-card modal-wide">
    <div class="panel-header"><div><h2>Edit Teacher</h2><p class="muted">${escapeHtml(teacher.mobile)}</p></div><button class="btn secondary small" data-action="close-teacher-edit">Close</button></div>
    <form class="form-grid" data-action="edit-teacher" data-id="${teacher.id}">
      <div class="grid-3">
        <label class="field"><span>Name *</span><input name="name" value="${escapeHtml(teacher.name)}" required></label>
        <label class="field"><span>Mobile *</span><input name="mobile" value="${escapeHtml(teacher.mobile)}" required></label>
        <label class="field"><span>Email</span><input name="email" type="email" value="${escapeHtml(teacher.email || '')}"></label>
      </div>
      <div class="grid-3">
        <label class="field"><span>Subject</span><input name="subject" value="${escapeHtml(teacher.subject || '')}"></label>
        <label class="field"><span>Default Rate / Class</span><input name="rate" type="number" min="0" step="0.01" value="${Number(teacher.rate || 0)}"></label>
        <label class="field"><span>Note</span><input name="note" value="${escapeHtml(teacher.note || '')}"></label>
      </div>
      <button class="btn" type="submit">Save Teacher</button>
    </form>
  </section></div>`;
}

function employeesView() {
  const employees = state.data.employees || [];
  return html`
    <section class="panel">
      <div class="panel-header"><div><h1>Employees</h1><p class="muted">Create employee profiles for salary and staff payment tracking.</p></div></div>
      <form class="form-grid" data-action="add-employee">
        <div class="grid-3">
          <label class="field"><span>Name *</span><input name="name" placeholder="Employee name" required></label>
          <label class="field"><span>Mobile *</span><input name="mobile" placeholder="01XXXXXXXXX" required></label>
          <label class="field"><span>Email</span><input name="email" type="email" placeholder="employee@example.com"></label>
        </div>
        <div class="grid-3">
          <label class="field"><span>Designation</span><input name="designation" placeholder="Office assistant"></label>
          <label class="field"><span>Monthly Salary</span><input name="salary" type="number" min="0" step="0.01" placeholder="0"></label>
          <label class="field"><span>Note</span><input name="note" placeholder="Optional note"></label>
        </div>
        <button class="btn" type="submit">Add Employee</button>
      </form>
    </section>
    <section class="panel">
      <div class="panel-header"><h2>Employee List</h2></div>
      <div class="table-wrap"><table><thead><tr><th>Name</th><th>Mobile</th><th>Designation</th><th>Salary</th><th>Status</th><th>Actions</th></tr></thead><tbody>
        ${employees.map((employee) => `<tr><td>${escapeHtml(employee.name)}<br><span class="muted">${escapeHtml(employee.email || '-')}</span></td><td>${escapeHtml(employee.mobile)}</td><td>${escapeHtml(employee.designation || '-')}</td><td>${formatMoney(employee.salary)}</td><td><span class="badge ${employee.status === 'active' ? 'success' : 'danger'}">${employee.status}</span></td><td><div class="actions"><button class="btn secondary small" data-action="edit-employee" data-id="${employee.id}">Edit</button><button class="btn secondary small" data-action="toggle-employee" data-id="${employee.id}" data-status="${employee.status === 'active' ? 'inactive' : 'active'}">${employee.status === 'active' ? 'Deactivate' : 'Activate'}</button></div></td></tr>`).join('') || '<tr><td colspan="6">No employees yet.</td></tr>'}
      </tbody></table></div>
    </section>
    ${state.editingEmployeeId ? employeeEditDialog() : ''}
  `;
}

function employeeEditDialog() {
  const employee = (state.data.employees || []).find((item) => item.id === state.editingEmployeeId);
  if (!employee) return '';
  return html`<div class="modal-backdrop"><section class="modal-card">
    <div class="panel-header"><div><h2>Edit Employee</h2><p class="muted">${escapeHtml(employee.mobile)}</p></div><button class="btn secondary small" data-action="close-employee-edit">Close</button></div>
    <form class="form-grid" data-action="edit-employee" data-id="${employee.id}">
      <label class="field"><span>Name *</span><input name="name" value="${escapeHtml(employee.name)}" required></label>
      <label class="field"><span>Mobile *</span><input name="mobile" value="${escapeHtml(employee.mobile)}" required></label>
      <label class="field"><span>Email</span><input name="email" type="email" value="${escapeHtml(employee.email || '')}"></label>
      <label class="field"><span>Designation</span><input name="designation" value="${escapeHtml(employee.designation || '')}"></label>
      <label class="field"><span>Monthly Salary</span><input name="salary" type="number" min="0" step="0.01" value="${Number(employee.salary || 0)}"></label>
      <label class="field"><span>Note</span><input name="note" value="${escapeHtml(employee.note || '')}"></label>
      <button class="btn" type="submit">Save Employee</button>
    </form>
  </section></div>`;
}
