<div class="page-container animate-fade-in">
  <div class="content-wrapper">

    <!-- Page Header -->
    <div class="page-header">
      <div>
        <h1>Group Interviews</h1>
        <p class="page-subtitle">Create and manage batch interview sessions for candidate groups</p>
      </div>
      <button class="btn btn-primary" (click)="openCreateModal()">
        <span class="material-symbols-rounded">group_add</span>
        Create Group Interview
      </button>
    </div>

    <!-- Stats -->
    <div class="stats-row">
      <div class="mini-stat">
        <span class="mini-stat-value">{{ stats().total }}</span>
        <span class="mini-stat-label">Total</span>
      </div>
      <div class="mini-stat">
        <span class="mini-stat-value orange">{{ stats().pending }}</span>
        <span class="mini-stat-label">In Progress</span>
      </div>
      <div class="mini-stat">
        <span class="mini-stat-value blue">{{ stats().completed }}</span>
        <span class="mini-stat-label">Completed</span>
      </div>
      <div class="mini-stat">
        <span class="mini-stat-value green">{{ stats().accepted }}</span>
        <span class="mini-stat-label">Accepted</span>
      </div>
      <div class="mini-stat">
        <span class="mini-stat-value red">{{ stats().rejected }}</span>
        <span class="mini-stat-label">Rejected</span>
      </div>
    </div>

    <!-- Filter -->
    <div class="filter-bar">
      <select class="filter-select" [(ngModel)]="filterStatus" (ngModelChange)="onFilterChange()">
        <option value="">All Statuses</option>
        <option value="pending">Pending</option>
        <option value="quiz_phase">Quiz Phase</option>
        <option value="coding_phase">Coding Phase</option>
        <option value="evaluation">Evaluation</option>
        <option value="completed">Completed</option>
      </select>
    </div>

    <!-- Interview Group List -->
    @if (loading()) {
      <div class="loading-center"><div class="spinner spinner-lg"></div><p>Loading interviews...</p></div>
    } @else if (groupedList().length === 0) {
      <div class="empty-state">
        <span class="material-symbols-rounded">groups</span>
        <h3>No group interviews found</h3>
        <p>Create your first group interview session to get started</p>
      </div>
    } @else {
      <div class="interview-list">
        @for (g of groupedList(); track g.groupId) {
          <div class="interview-card card card-padding" (click)="openDetail(g)">
            <div class="iv-card-top">
              <div class="iv-group-info">
                <div class="iv-group-avatar">
                  <span class="material-symbols-rounded">groups</span>
                </div>
                <div>
                  <h3 class="iv-name">{{ g.groupId }}</h3>
                  <p class="iv-email">{{ g.members.length }} candidate{{ g.members.length !== 1 ? 's' : '' }} · {{ g.position }}</p>
                </div>
              </div>
              <div class="iv-card-right">
                <span class="badge badge-group">Group</span>
                @if (completedCount(g.members) === g.members.length && g.members.length > 0) {
                  <span class="badge badge-success">All Done</span>
                } @else {
                  <span class="badge badge-warning">In Progress</span>
                }
                <!-- Dropdown toggle button with alert indicator -->
                <div class="eval-toggle-wrap">
                  @if (groupHasPendingEvals(g.members)) {
                    <span class="eval-alert-dot" title="You have pending evaluations"></span>
                  }
                  <button class="eval-toggle-btn" [class.open]="isExpanded(g.groupId)"
                    (click)="toggleExpand(g.groupId, $event)"
                    [title]="isExpanded(g.groupId) ? 'Hide candidates' : 'Quick Evaluate'">
                    <span class="material-symbols-rounded">{{ isExpanded(g.groupId) ? 'expand_less' : 'how_to_reg' }}</span>
                    <span class="eval-toggle-label">{{ isExpanded(g.groupId) ? 'Close' : 'Evaluate' }}</span>
                    @if (groupHasPendingEvals(g.members) && !isExpanded(g.groupId)) {
                      <span class="eval-badge-count">{{ g.members.length }}</span>
                    }
                  </button>
                </div>
              </div>
            </div>

            <div class="iv-card-meta">
              <span class="meta-item"><span class="material-symbols-rounded">work</span> {{ g.position }}</span>
              @if (g.techStack) {
                <span class="meta-item"><span class="material-symbols-rounded">code</span> {{ g.techStack }}</span>
              }
              <span class="meta-item"><span class="material-symbols-rounded">calendar_today</span> {{ g.dateOfInterview | date:'mediumDate' }}</span>
              @if (g.assignedInterviewers?.length > 0) {
                <span class="meta-item"><span class="material-symbols-rounded">person</span> {{ g.assignedInterviewers[0]?.name }}</span>
              }
            </div>

            <!-- Quick-evaluate dropdown panel -->
            @if (isExpanded(g.groupId)) {
              <div class="quick-eval-panel" (click)="$event.stopPropagation()">
                <div class="qep-header">
                  <span class="material-symbols-rounded">how_to_reg</span>
                  <span>Select a candidate to evaluate</span>
                </div>
                @for (m of g.members; track m._id) {
                  <div class="qep-row" [class.qep-done]="!['quiz_phase', 'coding_phase'].includes(m.status) && !needsEvaluation(m)">
                    <div class="qep-candidate">
                      <div class="qep-avatar" [ngClass]="getStatusClass(m.status)">
                        {{ m.candidateId?.name?.charAt(0)?.toUpperCase() }}
                      </div>
                      <div class="qep-info">
                        <span class="qep-name">{{ m.candidateId?.name }}</span>
                        <span class="qep-status">{{ formatStatus(m.status) }}</span>
                      </div>
                    </div>
                    <div class="qep-action">
                      @if (['quiz_phase', 'coding_phase'].includes(m.status)) {
                        <span class="qep-pending-label" style="color:var(--text-muted); font-size:12px; font-weight:500; display:flex; align-items:center; gap:4px;">
                          <span class="material-symbols-rounded" style="font-size:16px;">hourglass_empty</span>
                          Pending
                        </span>
                      } @else if (needsEvaluation(m)) {
                        <button class="btn-evaluate" (click)="openMemberDetail(m._id, $event)">
                          <span class="material-symbols-rounded">rate_review</span>
                          Evaluate
                        </button>
                      } @else {
                        <span class="qep-done-label">
                          <span class="material-symbols-rounded">check_circle</span>
                          Done
                        </span>
                      }
                    </div>
                  </div>
                }
              </div>
            }
            
            <div class="iv-card-bottom">
              <span class="status-summary">{{ groupStatusSummary(g.members) }}</span>
            </div>
          </div>
        }
      </div>
    }
  </div>
