<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>
      
    </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)">

            <!-- Top row: group info + badges + dropdown toggle -->
            <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>

            <!-- Meta row -->
            <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>



<!-- ═══════════════════════════════════════════════════════════
     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 class="detail-item">
              <span class="detail-label">Interviewer(s)</span>
              <span class="detail-value">
                @if (selectedGroup().assignedInterviewers?.length) {
                  @for (i of selectedGroup().assignedInterviewers; track i._id; let last = $last) {
                    {{ i.name }}{{ !last ? ', ' : '' }}
                  }
                } @else {
                  —
                }
              </span>
            </div>
            <div class="detail-item">
              <span class="detail-label">HR(s)</span>
              <span class="detail-value">
                @if (selectedGroup().assignedHRs?.length) {
                  @for (h of selectedGroup().assignedHRs; track h._id; let last = $last) {
                    {{ h.name }}{{ !last ? ', ' : '' }}
                  }
                } @else {
                  —
                }
              </span>
            </div>
            <div class="detail-item">
              <span class="detail-label">Project Manager(s)</span>
              <span class="detail-value">
                @if (selectedGroup().assignedPMs?.length) {
                  @for (p of selectedGroup().assignedPMs; track p._id; let last = $last) {
                    {{ p.name }}{{ !last ? ', ' : '' }}
                  }
                } @else {
                  —
                }
              </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>
                  </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">
        
        <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" [class.violation]="q.violation">{{ q.score }}/{{ q.totalMarks }} ({{ q.percentage }}%)</div>
                    @if (q.violation) {
                      <div style="color: #ef4444; font-size: 11px; margin-top: 6px; display: flex; align-items: center; gap: 4px; font-weight: 500;">
                        <span class="material-symbols-rounded" style="font-size: 14px;">warning</span> Auto-submitted (Violation)
                      </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 (getVisibleEvaluations(selectedMember().evaluations).length > 0) {
            <div class="eval-list">
              @for (ev of getVisibleEvaluations(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') {
            <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 -->
        

      </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]="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>
}
