<div>
    <!-- Filter Form -->
    <div class="row mb-4">
        <div class="col-md-3">
            <label for="year" class="form-label">Academic Year</label>
            <select wire:model="year" class="form-select" id="year">
                <option value="">Select Year</option>
                @foreach($years as $yearOption)
                    <option value="{{ $yearOption }}">{{ $yearOption }}/{{ $yearOption + 1 }}</option>
                @endforeach
            </select>
        </div>
        <div class="col-md-3">
            <label for="classId" class="form-label">Class</label>
            <select wire:model.live="classId" class="form-select" id="classId">
                <option value="">Select Class</option>
                @foreach($classes as $class)
                    <option value="{{ $class->id }}">{{ $class->display_name }}</option>
                @endforeach
            </select>
        </div>
        <div class="col-md-3">
            <label for="batchId" class="form-label">Batch (Optional)</label>
            <select wire:model="batchId" class="form-select" id="batchId">
                <option value="">All Batches</option>
                @foreach($batches as $batch)
                    <option value="{{ $batch->id }}">{{ $batch->name }}</option>
                @endforeach
            </select>
        </div>
        <div class="col-md-3">
            <label class="form-label">&nbsp;</label>
            <button wire:click="loadAnnualMasterList" class="btn btn-primary w-100">
                <i class="fas fa-search me-2"></i>Load
            </button>
        </div>
    </div>

    @if(!empty($masterListData))
        <!-- Results Header -->
        <div class="row mb-3">
            <div class="col-12 d-flex justify-content-between align-items-center">
                <h5>Annual Master List for {{ $selectedYear }}/{{ $selectedYear + 1 }} - {{ $selectedClass->display_name }}
                    @if($selectedBatch) ({{ $selectedBatch->name }}) @endif
                </h5>
                <button type="button" class="btn btn-outline-info btn-sm" data-bs-toggle="modal" data-bs-target="#calculationHelpModal">
                    <i class="fas fa-question-circle"></i> Help
                </button>
            </div>
        </div>

        <!-- Desktop View -->
        <div class="d-none d-lg-block">
            <div class="table-responsive">
                <table class="table table-bordered table-striped table-sm">
                    <thead class="table-dark">
                        <tr>
                            <th rowspan="3" class="sticky-left">Pos</th>
                            <th rowspan="3" class="sticky-left-name">Student Name</th>
                            <th rowspan="3">Student ID</th>
                            @foreach($subjects as $subject)
                                <th colspan="{{ count($sessions) + 2 }}" class="text-center">{{ $subject->display_name }}</th>
                            @endforeach
                            @php
                                $sampleStudent = $masterListData[0] ?? null;
                                $sampleHelpers = $sampleStudent ? app('App\Services\AnnualResultService')->getCalculationHelpers($sessions, $subjects, $sampleStudent) : null;
                                $sampleAnnualMaxTotal = $sampleHelpers ? $sampleHelpers['annual_max_total'] : ($subjects->count() * 100 * count($sessions));
                            @endphp
                            <th rowspan="3">Annual Total @if(!empty($masterListData))({{ $sampleAnnualMaxTotal }})@endif</th>
                            <th rowspan="3">Total Average @if(!empty($masterListData))({{ 100 * $subjects->count() }})@endif</th>
                            <th rowspan="3">Annual Score % (100%)</th>
                            <th colspan="6" class="text-center">Annual Grades</th>
                            <th rowspan="3">Status</th>
                        </tr>
                        <tr>
                            @foreach($subjects as $subject)
                                @foreach($sessions as $session)
                                    <th class="text-center">{{ $session->name }}</th>
                                @endforeach
                                <th class="text-center">Total</th>
                                <th class="text-center">Avg</th>
                            @endforeach
                            <th>A</th>
                            <th>B</th>
                            <th>C</th>
                            <th>D</th>
                            <th>E</th>
                            <th>F</th>
                        </tr>
                        <tr>
                            @foreach($subjects as $subject)
                                @foreach($sessions as $session)
                                    <th></th>
                                @endforeach
                                <th></th>
                                <th></th>
                            @endforeach
                            @for($i = 0; $i < 6; $i++)
                                <th></th>
                            @endfor
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($masterListData as $studentData)
                            <tr>
                                <td class="sticky-left">{{ $studentData['position_suffix'] }}</td>
                                <td class="sticky-left-name">{{ $studentData['student']->name }}</td>
                                <td>{{ $studentData['student']->student_id }}</td>
                                @foreach($subjects as $subject)
                                    @php
                                        $subjectTotal = 0;
                                        $sessionCount = 0;
                                    @endphp
                                    @foreach($sessions as $session)
                                        @php
                                            $result = $studentData['sessions'][$session->id]['subjects'][$subject->id] ?? null;
                                            $total = $result['total'] ?? 0;
                                            if($total !== '-') {
                                                $subjectTotal += $total;
                                                if($total > 0) $sessionCount++;
                                            }
                                        @endphp
                                        <td>{{ $total === '-' ? '-' : $total }}</td>
                                    @endforeach
                                    <td><strong>{{ $subjectTotal }}</strong></td>
                                    <td class="{{ $loop->last ? '' : 'border-end-subject' }}"><strong>{{ $sessionCount > 0 ? round($subjectTotal / count($sessions), 2) : 0 }}</strong></td>
                                @endforeach
                                @php
                                    $helpers = app('App\Services\AnnualResultService')->getCalculationHelpers($sessions, $subjects, $studentData);
                                    $annualMaxTotal = $helpers['annual_max_total'];
                                    $correctedAnnualAverage = $helpers['corrected_annual_average'];
                                    $promotionStatus = $helpers['promotion_status'];
                                @endphp
                                <td><strong>{{ $studentData['annual_grand_total'] }}</strong></td>
                                <td><strong>{{ $studentData['total_average'] }}</strong></td>
                                <td><strong>{{ $correctedAnnualAverage }}%</strong></td>
                                <td>{{ $studentData['annual_grades']['A'] }}</td>
                                <td>{{ $studentData['annual_grades']['B'] }}</td>
                                <td>{{ $studentData['annual_grades']['C'] }}</td>
                                <td>{{ $studentData['annual_grades']['D'] }}</td>
                                <td>{{ $studentData['annual_grades']['E'] }}</td>
                                <td>{{ $studentData['annual_grades']['F'] }}</td>
                                <td>
                                    <span class="badge {{ $promotionStatus['is_promoted'] ? 'bg-success' : 'bg-danger' }}">
                                        {{ $promotionStatus['comment'] }}
                                    </span>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Mobile View -->
        <div class="d-lg-none">
            @foreach($masterListData as $index => $studentData)
                <div class="card mb-2">
                    <div class="card-header p-0">
                        <div class="d-flex">
                            <div class="flex-grow-1 p-3" data-bs-toggle="collapse"
                                 data-bs-target="#student{{ $index }}" style="cursor: pointer;">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <span class="badge bg-light text-dark me-2">{{ $studentData['position_suffix'] }}</span>
                                        <strong>{{ $studentData['student']->name }}</strong>
                                    </div>
                                    <div>
                                        <i class="fas fa-chevron-down text-muted"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="collapse" id="student{{ $index }}">
                        <div class="card-body">
                            <div class="mb-3">
                                <div class="d-flex flex-wrap gap-2 mb-2">
                                    @php
                                        $mobileHelpers = app('App\Services\AnnualResultService')->getCalculationHelpers($sessions, $subjects, $studentData);
                                        $mobilePromotionStatus = $mobileHelpers['promotion_status'];
                                    @endphp
                                    <span class="badge bg-primary">{{ $mobileHelpers['corrected_annual_average'] }}%</span>
                                    <span class="badge bg-{{ $mobilePromotionStatus['is_promoted'] ? 'success' : 'danger' }}">{{ $mobilePromotionStatus['comment'] }}</span>
                                </div>
                            </div>
                            
                            @foreach($sessions as $session)
                                <div class="mb-3">
                                    <h6>{{ $session->name }}</h6>
                                    <div class="table-responsive">
                                        <table class="table table-sm">
                                            <thead>
                                                <tr>
                                                    <th>Subject</th>
                                                    <th>CA</th>
                                                    <th>Exam</th>
                                                    <th>Total</th>
                                                    <th>Grade</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                @foreach($subjects as $subject)
                                                    @php
                                                        $result = $studentData['sessions'][$session->id]['subjects'][$subject->id] ?? null;
                                                    @endphp
                                                    <tr>
                                                        <td>{{ $subject->display_name }}</td>
                                                        <td>{{ $result['ca_score'] === '-' ? '-' : ($result['ca_score'] ?? 0) }}</td>
                                                        <td>{{ $result['exam_score'] === '-' ? '-' : ($result['exam_score'] ?? 0) }}</td>
                                                        <td>{{ $result['total'] === '-' ? '-' : ($result['total'] ?? 0) }}</td>
                                                        <td>{{ $result['grade'] === '-' ? '-' : ($result['grade'] ?? 'F') }}</td>
                                                    </tr>
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                    @if(!$loop->last)
                                        <hr class="my-2">
                                    @endif
                                </div>
                            @endforeach
                            <hr>
                            <div class="row">
                                <div class="col-6">
                                    <strong>Annual Total:</strong> {{ $studentData['annual_grand_total'] }}
                                </div>
                                <div class="col-6">
                                    <strong>Annual Average:</strong> {{ $mobileHelpers['corrected_annual_average'] }}%
                                </div>
                                <div class="col-12 mt-2">
                                    <strong>Grades:</strong>
                                    A: {{ $studentData['annual_grades']['A'] }},
                                    B: {{ $studentData['annual_grades']['B'] }},
                                    C: {{ $studentData['annual_grades']['C'] }},
                                    D: {{ $studentData['annual_grades']['D'] }},
                                    E: {{ $studentData['annual_grades']['E'] }},
                                    F: {{ $studentData['annual_grades']['F'] }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            @endforeach
        </div>

        <!-- Chart and Summary Section -->
        <div class="row mb-4">
            <!-- Chart Column -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">Class Performance Chart</h6>
                    </div>
                    <div class="card-body">
                        <canvas id="masterListChart" width="400" height="300" wire:ignore></canvas>
                    </div>
                </div>
            </div>
            
            <!-- Summary Column -->
            <div class="col-md-6">
                <!-- Class Summary Cards -->
                <div class="row mb-3">
                    <div class="col-6">
                        <div class="card text-center bg-primary">
                            <div class="card-body">
                                <h5 class="card-title text-white">Total Students</h5>
                                <h3 class="text-white">{{ count($masterListData) }}</h3>
                            </div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="card text-center bg-success">
                            <div class="card-body">
                                <h5 class="card-title text-white">Passed</h5>
                                @php
                                    $passedCount = 0;
                                    foreach($masterListData as $student) {
                                        $helpers = app('App\Services\AnnualResultService')->getCalculationHelpers($sessions, $subjects, $student);
                                        if($helpers['promotion_status']['is_promoted']) $passedCount++;
                                    }
                                @endphp
                                <h3 class="text-white">{{ $passedCount }}</h3>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-6">
                        <div class="card text-center bg-info">
                            <div class="card-body">
                                <h5 class="card-title text-white">Sessions</h5>
                                <h3 class="text-white">{{ count($sessions) }}</h3>
                            </div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="card text-center bg-danger">
                            <div class="card-body">
                                <h5 class="card-title text-white">Failed</h5>
                                <h3 class="text-white">{{ count($masterListData) - $passedCount }}</h3>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Grade Distribution -->
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">Class Grade Distribution</h6>
                    </div>
                    <div class="card-body">
                        <div class="row text-center g-2">
                            @foreach(['A', 'B', 'C', 'D', 'E', 'F'] as $grade)
                                <div class="col-6 col-sm-4 col-md-2">
                                    <div class="badge bg-{{ $grade === 'A' ? 'success' : ($grade === 'F' ? 'danger' : 'secondary') }} p-3 w-100 d-flex flex-column align-items-center justify-content-center" style="min-height: 60px;">
                                        <div class="fw-bold">{{ $grade }}</div>
                                        <div class="h6 mb-0">{{ collect($masterListData)->sum("annual_grades.$grade") }}</div>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Teachers and Timestamp -->
        @if(settings('show_class_teachers_online', true) || settings('show_timestamp', true))
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            @if(settings('show_class_teachers_online', true))
                            <div class="col-md-6">
                                <h6>Class Teachers:</h6>
                                @if($selectedClass && $selectedClass->teachers && $selectedClass->teachers->count() > 0)
                                    @foreach($selectedClass->teachers as $teacher)
                                        <span class="badge bg-primary me-1">{{ $teacher->name }}</span>
                                    @endforeach
                                @else
                                    <span class="text-muted">No teachers assigned</span>
                                @endif
                            </div>
                            @endif
                            @if(settings('show_timestamp', true))
                            <div class="col-md-6 text-end">
                                <small class="text-muted">Generated on: {{ now()->format('M d, Y \a\t h:i A') }}</small>
                            </div>
                            @endif
                        </div>
                    </div>
                </div>
            </div>
        </div>
        @endif

        <!-- Print Button -->
        <div class="row mt-4">
            <div class="col-12 text-center">
                <button onclick="printAnnualMasterList()" class="btn btn-success">
                    <i class="fas fa-print"></i> Print Annual Master List
                </button>
            </div>
        </div>
    @endif

    <!-- Calculation Help Modal -->
    <div class="modal fade help-modal" id="calculationHelpModal" tabindex="-1" aria-labelledby="calculationHelpModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header text-light">
                    <h5 class="modal-title text-light" id="calculationHelpModalLabel">Annual Master List Calculation Guide</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body help-modal-body">
                    <div class="row">
                        <div class="col-12">
                            <h6 class="text-primary">Subject-Level Calculations</h6>
                            <ul class="list-unstyled">
                                <li><strong>Subject Total:</strong> Sum of all session scores for that subject</li>
                                <li><strong>Subject Average:</strong> Subject Total ÷ Number of Sessions</li>
                            </ul>
                            
                            <h6 class="text-primary mt-4">Student-Level Calculations</h6>
                            <ul class="list-unstyled">
                                <li><strong>Annual Total:</strong> Sum of all subject totals across all sessions</li>
                                <li><strong>Maximum Annual Total:</strong> 100 × Number of Subjects × Number of Sessions</li>
                                <li><strong>Total Average:</strong> Sum of all subject averages<br>
                                    <small class="text-muted">Each subject average = (Sum of session scores for that subject ÷ Number of sessions)</small>
                                </li>
                                <li><strong>Maximum Total Average:</strong> 100 × Number of Subjects</li>
                                <li><strong>Annual Avg %:</strong> (Annual Total ÷ Maximum Annual Total) × 100</li>
                                <li><strong>Maximum Annual Avg %:</strong> 100%</li>
                            </ul>
                            
                            <h6 class="text-primary mt-4">Grade Distribution</h6>
                            <p>Shows count of A, B, C, D, E, F grades earned across all subjects and sessions for each student.</p>
                            
                            <h6 class="text-primary mt-4">Example Calculation</h6>
                            <div class="bg-light p-3 rounded">
                                <p><strong>Scenario:</strong> 3 subjects, 2 sessions</p>
                                <p><strong>Student scores:</strong></p>
                                <ul>
                                    <li>Math: Session 1(80), Session 2(85) → Total: 165, Average: 82.5</li>
                                    <li>English: Session 1(70), Session 2(75) → Total: 145, Average: 72.5</li>
                                    <li>Science: Session 1(90), Session 2(95) → Total: 185, Average: 92.5</li>
                                </ul>
                                <p><strong>Annual Calculations:</strong></p>
                                <ul>
                                    <li>Annual Total: 165 + 145 + 185 = 495 (Max: 600)</li>
                                    <li>Total Average: 82.5 + 72.5 + 92.5 = 247.5 (Max: 300)</li>
                                    <li>Annual Avg %: (495 ÷ 600) × 100 = 82.5%</li>
                                </ul>
                            </div>
                            
                            <h6 class="text-primary mt-4">Pass/Fail Determination</h6>
                            <p>Students pass if their Annual Avg % meets or exceeds the school's annual pass percentage (configurable in settings).</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('livewire:initialized', () => {
        Livewire.on('initMasterListChart', (data) => {
            setTimeout(() => {
                if (typeof initGradeChart === 'function') {
                    initGradeChart('masterListChart', data[0].labels, data[0].data, 'Class Performance');
                }
            }, 100);
        });
    });

    function printAnnualMasterList() {
        @this.call('getPrintUrl').then(url => {
            if (url) {
                window.open(url, '_blank', 'width=1200,height=800,scrollbars=yes,resizable=yes');
            }
        });
    }


</script>