</div>

<!-- ═══════════════════════════════════════════════════════════
     CREATE GROUP INTERVIEW MODAL
═══════════════════════════════════════════════════════════ -->
@if (showCreateModal()) {
  <div class="modal-overlay" (click)="closeCreateModal()">
    <div class="modal-container modal-xl" (click)="$event.stopPropagation()">

      <div class="modal-header">
        <h2>Create Group Interview</h2>
        <button class="icon-btn" (click)="closeCreateModal()"><span class="material-symbols-rounded">close</span></button>
      </div>

      @if (successMsg()) {
        <div class="success-banner">
          <span class="material-symbols-rounded">check_circle</span>
          {{ successMsg() }}
          <button class="btn btn-outline btn-sm" (click)="closeCreateModal()">Close</button>
        </div>
      } @else {
        <div class="modal-body">

          <!-- Staff assignment -->
          <div class="section-title">
            <span class="material-symbols-rounded">badge</span> Staff Assignment
          </div>
          <div class="form-row three-col">
            <div class="form-group">
              <label class="form-label">Interviewers</label>
              <div class="checklist-box">
                @for (i of interviewers(); track i._id) {
                  <label class="check-item">
                    <input type="checkbox" [value]="i._id"
                      (change)="toggleSelection($event, newGroupInterview.assignedInterviewers)">
                    <span>{{ i.name }}</span>
                  </label>
                }
                @if (interviewers().length === 0) { <p class="text-muted">No interviewers found</p> }
              </div>
            </div>
            <div class="form-group">
              <label class="form-label">HR Personnel</label>
              <div class="checklist-box">
                @for (h of hrs(); track h._id) {
                  <label class="check-item">
                    <input type="checkbox" [value]="h._id"
                      (change)="toggleSelection($event, newGroupInterview.assignedHRs)">
                    <span>{{ h.name }}</span>
                  </label>
                }
                @if (hrs().length === 0) { <p class="text-muted">No HR found</p> }
              </div>
            </div>
            <div class="form-group">
              <label class="form-label">Project Managers</label>
              <div class="checklist-box">
                @for (p of pms(); track p._id) {
                  <label class="check-item">
                    <input type="checkbox" [value]="p._id"
                      (change)="toggleSelection($event, newGroupInterview.assignedPMs)">
                    <span>{{ p.name }}</span>
                  </label>
                }
                @if (pms().length === 0) { <p class="text-muted">No PMs found</p> }
              </div>
            </div>
          </div>

          <!-- Group + Position -->
          <div class="section-title">
            <span class="material-symbols-rounded">groups</span> Group & Position
          </div>
          <div class="form-row">
            <div class="form-group">
              <label class="form-label">Group *</label>
              <select class="form-input" [(ngModel)]="newGroupInterview.groupName" (ngModelChange)="onGroupChange()">
                <option value="">Select group</option>
                @for (g of groups(); track g) {
                  <option [value]="g">{{ g }}</option>
                }
              </select>
              @if (groupMembers().length > 0) {
                <span class="field-hint">
                  <span class="material-symbols-rounded">person</span>
                  {{ groupMembers().length }} candidate{{ groupMembers().length !== 1 ? 's' : '' }} in this group
                </span>
              }
            </div>
            <div class="form-group">
              <label class="form-label">Position *</label>
              <input class="form-input" [(ngModel)]="newGroupInterview.position" placeholder="e.g., MEAN Stack Developer">
            </div>
          </div>
          <div class="form-row">
            <div class="form-group">
              <label class="form-label">Source</label>
              <input class="form-input" [(ngModel)]="newGroupInterview.source" placeholder="e.g., LinkedIn, Campus">
            </div>
            <div class="form-group">
              <label class="form-label">Date of Interview</label>
              <input class="form-input" type="date" [(ngModel)]="newGroupInterview.dateOfInterview">
            </div>
          </div>
          <div class="form-row">
            <div class="form-group">
              <label class="form-label">Tech Stack</label>
              <input class="form-input" [(ngModel)]="newGroupInterview.techStack" placeholder="e.g., MERN, Java, Python">
            </div>
          </div>

          <!-- Quiz Configuration -->
          <div class="section-title">
            <span class="material-symbols-rounded">quiz</span> Quiz Configuration
            @if (quizSets.length > 0) {
              <button class="btn btn-outline btn-sm" style="margin-left: auto;" (click)="addMoreSet()">
                <span class="material-symbols-rounded">add</span> Add Quiz
              </button>
            }
          </div>

          @if (quizSets.length === 0 && !showQuizSetup) {
            <div class="quiz-empty-hint">
              <span class="material-symbols-rounded">quiz</span>
              <p>No quizzes configured yet.</p>
              <button class="btn btn-primary" (click)="showQuizSetup = true">
                <span class="material-symbols-rounded">add</span> Add Quiz
              </button>
            </div>
          }

          @if (showQuizSetup) {
            <div class="quiz-setup-prompt">
              <span class="material-symbols-rounded">help_outline</span>
              <span>How many quizzes?</span>
              <input type="number" min="1" max="10" class="sets-count-input"
                [(ngModel)]="pendingSetsCount" placeholder="e.g. 2">
              <button class="btn btn-primary btn-sm" (click)="confirmSetsCount()">Confirm</button>
              <button class="btn btn-outline btn-sm" (click)="showQuizSetup = false">Cancel</button>
            </div>
          }

          <!-- Quiz Sets -->
          @for (set of quizSets; track $index; let si = $index) {
            <div class="quiz-set-block">
              <div class="quiz-set-header">
                <div class="quiz-set-title">
                  <span class="set-badge">Quiz {{ si + 1 }}</span>
                  @if (isSingleQuizSet(set)) {
                    <span class="set-note">📌 Assigned to all candidates</span>
                  } @else if (isMultiQuizSet(set)) {
                    <span class="set-note">🎯 {{ validEntries(set).length }} sets · {{ set.mode === 'random' ? '🎲 Random' : 'Direct' }} assignment</span>
                  }
                </div>
                <button class="icon-btn danger" (click)="removeQuizSet(si)">
                  <span class="material-symbols-rounded">delete</span>
                </button>
              </div>

              <!-- Quiz entries in this set -->
              @for (entry of set.quizEntries; track $index; let ei = $index) {
                <div class="quiz-entry-row">
                  <select class="form-input" [(ngModel)]="entry.quizId">
                    <option value="">— Select set —</option>
                    @for (q of getAvailableQuizzes(si, ei); track q._id) {
                      <option [value]="q._id">{{ q.title }}</option>
                    }
                  </select>
                  <button class="icon-btn" (click)="removeQuizEntry(si, ei)">
                    <span class="material-symbols-rounded">remove_circle_outline</span>
                  </button>
                </div>
              }

              <button class="btn btn-ghost btn-sm" (click)="addQuizToSet(si)">
                <span class="material-symbols-rounded">add</span> Add set to Quiz {{ si + 1 }}
              </button>

              <!-- Assignment mode — only shown when multiple quizzes -->
              @if (isMultiQuizSet(set)) {
                <div class="assignment-mode-row">
                  <span class="mode-label">Assignment Mode:</span>
                  <div class="mode-toggle">
                    <button class="mode-btn" [class.active]="set.mode === 'random'" (click)="set.mode = 'random'">
                      <span class="material-symbols-rounded">shuffle</span> Random
                    </button>
                    <button class="mode-btn" [class.active]="set.mode === 'direct'" (click)="set.mode = 'direct'">
                      <span class="material-symbols-rounded">assignment_ind</span> Direct
                    </button>
                  </div>
                </div>

                <!-- Direct assignment table -->
                @if (set.mode === 'direct') {
                  @if (groupMembers().length === 0) {
                    <p class="text-muted" style="font-size:13px; margin-top:8px;">
                      ⚠️ Select a group above to assign quizzes to individual candidates.
                    </p>
                  } @else {
                    <div class="direct-assignment-table">
                      <div class="da-header">
                        <span>Candidate</span>
                        <span>Assigned Quiz (Set {{ si + 1 }})</span>
                      </div>
                      @for (member of groupMembers(); track member._id) {
                        <div class="da-row">
                          <div class="da-candidate">
                            <div class="da-avatar">{{ member.name.charAt(0).toUpperCase() }}</div>
                            <span>{{ member.name }}</span>
                          </div>
                          <select class="form-input" [(ngModel)]="set.directAssignments[member._id]">
                            <option value="">— Select —</option>
                            @for (entry of validEntries(set); track entry.quizId) {
                              <option [value]="entry.quizId">{{ getQuizTitle(entry.quizId) }}</option>
                            }
                          </select>
                        </div>
                      }
                    </div>
                  }
                }
              }
            </div>
          }

        </div><!-- /modal-body -->

        <div class="modal-footer">
          <button class="btn btn-outline" (click)="closeCreateModal()">Cancel</button>
          <button class="btn btn-primary"
            (click)="createGroupInterview()"
            [disabled]="isSubmitting() || !newGroupInterview.groupName || !newGroupInterview.position">
            @if (isSubmitting()) {
              <span class="spinner spinner-sm"></span> Creating...
            } @else {
              <span class="material-symbols-rounded">rocket_launch</span> Create Group Interview
            }
          </button>
        </div>
      }

    </div>
  </div>
}

