@extends('layouts.self-paced-portal')

@section('title', 'Exam Results — ' . $course->title)
@section('course-title', $course->title)
@section('current-phase', '4')
@section('progress-percentage', $progressPercentage)

@section('content')
<div class="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-10"
     x-data="resultsPage()"
     x-cloak>

    {{-- ===================================================================
         RESULT HERO — PASS or FAIL
    =================================================================== --}}
    <div class="text-center mb-8">
        @if($result->passed)
            <div class="inline-flex items-center justify-center w-20 h-20 bg-green-100 rounded-full mb-4 ring-4 ring-green-200">
                <i class="fas fa-trophy text-green-500 text-3xl"></i>
            </div>
            <div class="inline-flex items-center gap-2 px-5 py-2 bg-green-100 text-green-700 rounded-full text-sm font-bold mb-3">
                <i class="fas fa-check-circle"></i> PASSED
            </div>
            <h1 class="text-4xl font-extrabold text-green-600 mb-1">
                {{ number_format((float) $result->score_percentage, 1) }}%
            </h1>
            <p class="text-gray-500 text-sm">
                {{ $result->correct_answers }} out of {{ $result->total_questions }} correct
            </p>
            <p class="text-green-700 font-semibold mt-2">
                Congratulations! You have successfully passed the exam.
            </p>
        @else
            <div class="inline-flex items-center justify-center w-20 h-20 bg-red-100 rounded-full mb-4 ring-4 ring-red-200">
                <i class="fas fa-times-circle text-red-400 text-3xl"></i>
            </div>
            <div class="inline-flex items-center gap-2 px-5 py-2 bg-red-100 text-red-700 rounded-full text-sm font-bold mb-3">
                <i class="fas fa-times-circle"></i> FAILED
            </div>
            <h1 class="text-4xl font-extrabold text-red-500 mb-1">
                {{ number_format((float) $result->score_percentage, 1) }}%
            </h1>
            <p class="text-gray-500 text-sm">
                {{ $result->correct_answers }} out of {{ $result->total_questions }} correct
            </p>
            <p class="text-gray-600 mt-2">
                Keep going — review the material and try again.
            </p>
        @endif
    </div>

    {{-- ===================================================================
         SCORE BREAKDOWN CARD
    =================================================================== --}}
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-6 mb-5">
        <h2 class="text-sm font-semibold text-gray-700 mb-4 flex items-center gap-2">
            <i class="fas fa-chart-bar text-indigo-400"></i> Score Breakdown
        </h2>
        <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
            <div class="flex flex-col items-center p-3 bg-indigo-50 rounded-xl">
                <span class="text-2xl font-bold text-indigo-700">{{ $result->total_questions }}</span>
                <span class="text-xs text-gray-500 mt-1">Total Questions</span>
            </div>
            <div class="flex flex-col items-center p-3 bg-green-50 rounded-xl">
                <span class="text-2xl font-bold text-green-700">{{ $result->correct_answers }}</span>
                <span class="text-xs text-gray-500 mt-1">Correct</span>
            </div>
            <div class="flex flex-col items-center p-3 {{ $result->passed ? 'bg-green-50' : 'bg-red-50' }} rounded-xl">
                <span class="text-2xl font-bold {{ $result->passed ? 'text-green-700' : 'text-red-600' }}">
                    {{ number_format((float) $result->score_percentage, 1) }}%
                </span>
                <span class="text-xs text-gray-500 mt-1">Your Score</span>
            </div>
            <div class="flex flex-col items-center p-3 bg-amber-50 rounded-xl">
                <span class="text-2xl font-bold text-amber-700">{{ $result->passing_threshold }}%</span>
                <span class="text-xs text-gray-500 mt-1">Pass Mark</span>
            </div>
        </div>

        {{-- Score progress bar --}}
        <div class="mt-5">
            <div class="flex items-center justify-between text-xs text-gray-500 mb-1">
                <span>0%</span>
                <span class="font-medium {{ $result->passed ? 'text-green-600' : 'text-red-500' }}">
                    Your score: {{ number_format((float) $result->score_percentage, 1) }}%
                </span>
                <span>100%</span>
            </div>
            <div class="relative w-full h-3 bg-gray-100 rounded-full overflow-hidden">
                {{-- Pass threshold marker --}}
                <div class="absolute top-0 bottom-0 w-0.5 bg-amber-400 z-10"
                     style="left: {{ $result->passing_threshold }}%"
                     title="Pass mark: {{ $result->passing_threshold }}%"></div>
                {{-- Score bar --}}
                <div class="h-full rounded-full transition-all duration-700 {{ $result->passed ? 'bg-gradient-to-r from-green-400 to-green-600' : 'bg-gradient-to-r from-red-400 to-red-500' }}"
                     style="width: {{ min(100, (float) $result->score_percentage) }}%"></div>
            </div>
            <div class="flex items-center gap-3 mt-2 text-xs text-gray-400">
                <span class="flex items-center gap-1">
                    <span class="w-2.5 h-2.5 rounded-full bg-amber-400 inline-block"></span>
                    Pass mark ({{ $result->passing_threshold }}%)
                </span>
                <span class="flex items-center gap-1">
                    <span class="w-2.5 h-2.5 rounded-full {{ $result->passed ? 'bg-green-500' : 'bg-red-400' }} inline-block"></span>
                    Your score ({{ number_format((float) $result->score_percentage, 1) }}%)
                </span>
            </div>
        </div>
    </div>

    {{-- ===================================================================
         ACTION BUTTONS — PASS scenario
    =================================================================== --}}
    @if($result->passed)
    <div class="bg-green-50 border border-green-200 rounded-2xl p-6 mb-5">
        <div class="flex items-center gap-3 mb-4">
            <span class="w-10 h-10 bg-green-100 rounded-xl flex items-center justify-center flex-shrink-0">
                <i class="fas fa-award text-green-600"></i>
            </span>
            <div>
                <p class="font-semibold text-green-800 text-sm">You earned a certificate!</p>
                <p class="text-xs text-green-600">Download your certificate and result slip below.</p>
            </div>
        </div>
        <div class="flex flex-col sm:flex-row gap-3">
            {{-- Result Slip (always free) --}}
            <a href="{{ route('self-paced.learn.results.slip', [$course, $result]) }}"
               class="flex-1 flex items-center justify-center gap-2 px-5 py-3 bg-white hover:bg-gray-50 text-gray-700 font-semibold text-sm rounded-xl border border-gray-200 transition active:scale-95">
                <i class="fas fa-file-pdf text-red-500"></i>
                Download Result Slip
            </a>

            {{-- Certificate download or payment --}}
            @if($certificateFee > 0 && !$certificateFeePaid)
                {{-- Certificate requires payment --}}
                <button type="button"
                        @click="showCertificatePaymentModal = true"
                        class="flex-1 flex items-center justify-center gap-2 px-5 py-3 bg-green-600 hover:bg-green-700 text-white font-semibold text-sm rounded-xl transition shadow-md shadow-green-200 active:scale-95">
                    <i class="fas fa-lock text-xs"></i>
                    Pay {{ $paystackConfig->supportsCurrency('USD') ? 'USD ' : 'KES ' }}{{ number_format($certificateFee, 2) }} to Download
                </button>
            @else
                {{-- Certificate is free or already paid --}}
                @if($certificateCollectionMode === 'hardcopy')
                    <div class="flex-1 flex items-center justify-center gap-2 px-5 py-3 bg-amber-100 border border-amber-300 text-amber-800 font-semibold text-sm rounded-xl">
                        <i class="fas fa-building"></i>
                        Visit Institution to Collect
                    </div>
                @else
                    <a href="{{ route('self-paced.learn.results.certificate', [$course, $result]) }}"
                       class="flex-1 flex items-center justify-center gap-2 px-5 py-3 bg-green-600 hover:bg-green-700 text-white font-semibold text-sm rounded-xl transition shadow-md shadow-green-200 active:scale-95">
                        <i class="fas fa-certificate"></i>
                        Download Certificate
                    </a>
                @endif
            @endif
        </div>
    </div>

    {{-- Certificate Payment Modal --}}
    @if($certificateFee > 0 && !$certificateFeePaid)
    <div x-show="showCertificatePaymentModal"
         x-cloak
         @keydown.escape="showCertificatePaymentModal = false"
         class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
        <div class="bg-white rounded-2xl shadow-xl max-w-md w-full p-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-bold text-gray-800">Download Certificate</h3>
                <button type="button"
                        @click="showCertificatePaymentModal = false"
                        class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-lg"></i>
                </button>
            </div>

            <p class="text-sm text-gray-600 mb-4">
                A certificate fee is required to download your certificate.
            </p>

            <div class="bg-indigo-50 border border-indigo-200 rounded-lg p-4 mb-5">
                <div class="flex items-center justify-between">
                    <span class="text-sm font-medium text-gray-700">Certificate Fee:</span>
                    <span class="text-lg font-bold text-indigo-700">KES {{ number_format($certificateFee, 2) }}</span>
                </div>
            </div>

            <div class="space-y-2 mb-5">
                @if($course->acceptsOnlinePayment())
                <button type="button"
                        @click="proceedCertificatePayment()"
                        class="w-full flex items-center justify-center gap-2 px-4 py-3 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold text-sm rounded-lg transition">
                    <i class="fas fa-credit-card"></i>
                    Pay with Paystack
                </button>
                @endif

                @if($course->acceptsCashPayment())
                <button type="button"
                        @click="showCertificateProofForm = true"
                        class="w-full flex items-center justify-center gap-2 px-4 py-3 bg-white hover:bg-gray-50 text-gray-700 font-semibold text-sm rounded-lg border border-gray-200 transition">
                    <i class="fas fa-money-bill"></i>
                    Pay with Cash Proof
                </button>
                @endif
            </div>

            <button type="button"
                    @click="showCertificatePaymentModal = false"
                    class="w-full px-4 py-2 text-sm text-gray-600 hover:text-gray-800 transition">
                Cancel
            </button>
        </div>
    </div>

    {{-- Certificate Cash Proof Form --}}
    <div x-show="showCertificateProofForm"
         x-cloak
         @keydown.escape="showCertificateProofForm = false"
         class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
        <div class="bg-white rounded-2xl shadow-xl max-w-md w-full p-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-bold text-gray-800">Upload Payment Proof</h3>
                <button type="button"
                        @click="showCertificateProofForm = false"
                        class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-lg"></i>
                </button>
            </div>

            <form method="POST" action="{{ route('self-paced.learn.certificate.proof', $course) }}" enctype="multipart/form-data" class="space-y-4">
                @csrf

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Proof Type</label>
                    <select name="proof_type" required class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500">
                        <option value="">-- Select Proof Type --</option>
                        <option value="mpesa">M-Pesa Screenshot</option>
                        <option value="bank_slip">Bank Slip</option>
                        <option value="institution_receipt">Institution Receipt</option>
                    </select>
                    @error('proof_type')
                    <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Upload Proof (JPEG, PNG, or PDF)</label>
                    <input type="file" name="file" required accept=".jpg,.jpeg,.png,.pdf" class="w-full text-sm" />
                    <p class="text-xs text-gray-500 mt-1">Max 5 MB</p>
                    @error('file')
                    <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div class="bg-amber-50 border border-amber-200 rounded-lg p-3">
                    <p class="text-xs text-amber-800">
                        <i class="fas fa-info-circle mr-1"></i>
                        Your proof will be reviewed by an administrator. You'll receive email confirmation once approved.
                    </p>
                </div>

                <div class="flex gap-3">
                    <button type="submit" class="flex-1 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold text-sm rounded-lg transition">
                        Submit
                    </button>
                    <button type="button"
                            @click="showCertificateProofForm = false"
                            class="flex-1 px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 font-semibold text-sm rounded-lg transition">
                        Cancel
                    </button>
                </div>
            </form>
        </div>
    </div>
    @endif
    @endif

    {{-- ===================================================================
         ACTION BUTTONS — FAIL scenario
    =================================================================== --}}
    @if(!$result->passed)
    <div class="bg-white border border-gray-100 rounded-2xl shadow-sm p-6 mb-5">
        <div class="flex items-center gap-3 mb-4">
            <span class="w-10 h-10 bg-amber-100 rounded-xl flex items-center justify-center flex-shrink-0">
                <i class="fas fa-redo text-amber-600"></i>
            </span>
            <div>
                <p class="font-semibold text-gray-800 text-sm">Want to try again?</p>
                <p class="text-xs text-gray-500">
                    You need {{ $result->passing_threshold }}% to pass.
                    You scored {{ number_format((float) $result->score_percentage, 1) }}%.
                </p>
            </div>
        </div>

        {{-- Attempt tracking --}}
        @if($remainingAttempts > 0 || $isExamExhausted)
        <div class="flex items-center gap-2 px-4 py-3 bg-gray-50 rounded-lg mb-4 text-sm">
            <i class="fas fa-info-circle text-gray-400"></i>
            <span class="text-gray-700">
                @if($isExamExhausted)
                    <strong>All exam attempts used.</strong> You must pay the re-sit fee to continue.
                @else
                    <strong>Attempts remaining: {{ $remainingAttempts }}</strong>
                @endif
            </span>
        </div>
        @endif

        {{-- Action buttons based on remaining attempts and exhaustion --}}
        <div class="flex flex-col sm:flex-row gap-3">
            @if($remainingAttempts > 0 && !$isExamExhausted)
                {{-- User can retry for free --}}
                <a href="{{ route('self-paced.learn.exam.confirm', $course) }}"
                   class="flex-1 flex items-center justify-center gap-2 px-5 py-3 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold text-sm rounded-xl transition shadow-md shadow-indigo-200 active:scale-95">
                    <i class="fas fa-redo"></i>
                    Retry Exam
                    <span class="text-xs opacity-70">({{ $remainingAttempts }} left)</span>
                </a>
            @elseif($isExamExhausted)
                {{-- User has exhausted attempts, needs to pay re-sit fee or retry for free if no fee --}}
                @if($examFailureFee > 0)
                    {{-- Re-sit fee required --}}
                    <button type="button"
                            @click="showResitPaymentModal = true"
                            class="flex-1 flex items-center justify-center gap-2 px-5 py-3 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold text-sm rounded-xl transition shadow-md shadow-indigo-200 active:scale-95">
                        <i class="fas fa-lock text-xs"></i>
                        Pay KES {{ number_format($examFailureFee, 2) }} for Re-sit
                    </button>
                @else
                    {{-- Re-sit fee is free --}}
                    <a href="{{ route('self-paced.learn.exam.confirm', $course) }}"
                       class="flex-1 flex items-center justify-center gap-2 px-5 py-3 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold text-sm rounded-xl transition shadow-md shadow-indigo-200 active:scale-95">
                        <i class="fas fa-redo"></i>
                        Re-study and Retry
                    </a>
                @endif
            @else
                {{-- No attempts left and no re-sit option available --}}
                <div class="flex-1 flex items-center justify-center gap-2 px-5 py-3 bg-gray-100 text-gray-400 font-semibold text-sm rounded-xl cursor-not-allowed">
                    <i class="fas fa-ban"></i>
                    No Retakes Remaining
                </div>
            @endif

            {{-- Result slip (always available) --}}
            <a href="{{ route('self-paced.learn.results.slip', [$course, $result]) }}"
               class="flex-1 flex items-center justify-center gap-2 px-5 py-3 bg-white hover:bg-gray-50 text-gray-700 font-semibold text-sm rounded-xl border border-gray-200 transition active:scale-95">
                <i class="fas fa-file-pdf text-red-500"></i>
                Download Result Slip
            </a>
        </div>

        @if($remainingAttempts === 0 && !$isExamExhausted)
        <p class="text-xs text-gray-400 text-center mt-3">
            You have used {{ $course->max_exam_attempts }} out of {{ $course->max_exam_attempts }} allowed attempts for this course.
        </p>
        @endif
    </div>

    {{-- Re-sit Payment Modal --}}
    @if($examFailureFee > 0 && $isExamExhausted)
    <div x-show="showResitPaymentModal"
         x-cloak
         @keydown.escape="showResitPaymentModal = false"
         class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
        <div class="bg-white rounded-2xl shadow-xl max-w-md w-full p-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-bold text-gray-800">Exam Re-sit Fee</h3>
                <button type="button"
                        @click="showResitPaymentModal = false"
                        class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-lg"></i>
                </button>
            </div>

            <p class="text-sm text-gray-600 mb-4">
                To re-attempt this exam after using all allowed attempts, you need to pay the re-sit fee.
            </p>

            <div class="bg-indigo-50 border border-indigo-200 rounded-lg p-4 mb-5">
                <div class="flex items-center justify-between">
                    <span class="text-sm font-medium text-gray-700">Re-sit Fee:</span>
                    <span class="text-lg font-bold text-indigo-700">KES {{ number_format($examFailureFee, 2) }}</span>
                </div>
            </div>

            <div class="space-y-2 mb-5">
                @if($course->acceptsOnlinePayment())
                <button type="button"
                        @click="proceedResitPayment()"
                        class="w-full flex items-center justify-center gap-2 px-4 py-3 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold text-sm rounded-lg transition">
                    <i class="fas fa-credit-card"></i>
                    Pay with Paystack
                </button>
                @endif

                @if($course->acceptsCashPayment())
                <button type="button"
                        @click="showResitProofForm = true"
                        class="w-full flex items-center justify-center gap-2 px-4 py-3 bg-white hover:bg-gray-50 text-gray-700 font-semibold text-sm rounded-lg border border-gray-200 transition">
                    <i class="fas fa-money-bill"></i>
                    Pay with Cash Proof
                </button>
                @endif
            </div>

            <button type="button"
                    @click="showResitPaymentModal = false"
                    class="w-full px-4 py-2 text-sm text-gray-600 hover:text-gray-800 transition">
                Cancel
            </button>
        </div>
    </div>

    {{-- Re-sit Cash Proof Form --}}
    <div x-show="showResitProofForm"
         x-cloak
         @keydown.escape="showResitProofForm = false"
         class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
        <div class="bg-white rounded-2xl shadow-xl max-w-md w-full p-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-bold text-gray-800">Upload Payment Proof</h3>
                <button type="button"
                        @click="showResitProofForm = false"
                        class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-lg"></i>
                </button>
            </div>

            <form method="POST" action="{{ route('self-paced.learn.resit.proof', $course) }}" enctype="multipart/form-data" class="space-y-4">
                @csrf

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Proof Type</label>
                    <select name="proof_type" required class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500">
                        <option value="">-- Select Proof Type --</option>
                        <option value="mpesa">M-Pesa Screenshot</option>
                        <option value="bank_slip">Bank Slip</option>
                        <option value="institution_receipt">Institution Receipt</option>
                    </select>
                    @error('proof_type')
                    <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Upload Proof (JPEG, PNG, or PDF)</label>
                    <input type="file" name="file" required accept=".jpg,.jpeg,.png,.pdf" class="w-full text-sm" />
                    <p class="text-xs text-gray-500 mt-1">Max 5 MB</p>
                    @error('file')
                    <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <div class="bg-amber-50 border border-amber-200 rounded-lg p-3">
                    <p class="text-xs text-amber-800">
                        <i class="fas fa-info-circle mr-1"></i>
                        Your proof will be reviewed by an administrator. You'll receive email confirmation once approved.
                    </p>
                </div>

                <div class="flex gap-3">
                    <button type="submit" class="flex-1 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold text-sm rounded-lg transition">
                        Submit
                    </button>
                    <button type="button"
                            @click="showResitProofForm = false"
                            class="flex-1 px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 font-semibold text-sm rounded-lg transition">
                        Cancel
                    </button>
                </div>
            </form>
        </div>
    </div>
    @endif
    @endif

    {{-- ===================================================================
         PER-TOPIC BREAKDOWN
    =================================================================== --}}
    @if(!empty($result->topic_scores))
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-6 mb-5">
        <h2 class="text-sm font-semibold text-gray-700 mb-4 flex items-center gap-2">
            <i class="fas fa-bookmark text-indigo-400"></i> Performance by Topic
        </h2>
        <div class="overflow-x-auto">
            <table class="w-full text-sm border-collapse">
                <thead>
                    <tr class="bg-gray-50">
                        <th class="text-left px-4 py-2.5 text-xs font-semibold text-gray-500 uppercase tracking-wide border-b border-gray-100">Topic</th>
                        <th class="text-center px-4 py-2.5 text-xs font-semibold text-gray-500 uppercase tracking-wide border-b border-gray-100">Questions</th>
                        <th class="text-center px-4 py-2.5 text-xs font-semibold text-gray-500 uppercase tracking-wide border-b border-gray-100">Correct</th>
                        <th class="text-center px-4 py-2.5 text-xs font-semibold text-gray-500 uppercase tracking-wide border-b border-gray-100">Score</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-50">
                    @foreach($result->topic_scores as $ts)
                    <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                        <td class="px-4 py-3 text-sm text-gray-700 font-medium">{{ $ts['topic_title'] }}</td>
                        <td class="px-4 py-3 text-sm text-gray-600 text-center">{{ $ts['total_questions'] }}</td>
                        <td class="px-4 py-3 text-sm text-gray-600 text-center">{{ $ts['correct_answers'] }}</td>
                        <td class="px-4 py-3 text-center">
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-bold
                                {{ $ts['score_percentage'] >= $result->passing_threshold ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700' }}">
                                {{ number_format($ts['score_percentage'], 1) }}%
                            </span>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
    @endif

    {{-- ===================================================================
         INCORRECT ANSWERS REVIEW — collapsible
    =================================================================== --}}
    @if(count($incorrectAnswers) > 0)
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm mb-5"
         x-data="{ open: false }">
        <button @click="open = !open"
                class="w-full flex items-center justify-between px-6 py-4 text-left hover:bg-gray-50 rounded-2xl transition">
            <span class="flex items-center gap-2 font-semibold text-gray-700 text-sm">
                <i class="fas fa-magnifying-glass text-rose-400"></i>
                Review Incorrect Answers
                <span class="ml-1 px-2 py-0.5 bg-rose-100 text-rose-600 text-xs rounded-full font-bold">
                    {{ count($incorrectAnswers) }}
                </span>
            </span>
            <i class="fas text-gray-400 text-sm transition-transform duration-200"
               :class="open ? 'fa-chevron-up' : 'fa-chevron-down'"></i>
        </button>

        <div x-show="open" x-transition x-cloak class="px-6 pb-6">
            <div class="space-y-4">
                @foreach($incorrectAnswers as $index => $item)
                @php
                    /** @var \App\Models\SelfPaced\ExamQuestion $question */
                    $question = $item['question'];
                    $selected = $item['selected'];
                    $correct  = $item['correct'];
                @endphp
                <div class="border border-gray-100 rounded-xl p-4 bg-gray-50">
                    {{-- Question --}}
                    <p class="text-sm font-medium text-gray-800 mb-3">
                        <span class="inline-flex items-center justify-center w-5 h-5 bg-rose-100 text-rose-600 rounded-full text-xs font-bold mr-1.5">
                            {{ $index + 1 }}
                        </span>
                        {{ $question->question_text }}
                    </p>

                    {{-- Options --}}
                    <div class="space-y-1.5 mb-3">
                        @foreach(['A', 'B', 'C', 'D'] as $letter)
                        @php
                            $optionText = $question->getOptionText($letter);
                            $isCorrect  = $letter === $correct;
                            $isSelected = $letter === $selected;
                        @endphp
                        <div class="flex items-start gap-2 px-3 py-2 rounded-lg text-sm
                            {{ $isCorrect ? 'bg-green-50 border border-green-200' : ($isSelected && !$isCorrect ? 'bg-red-50 border border-red-200' : 'bg-white border border-gray-100') }}">
                            <span class="flex-shrink-0 w-5 h-5 rounded-full flex items-center justify-center text-xs font-bold mt-0.5
                                {{ $isCorrect ? 'bg-green-500 text-white' : ($isSelected && !$isCorrect ? 'bg-red-400 text-white' : 'bg-gray-200 text-gray-500') }}">
                                {{ $letter }}
                            </span>
                            <span class="{{ $isCorrect ? 'text-green-800 font-medium' : ($isSelected && !$isCorrect ? 'text-red-700' : 'text-gray-600') }}">
                                {{ $optionText }}
                            </span>
                            @if($isCorrect)
                                <span class="ml-auto flex-shrink-0 text-xs text-green-600 font-semibold flex items-center gap-1">
                                    <i class="fas fa-check"></i> Correct
                                </span>
                            @elseif($isSelected && !$isCorrect)
                                <span class="ml-auto flex-shrink-0 text-xs text-red-500 font-semibold flex items-center gap-1">
                                    <i class="fas fa-times"></i> Your answer
                                </span>
                            @endif
                        </div>
                        @endforeach
                    </div>

                    {{-- Unanswered notice --}}
                    @if(!$selected)
                    <div class="flex items-center gap-1.5 text-xs text-amber-600 mb-2">
                        <i class="fas fa-exclamation-triangle"></i>
                        You did not answer this question.
                    </div>
                    @endif

                    {{-- Explanation --}}
                    @if($question->explanation)
                    <div class="flex items-start gap-2 bg-blue-50 border border-blue-100 rounded-lg px-3 py-2 text-xs text-blue-800">
                        <i class="fas fa-lightbulb text-blue-400 mt-0.5 flex-shrink-0"></i>
                        <span>{{ $question->explanation }}</span>
                    </div>
                    @endif
                </div>
                @endforeach
            </div>
        </div>
    </div>
    @else
    {{-- All correct --}}
    @if($result->passed && $result->correct_answers === $result->total_questions)
    <div class="bg-green-50 border border-green-200 rounded-xl p-4 mb-5 flex items-center gap-3">
        <i class="fas fa-star text-green-500 text-lg"></i>
        <p class="text-sm text-green-800 font-medium">Perfect score! You answered every question correctly.</p>
    </div>
    @endif
    @endif

    {{-- ===================================================================
         FOOTER NAVIGATION
    =================================================================== --}}
    <div class="flex items-center justify-between pt-2">
        <a href="{{ route('self-paced.learn.overview', $course) }}"
           class="inline-flex items-center gap-1.5 text-sm text-gray-500 hover:text-indigo-600 transition">
            <i class="fas fa-arrow-left text-xs"></i>
            Back to Course Overview
        </a>
        <a href="{{ route('self-paced.public.index') }}"
           class="inline-flex items-center gap-1.5 text-sm text-gray-500 hover:text-indigo-600 transition">
            Browse More Courses
            <i class="fas fa-arrow-right text-xs"></i>
        </a>
    </div>

</div>

<script>
function resultsPage() {
    return {
        showCertificatePaymentModal: false,
        showCertificateProofForm: false,
        showResitPaymentModal: false,
        showResitProofForm: false,
        isProcessing: false,

        async proceedCertificatePayment() {
            this.isProcessing = true;
            try {
                const response = await fetch('{{ route("self-paced.learn.certificate.init", $course) }}', {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content,
                        'Content-Type': 'application/json'
                    }
                });

                if (!response.ok) throw new Error('Failed to initialize payment');

                const data = await response.json();
                
                if (!data.paystack_config) {
                    alert('Failed to load payment configuration');
                    return;
                }

                PaystackPop.setup(data.paystack_config);
                PaystackPop.openIframe();
            } catch (error) {
                console.error('Certificate payment error:', error);
                alert('An error occurred. Please try again.');
            } finally {
                this.isProcessing = false;
            }
        },

        async proceedResitPayment() {
            this.isProcessing = true;
            try {
                const response = await fetch('{{ route("self-paced.learn.resit.init", $course) }}', {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content,
                        'Content-Type': 'application/json'
                    }
                });

                if (!response.ok) throw new Error('Failed to initialize payment');

                const data = await response.json();
                
                if (!data.paystack_config) {
                    alert('Failed to load payment configuration');
                    return;
                }

                PaystackPop.setup(data.paystack_config);
                PaystackPop.openIframe();
            } catch (error) {
                console.error('Resit payment error:', error);
                alert('An error occurred. Please try again.');
            } finally {
                this.isProcessing = false;
            }
        }
    };
}
</script>
@endsection