<!-- ═══════════════════════════════════════════════════════════
     DETAIL MODAL — All candidates in a group session
═══════════════════════════════════════════════════════════ -->
@if (showDetailModal() && selectedGroup()) {
  <div class="modal-overlay" (click)="closeDetail()">
    <div class="modal-container modal-xl" (click)="$event.stopPropagation()">

      <div class="modal-header">
        <div>
          <h2>{{ selectedGroup().groupId }}</h2>
          <span style="font-size:13px; color:var(--text-muted)">
            {{ selectedGroup().position }} · {{ selectedGroup().members.length }} candidates
          </span>
        </div>
        <button class="icon-btn" (click)="closeDetail()"><span class="material-symbols-rounded">close</span></button>
      </div>

      <div class="modal-body detail-body">

        <!-- Session meta -->
        <div class="detail-section">
          <h3 class="detail-section-title">Session Info</h3>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="detail-label">Position</span>
              <span class="detail-value">{{ selectedGroup().position }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">Tech Stack</span>
              <span class="detail-value">{{ selectedGroup().techStack || '—' }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">Source</span>
              <span class="detail-value">{{ selectedGroup().source || '—' }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">Interview Date</span>
              <span class="detail-value">{{ selectedGroup().dateOfInterview | date:'mediumDate' }}</span>
            </div>
          </div>
        </div>

        <!-- Candidate rows -->
        <div class="detail-section">
          <h3 class="detail-section-title">Candidates</h3>
          <div class="candidate-detail-list">
            @for (m of selectedGroup().members; track m._id) {
              <div class="candidate-row">

                <!-- Top row: clickable avatar+name on the left, progress bar on the right -->
                <div class="candidate-row-top">
                  <div class="cr-clickable" style="cursor: default;">
                    <div class="iv-avatar small">{{ m.candidateId?.name?.charAt(0)?.toUpperCase() }}</div>
                    <div>
                      <div class="cr-name">
                        {{ m.candidateId?.name }}
                      </div>
                      <div class="cr-email">{{ m.candidateId?.email }}</div>
                    </div>
                  </div>
                  <div class="candidate-row-mid">
                    <div class="progress-steps mini">
                      <div class="step" [class.done]="['quiz_phase','coding_phase','evaluation','completed'].includes(m.status)">
                        <span class="step-dot"></span><span class="step-label">Created</span>
                      </div>
                      <div class="step-line" [class.done]="['quiz_phase','coding_phase','evaluation','completed'].includes(m.status)"></div>
                      <div class="step" [class.active]="m.status==='quiz_phase'" [class.done]="['coding_phase','evaluation','completed'].includes(m.status)">
                        <span class="step-dot"></span><span class="step-label">Quiz</span>
                      </div>
                      <div class="step-line" [class.done]="['coding_phase','evaluation','completed'].includes(m.status)"></div>
                      <div class="step" [class.active]="m.status==='coding_phase'" [class.done]="['evaluation','completed'].includes(m.status)">
                        <span class="step-dot"></span><span class="step-label">Coding</span>
                      </div>
                      <div class="step-line" [class.done]="['evaluation','completed'].includes(m.status)"></div>
                      <div class="step" [class.active]="m.status==='evaluation'" [class.done]="m.status==='completed'">
                        <span class="step-dot"></span><span class="step-label">Evaluate</span>
                      </div>
                      <div class="step-line" [class.done]="m.status==='completed'"></div>
                      <div class="step" [class.active]="m.status==='completed'" [class.done]="m.status==='completed'">
                        <span class="step-dot"></span><span class="step-label">Done</span>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- Bottom row: status badge + final decision -->
                <div class="candidate-row-bottom" style="display: flex; justify-content: space-between; width: 100%;">
                  <div style="display: flex; align-items: center; gap: 8px; cursor: pointer; padding: 4px; border-radius: 4px;" (click)="openMemberDetail(m._id, $event)">
                    <span style="font-size: 11px; color: var(--text-muted); font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;">Current Status:</span>
                    <span class="badge" [ngClass]="getStatusClass(m.status)">{{ formatStatus(m.status) }}</span>
                    @if (needsEvaluation(m)) {
                      <span class="eval-pending-badge" title="Your evaluation is pending" style="margin-left: 4px;">⚠️ Evaluate</span>
                    }
                  </div>
                  
                  @if (m.finalDecision !== 'pending') {
                    <div style="display: flex; align-items: center; gap: 8px;">
                      <span style="font-size: 11px; color: var(--text-muted); font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;">Overall Status:</span>
                      <span class="badge" [ngClass]="getDecisionClass(m.finalDecision)">{{ formatDecision(m.finalDecision) }}</span>
                    </div>
                  }
                </div>

              </div>
            }
          </div>
        </div>

      </div>

      <div class="modal-footer">
        @if (authService.getUserRole() === 'admin' || authService.getUserRole() === 'hr') {
          <button class="btn btn-danger btn-sm" (click)="deleteGroupInterview(selectedGroup().groupId)">
            Delete All Interviews
          </button>
        }
        <button class="btn btn-outline" (click)="closeDetail()">Close</button>
      </div>

    </div>
  </div>
}

<!-- ═══════════════════════════════════════════════════════════
     MEMBER DETAIL MODAL — full evaluation panel for one candidate
═══════════════════════════════════════════════════════════ -->
@if (showMemberDetailModal() && selectedMember()) {
  <div class="modal-overlay" (click)="closeMemberDetail()">
    <div class="modal-container modal-xl" (click)="$event.stopPropagation()">

      <!-- Header -->
      <div class="modal-header">
        <div>
          <h2>{{ selectedMember().candidateId?.name }}</h2>
          <span class="badge" [ngClass]="getStatusClass(selectedMember().status)">{{ formatStatus(selectedMember().status) }}</span>
          @if (selectedMember().finalDecision !== 'pending') {
            <span class="badge" [ngClass]="getDecisionClass(selectedMember().finalDecision)" style="margin-left:6px">
              {{ formatDecision(selectedMember().finalDecision) }}
            </span>
          }
        </div>
        <button class="icon-btn" (click)="closeMemberDetail()"><span class="material-symbols-rounded">close</span></button>
      </div>

      <div class="modal-body detail-body">

        <!-- Candidate Info -->
        <div class="detail-section">
          <h3 class="detail-section-title">Candidate Information</h3>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="detail-label">Name</span>
              <span class="detail-value">{{ selectedMember().candidateId?.name }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">Email</span>
              <span class="detail-value">{{ selectedMember().candidateId?.email }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">Position</span>
              <span class="detail-value">{{ selectedMember().position }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">Tech Stack</span>
              <span class="detail-value">{{ selectedMember().techStack || '—' }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">Date of Interview</span>
              <span class="detail-value">{{ selectedMember().dateOfInterview | date:'mediumDate' }}</span>
            </div>
          </div>
        </div>

        <!-- Quiz Results -->
        @if (selectedMember().quizzes?.length > 0) {
          <div class="detail-section">
            <h3 class="detail-section-title">Quiz Results</h3>
            <div class="quiz-results-grid">
              @for (q of selectedMember().quizzes; track q.quizId) {
                <div class="quiz-result-card">
                  <div class="qr-title">{{ q.title }}</div>
                  @if (q.completed) {
                    <div class="qr-score">{{ q.score }}/{{ q.totalMarks }} ({{ q.percentage }}%)</div>
                  } @else {
                    <div class="qr-pending">Not Taken</div>
                  }
                </div>
              }
            </div>
          </div>
        }

        <!-- Evaluations -->
        <div class="detail-section">
          <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:16px;">
            <h3 class="detail-section-title" style="margin:0;">Evaluations</h3>
            <div style="display: flex; gap: 8px; align-items: center;">
              @if (allMemberEvaluationsDone()) {
                <span class="badge badge-success">All evaluations done</span>
                <button class="btn btn-primary btn-sm" (click)="downloadEvaluationPdf()">
                  @if (isPdfGenerating()) { <span class="spinner spinner-sm"></span> Generating... } @else { <span class="material-symbols-rounded" style="font-size: 16px; margin-right: 4px;">download</span> Download PDF }
                </button>
              } @else {
                <span class="badge badge-warning">Evaluations pending</span>
              }
            </div>
          </div>

          <!-- Evaluation list -->
          @if (selectedMember().evaluations?.length > 0) {
            <div class="eval-list">
              @for (ev of selectedMember().evaluations; track ev._id) {
                <div class="eval-card">
                  <div class="eval-header">
                    <div class="eval-evaluator">
                      <strong>{{ ev.evaluatorId?.name }}</strong>
                      <span class="eval-role badge badge-muted">{{ ev.evaluatorRole | uppercase }}</span>
                    </div>
                    <span class="badge" [ngClass]="getDecisionClass(ev.recommendation)">{{ formatDecision(ev.recommendation) }}</span>
                  </div>
                  @if (ev.comments) {
                    <p class="eval-comments">"{{ ev.comments }}"</p>
                  }
                  <span class="eval-date">{{ ev.date | date:'medium' }}</span>
                </div>
              }
            </div>
          } @else {
            <p class="text-muted">No evaluations yet</p>
          }

          <!-- Add evaluation form (HR / PM / Interviewer, not if already submitted or completed) -->
          @if (!hasMemberEvaluated() && selectedMember().status !== 'completed' && authService.getUserRole() !== 'admin') {
            <div class="eval-form">
              <h4>Add Your Evaluation</h4>
              <div class="form-group">
                <label class="form-label">Comments</label>
                <textarea class="form-input form-textarea" [(ngModel)]="memberEvalComment"
                  placeholder="Enter your comments..." rows="3"></textarea>
              </div>
              <div class="form-group">
                <label class="form-label">Recommendation *</label>
                <select class="form-input" [(ngModel)]="memberEvalRecommendation">
                  <option value="">Select recommendation</option>
                  <option value="offer">Offer / Hire as Intern</option>
                  <option value="on_hold">On Hold</option>
                  <option value="rejected">Rejected</option>
                  <option value="2nd_round">2nd Round</option>
                </select>
              </div>
              <button class="btn btn-primary" (click)="submitMemberEvaluation()"
                [disabled]="!memberEvalRecommendation || isMemberSubmitting()">
                @if (isMemberSubmitting()) { <span class="spinner spinner-sm"></span> Submitting... }
                @else { Submit Evaluation }
              </button>
            </div>
          }
        </div>

        <!-- Final Decision — Admin and HR, only when all evaluations done -->
        @if ((authService.getUserRole() === 'admin' || authService.getUserRole() === 'hr') && allMemberEvaluationsDone() && selectedMember().status !== 'completed') {
          <div class="detail-section decision-section">
            <h3 class="detail-section-title">Final Decision</h3>
            <div class="decision-buttons">
              <button class="btn btn-success" (click)="setMemberDecision('accepted')">
                <span class="material-symbols-rounded">check_circle</span> Accept
              </button>
              <button class="btn btn-warning" (click)="setMemberDecision('on_hold')">
                <span class="material-symbols-rounded">pause_circle</span> On Hold
              </button>
              <button class="btn btn-danger" (click)="setMemberDecision('rejected')">
                <span class="material-symbols-rounded">cancel</span> Reject
              </button>
              <button class="btn btn-outline" (click)="setMemberDecision('2nd_round')">
                <span class="material-symbols-rounded">replay</span> 2nd Round
              </button>
            </div>
          </div>
        }

      </div>

      <div class="modal-footer">
        <button class="btn btn-outline" (click)="closeMemberDetail()">Close</button>
      </div>

    </div>
  </div>
}

<!-- Print Template for Evaluation PDF -->
@if (selectedMember()) {
<div class="print-container">
  <div class="print-header">
    <div class="print-header-left">
      <h2 style="margin: 0; font-size: 20px;">Intern Interview Evaluation Form</h2>
    </div>
    <div class="print-header-right" style="text-align: right;">
      <span style="color: #0078d4; font-weight: bold; font-size: 24px;">IDEAL</span><br>
      <span style="font-size: 10px; color: #555;">TECH LABS</span>
    </div>
  </div>

  <table class="print-table" style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
    <tr>
      <td style="border: 1px solid #000; padding: 8px; font-weight: bold; width: 25%;">Candidate Name:</td>
      <td style="border: 1px solid #000; padding: 8px; width: 25%;">{{ selectedMember().candidateId?.name }}</td>
      <td style="border: 1px solid #000; padding: 8px; font-weight: bold; width: 25%;">Date of Interview:</td>
      <td style="border: 1px solid #000; padding: 8px; width: 25%;">{{ selectedMember().dateOfInterview | date:'mediumDate' }}</td>
    </tr>
    <tr>
      <td style="border: 1px solid #000; padding: 8px; font-weight: bold;">Position:</td>
      <td style="border: 1px solid #000; padding: 8px;">{{ selectedMember().position }}</td>
      <td style="border: 1px solid #000; padding: 8px; font-weight: bold;">Source</td>
      <td style="border: 1px solid #000; padding: 8px;">{{ selectedMember().source || '—' }}</td>
    </tr>
    <tr>
      <td style="border: 1px solid #000; padding: 8px; font-weight: bold;">Tech Stack:</td>
      <td style="border: 1px solid #000; padding: 8px;">{{ selectedMember().techStack || '—' }}</td>
      <td style="border: 1px solid #000; padding: 8px; font-weight: bold;">Interviewer(s):</td>
      <td style="border: 1px solid #000; padding: 8px;">
        @if (selectedMember().assignedInterviewers?.length) {
          @for (i of selectedMember().assignedInterviewers; track i._id; let last = $last) {
            {{ i.name }}{{ !last ? ', ' : '' }}
          }
        } @else {
          {{ selectedMember().interviewerId?.name || '—' }}
        }
      </td>
    </tr>
    <tr>
      <td style="border: 1px solid #000; padding: 8px; font-weight: bold;">General Aptitude Test QP Set</td>
      <td style="border: 1px solid #000; padding: 8px;">{{ selectedMember().quizzes?.[0]?.title || '—' }}</td>
      <td style="border: 1px solid #000; padding: 8px; font-weight: bold;">General Aptitude Test Score</td>
      <td style="border: 1px solid #000; padding: 8px;">{{ selectedMember().quizzes?.[0]?.completed ? selectedMember().quizzes[0].score + '/' + selectedMember().quizzes[0].totalMarks : 'Not Taken' }}</td>
    </tr>
    <tr>
      <td style="border: 1px solid #000; padding: 8px; font-weight: bold;">Technical MCQ Test QP Set</td>
      <td style="border: 1px solid #000; padding: 8px;">{{ selectedMember().quizzes?.[1]?.title || '—' }}</td>
      <td style="border: 1px solid #000; padding: 8px; font-weight: bold;">Technical MCQ Test Score</td>
      <td style="border: 1px solid #000; padding: 8px;">{{ selectedMember().quizzes?.[1]?.completed ? selectedMember().quizzes[1].score + '/' + selectedMember().quizzes[1].totalMarks : 'Not Taken' }}</td>
    </tr>
  </table>

  <!-- Render evaluations -->
  @for (ev of selectedMember().evaluations; track ev._id) {
    <div class="print-eval-block" style="margin-bottom: 30px; page-break-inside: avoid;">
      <div class="print-eval-title" style="font-weight: bold; margin-bottom: 10px;">
        {{ ev.evaluatorRole === 'hr' ? 'HR' : ev.evaluatorRole === 'pm' ? 'Project Manager' : 'Interviewer' }}'s Comments ({{ ev.evaluatorId?.name }}):
      </div>
      <div class="print-comments" style="min-height: 80px; margin-bottom: 15px;">
        {{ ev.comments || 'No comments provided.' }}
      </div>
      
      <div class="print-recommendation" style="margin-bottom: 20px;">
        <strong style="margin-right: 15px;">Recommendation:</strong>
        <span style="margin-right: 15px;"><span style="font-size: 16px;">{{ ev.recommendation === 'offer' ? '☑' : '☐' }}</span> Offer/Hire as Intern</span>
        <span style="margin-right: 15px;"><span style="font-size: 16px;">{{ ev.recommendation === 'on_hold' ? '☑' : '☐' }}</span> On Hold</span>
        <span style="margin-right: 15px;"><span style="font-size: 16px;">{{ ev.recommendation === 'rejected' ? '☑' : '☐' }}</span> Rejected</span>
        <span><span style="font-size: 16px;">{{ ev.recommendation === '2nd_round' ? '☑' : '☐' }}</span> 2nd Round</span>
      </div>

      <div class="print-signature-row" style="display: flex; justify-content: space-between; align-items: flex-end;">
        <div class="print-signature" style="display: flex; align-items: flex-end;">
          <strong>Evaluator's Signature:</strong>
          @if (ev.evaluatorId?.signature) {
            <img [src]="'http://localhost:5000' + ev.evaluatorId.signature" style="max-height: 40px; margin-left: 10px;">
          } @else {
            <span style="border-bottom: 1px solid #000; display: inline-block; width: 150px; margin-left: 10px;"></span>
          }
        </div>
        <div class="print-date" style="display: flex; align-items: flex-end;">
          <strong>Date:</strong>
          <span style="border-bottom: 1px solid #000; display: inline-block; width: 120px; margin-left: 10px; text-align: center;">{{ ev.date | date:'shortDate' }}</span>
        </div>
      </div>
    </div>
  }
</div>
}
