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

@section('header-class', 'bg-gradient-to-r from-indigo-700 to-purple-700')
@section('footer-class', 'bg-gradient-to-r from-indigo-800 to-purple-900')
@section('header-dark', 'true')

@push('styles')
<style>
    /* Ensure embedded images from Quill editor render correctly */
    .prose img { max-width: 100%; height: auto; border-radius: 6px; }
    /* Ensure embedded iframes (YouTube/Vimeo) render correctly */
    .prose iframe { max-width: 100%; width: 100%; aspect-ratio: 16/9; border-radius: 8px; border: none; }
</style>
@endpush

@section('title', $subtopic->title . ' — ' . $course->title)
@section('course-title', $course->title)
@section('current-phase', '2')
@section('progress-percentage', $progressPercentage)
@section('has-sidebar')

@section('content')
{{-- ===================================================================
     PHASE 2 — TWO-COLUMN LAYOUT: Sidebar + Content Area
     The layout body has x-data="{ sidebarOpen: false }" from the portal layout.
=================================================================== --}}
<div class="flex h-[calc(100vh-3.5rem-0.25rem)] overflow-hidden" x-data="{
    sidebarOpen: window.innerWidth >= 768,
    progressPercentage: {{ $progressPercentage }},
    isRead: {{ $isRead ? 'true' : 'false' }},
    topicComplete: {{ $topic->isCompletedForEnrollment($enrollment->id) ? 'true' : 'false' }},
    allDone: {{ $allDone ? 'true' : 'false' }},
    isExamUnlocked: {{ $isExamUnlocked ? 'true' : 'false' }},
    elapsedSeconds: {{ $elapsedSeconds }},
    minTimeSeconds: {{ $minTimeSeconds }},
    remainingMinSeconds: Math.max(0, {{ $minTimeSeconds }} - {{ $elapsedSeconds }}),
    timerInterval: null,
    pingInterval: null,
    countdownInterval: null,
    markingRead: false,

    get formattedTimer() {
        let total = this.elapsedSeconds;
        let h = Math.floor(total / 3600);
        let m = Math.floor((total % 3600) / 60);
        let s = total % 60;
        if (h > 0) return h + 'h ' + m + 'm';
        if (m > 0) return m + 'm ' + s + 's';
        return s + 's';
    },

    get formattedCountdown() {
        let total = this.remainingMinSeconds;
        let m = Math.floor(total / 60);
        let s = total % 60;
        if (m > 0) return m + 'm ' + s + 's';
        return s + 's';
    },

    get canMarkAsRead() {
        return this.remainingMinSeconds <= 0;
    },

    startTimer() {
        // Increment elapsed seconds every second
        this.timerInterval = setInterval(() => {
            this.elapsedSeconds++;
            if (this.remainingMinSeconds > 0) {
                this.remainingMinSeconds--;
            }
        }, 1000);
        // Ping server every 30 seconds
        this.pingInterval  = setInterval(() => { this.pingTimer(); }, 30000);
        // Countdown every second
        this.countdownInterval = setInterval(() => {
            if (this.remainingMinSeconds <= 0) {
                clearInterval(this.countdownInterval);
            }
        }, 1000);
    },

    stopTimer() {
        clearInterval(this.timerInterval);
        clearInterval(this.pingInterval);
        clearInterval(this.countdownInterval);
    },

    async pingTimer() {
        try {
            await axios.post(
                '{{ route('api.self-paced.timer.ping', [$course, $topic]) }}',
                { seconds: 30, _token: '{{ csrf_token() }}' }
            );
        } catch(e) { /* silent */ }
    },

    async markRead() {
        if (this.isRead || this.markingRead || !this.canMarkAsRead) return;
        this.markingRead = true;
        try {
            const res = await axios.post(
                '{{ route('api.self-paced.mark-read', [$course, $subtopic]) }}',
                { _token: '{{ csrf_token() }}' }
            );
            if (res.data.success) {
                this.isRead             = true;
                this.progressPercentage = res.data.progress_percentage;
                this.topicComplete      = res.data.topic_complete;
                this.allDone            = res.data.all_done;
                this.isExamUnlocked     = res.data.is_exam_unlocked || this.allDone;
            }
        } catch(e) {
            console.error('Error marking as read:', e.response?.data?.message || e.message);
            alert('Error marking as read: ' + (e.response?.data?.message || 'Please try again'));
        } finally {
            this.markingRead = false;
        }
    }
}" x-init="startTimer()" @beforeunload.window="stopTimer()">

    {{-- =================================================================
         LEFT SIDEBAR — Course Navigation Tree
    ================================================================= --}}
    <aside
        class="flex-shrink-0 bg-white border-r border-gray-200 flex flex-col transition-all duration-300 overflow-hidden z-30"
        :class="sidebarOpen ? 'w-72' : 'w-0 md:w-12'"
        style="min-height: 0;">

        {{-- Sidebar Header --}}
        <div class="flex items-center justify-between px-3 py-3 border-b border-gray-100 flex-shrink-0"
             :class="sidebarOpen ? '' : 'md:flex-col md:gap-2'">
            <span class="text-xs font-semibold text-gray-500 uppercase tracking-wide whitespace-nowrap overflow-hidden"
                  :class="sidebarOpen ? 'block' : 'hidden md:hidden'">
                Course Content
            </span>
            <button @click="sidebarOpen = !sidebarOpen"
                    class="p-1.5 rounded-md text-gray-400 hover:text-indigo-600 hover:bg-indigo-50 transition flex-shrink-0"
                    :title="sidebarOpen ? 'Collapse sidebar' : 'Expand sidebar'">
                <i class="fas text-sm" :class="sidebarOpen ? 'fa-chevron-left' : 'fa-bars'"></i>
            </button>
        </div>

        {{-- Navigation Tree --}}
        <div class="flex-1 overflow-y-auto py-2" :class="sidebarOpen ? 'block' : 'hidden md:hidden'">
            @foreach($allTopics as $tIdx => $navTopic)
            @php
                $isActiveTopic = $navTopic->id === $topic->id;
            @endphp
            <div x-data="{ open: {{ $isActiveTopic ? 'true' : 'false' }} }" class="mb-0.5">

                {{-- Topic Row --}}
                <button @click="open = !open"
                        class="w-full flex items-center gap-2 px-3 py-2.5 text-left hover:bg-gray-50 transition group"
                        :class="{{ $isActiveTopic ? 'true' : 'false' }} ? 'bg-indigo-50/60' : ''">
                    @if(in_array($navTopic->id, $lockedTopicIds))
                    <span class="flex-shrink-0 w-5 h-5 rounded-full flex items-center justify-center text-xs text-gray-400 bg-gray-200"
                          title="Complete previous topics first">
                        <i class="fas fa-lock text-[8px]"></i>
                    </span>
                    @else
                    <span class="flex-shrink-0 w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-bold
                        @if($navTopic->is_completed) bg-green-500 text-white
                        @elseif($isActiveTopic) bg-indigo-600 text-white
                        @else bg-gray-200 text-gray-500 @endif">
                        @if($navTopic->is_completed)
                            <i class="fas fa-check text-[8px]"></i>
                        @else
                            {{ $tIdx + 1 }}
                        @endif
                    </span>
                    @endif
                    <span class="flex-1 text-xs font-medium truncate
                        @if($navTopic->is_completed) text-green-700
                        @elseif($isActiveTopic) text-indigo-700
                        @else text-gray-600 @endif">
                        {{ $navTopic->title }}
                    </span>
                    <i class="fas fa-chevron-down text-[10px] text-gray-300 transition-transform flex-shrink-0"
                       :class="open ? 'rotate-180' : ''"></i>
                </button>

                {{-- Subtopics --}}
                <div x-show="open"
                     x-transition:enter="transition ease-out duration-150"
                     x-transition:enter-start="opacity-0 -translate-y-1"
                     x-transition:enter-end="opacity-100 translate-y-0"
                     x-transition:leave="transition ease-in duration-100"
                     x-transition:leave-start="opacity-100 translate-y-0"
                     x-transition:leave-end="opacity-0 -translate-y-1"
                     class="pl-4 border-l-2 border-gray-100 ml-4">
                    @foreach($navTopic->subtopics->where('is_published', true) as $navSub)
                    @php $isActiveSub = $navSub->id === $subtopic->id; @endphp
                    @if(in_array($navTopic->id, $lockedTopicIds))
                    <div class="flex items-center gap-2 px-3 py-2 text-xs rounded-lg mx-1 my-0.5 text-gray-400 bg-gray-50 cursor-not-allowed"
                         title="Complete previous topics first">
                        <i class="fas fa-lock text-gray-400 flex-shrink-0 text-xs"></i>
                        <span class="truncate">{{ $navSub->title }}</span>
                    </div>
                    @else
                    <a href="{{ route('self-paced.learn.content.subtopic', [$course, $navSub->id]) }}"
                       class="flex items-center gap-2 px-3 py-2 text-xs rounded-lg mx-1 my-0.5 transition
                           @if($isActiveSub) bg-indigo-100 text-indigo-700 font-semibold
                           @elseif($navSub->is_read) text-green-700 hover:bg-green-50
                           @else text-gray-500 hover:bg-gray-50 @endif">
                        <span class="flex-shrink-0 w-4 h-4 rounded-full flex items-center justify-center
                            @if($navSub->is_read) bg-green-500
                            @elseif($isActiveSub) bg-indigo-600
                            @else bg-gray-200 @endif">
                            @if($navSub->is_read)
                                <i class="fas fa-check text-white text-[8px]"></i>
                            @elseif($isActiveSub)
                                <i class="fas fa-circle text-white text-[6px]"></i>
                            @endif
                        </span>
                        <span class="truncate">{{ $navSub->title }}</span>
                    </a>
                    @endif
                    @endforeach
                </div>
            </div>
            @endforeach
        </div>

        {{-- Sidebar Footer: Progress --}}
        <div class="border-t border-gray-100 px-3 py-3 flex-shrink-0" :class="sidebarOpen ? 'block' : 'hidden md:hidden'">
            <div class="flex items-center justify-between mb-1">
                <span class="text-xs text-gray-400">Progress</span>
                <span class="text-xs font-bold text-indigo-700" x-text="Math.round(progressPercentage) + '%'"></span>
            </div>
            <div class="w-full h-1.5 bg-gray-100 rounded-full overflow-hidden">
                <div class="h-full bg-indigo-500 rounded-full transition-all duration-500"
                     :style="'width: ' + Math.min(100, progressPercentage) + '%'"></div>
            </div>
        </div>
    </aside>

    {{-- =================================================================
         RIGHT CONTENT AREA
    ================================================================= --}}
    <div class="flex-1 flex flex-col overflow-hidden min-w-0">

        {{-- Content Scrollable Body --}}
        <div class="flex-1 overflow-y-auto">

            {{-- Hero Header Banner — full width, no padding wrapper --}}
            <div class="w-full bg-gradient-to-r from-indigo-700 via-purple-700 to-indigo-800 px-6 sm:px-8 lg:px-10 py-5">
                <nav class="flex items-center gap-1.5 text-xs text-indigo-200 mb-2 flex-wrap">
                    <a href="{{ route('self-paced.learn.overview', $course) }}"
                       class="hover:text-white transition">{{ $course->title }}</a>
                    <i class="fas fa-chevron-right text-[10px] text-indigo-400"></i>
                    <span class="text-indigo-300">{{ $topic->title }}</span>
                    <i class="fas fa-chevron-right text-[10px] text-indigo-400"></i>
                    <span class="text-white font-medium">{{ $subtopic->title }}</span>
                </nav>
                <div class="flex items-start justify-between gap-4">
                    <h1 class="text-xl sm:text-2xl font-bold text-white leading-tight">
                        {{ $subtopic->title }}
                    </h1>
                    {{-- Topic Timer Badge --}}
                    <div class="flex-shrink-0 flex items-center gap-1.5 bg-white/10 border border-white/20 rounded-lg px-3 py-1.5 text-xs font-medium text-white whitespace-nowrap">
                        <i class="fas fa-clock text-indigo-200"></i>
                        <span x-text="formattedTimer"></span>
                    </div>
                </div>
            </div>

            {{-- Content body with comfortable reading padding --}}
            <div class="w-full px-5 sm:px-8 lg:px-10 py-6 pb-32">

                {{-- Read Status Banner --}}
                <div x-show="isRead" x-transition
                     class="flex items-center gap-2 bg-green-50 border border-green-200 text-green-700 rounded-lg px-4 py-2.5 mb-5 text-sm">
                    <i class="fas fa-check-circle text-green-500"></i>
                    <span>You have completed this section.</span>
                </div>

                {{-- =====================================================
                     RICH HTML CONTENT
                ===================================================== --}}
                @if($subtopic->content)
                <div class="prose prose-sm sm:prose prose-full-width text-gray-700 leading-relaxed mb-8
                            prose-headings:text-gray-800 prose-a:text-indigo-600 prose-strong:text-gray-800
                            prose-img:rounded-lg prose-img:shadow-sm prose-pre:bg-gray-900 prose-code:text-indigo-600">
                    {!! $subtopic->content !!}
                </div>
                @else
                <div class="bg-gray-50 border border-dashed border-gray-200 rounded-xl p-8 text-center mb-8">
                    <i class="fas fa-file-alt text-3xl text-gray-300 mb-2 block"></i>
                    <p class="text-sm text-gray-400">No content available for this section yet.</p>
                </div>
                @endif

                {{-- =====================================================
                     INLINE MEDIA — video, image, pdf, presentation, excel
                ===================================================== --}}
                @if($subtopic->media->isNotEmpty())
                <div class="mb-8">
                    <h2 class="text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2">
                        <i class="fas fa-photo-video text-purple-500"></i>
                        Media Resources
                    </h2>
                    <div class="space-y-4">
                        @foreach($subtopic->media as $media)
                        <div class="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
                            @php
                                $mediaIconMap = [
                                    'video'        => ['fa-film',             'text-rose-500'],
                                    'image'        => ['fa-image',            'text-blue-500'],
                                    'pdf'          => ['fa-file-pdf',         'text-red-500'],
                                    'presentation' => ['fa-file-powerpoint',  'text-orange-500'],
                                    'excel'        => ['fa-file-excel',       'text-green-600'],
                                ];
                                [$mediaIcon, $mediaColor] = $mediaIconMap[$media->type] ?? ['fa-file', 'text-gray-400'];
                            @endphp
                            @if($media->title)
                            <div class="px-4 py-2.5 border-b border-gray-100 flex items-center gap-2">
                                <i class="fas {{ $mediaIcon }} {{ $mediaColor }} text-sm"></i>
                                <span class="text-sm font-medium text-gray-700">{{ $media->title }}</span>
                                <span class="ml-auto text-xs text-gray-400">{{ $media->getFormattedFileSize() }}</span>
                            </div>
                            @endif

                            <div class="p-4">
                                @if($media->type === 'video')
                                    {{-- HTML5 Video Player --}}
                                    <video controls
                                           class="w-full rounded-lg bg-black max-h-96"
                                           preload="metadata">
                                        <source src="{{ Storage::url($media->file_path) }}"
                                                type="{{ $media->mime_type ?? 'video/mp4' }}">
                                        <p class="text-sm text-gray-500 p-4">
                                            Your browser does not support the video tag.
                                            <a href="{{ Storage::url($media->file_path) }}"
                                               class="text-indigo-600 underline">Download video</a>
                                        </p>
                                    </video>

                                @elseif($media->type === 'image')
                                    {{-- Image with lightbox --}}
                                    <div x-data="{ lightbox: false }">
                                        <img src="{{ Storage::url($media->file_path) }}"
                                             alt="{{ $media->title ?? $media->file_name }}"
                                             class="w-full rounded-lg object-contain max-h-96 cursor-zoom-in hover:opacity-95 transition"
                                             @click="lightbox = true"
                                             loading="lazy">
                                        {{-- Lightbox overlay --}}
                                        <div x-show="lightbox"
                                             x-transition
                                             @click="lightbox = false"
                                             @keydown.escape.window="lightbox = false"
                                             class="fixed inset-0 bg-black/80 z-50 flex items-center justify-center p-4 cursor-zoom-out"
                                             x-cloak>
                                            <img src="{{ Storage::url($media->file_path) }}"
                                                 alt="{{ $media->title ?? $media->file_name }}"
                                                 class="max-w-full max-h-full rounded-lg shadow-2xl object-contain">
                                            <button @click.stop="lightbox = false"
                                                    class="absolute top-4 right-4 w-9 h-9 bg-white/20 hover:bg-white/30 rounded-full flex items-center justify-center text-white transition">
                                                <i class="fas fa-times"></i>
                                            </button>
                                        </div>
                                    </div>

                                @elseif($media->type === 'pdf')
                                    {{-- PDF Embed --}}
                                    <div class="rounded-lg overflow-hidden border border-gray-100">
                                        <iframe src="{{ Storage::url($media->file_path) }}#toolbar=1&navpanes=0"
                                                class="w-full"
                                                style="height: 500px;"
                                                title="{{ $media->title ?? $media->file_name }}">
                                        </iframe>
                                    </div>
                                    <a href="{{ Storage::url($media->file_path) }}"
                                       target="_blank"
                                       class="inline-flex items-center gap-1.5 mt-2 text-xs text-indigo-600 hover:text-indigo-800 font-medium transition">
                                        <i class="fas fa-external-link-alt"></i> Open PDF in new tab
                                    </a>

                                @else
                                    {{-- Presentation / Excel — download link --}}
                                    <div class="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
                                        <span class="w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0
                                            @if($media->type === 'presentation') bg-orange-100 @else bg-green-100 @endif">
                                            <i class="fas {{ $mediaIcon }} {{ $mediaColor }} text-lg"></i>
                                        </span>
                                        <div class="flex-1 min-w-0">
                                            <p class="text-sm font-medium text-gray-700 truncate">{{ $media->file_name }}</p>
                                            <p class="text-xs text-gray-400">{{ $media->getFormattedFileSize() }}</p>
                                        </div>
                                        <a href="{{ Storage::url($media->file_path) }}"
                                           download="{{ $media->file_name }}"
                                           class="flex-shrink-0 inline-flex items-center gap-1.5 px-3 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-medium rounded-lg transition">
                                            <i class="fas fa-download"></i> Download
                                        </a>
                                    </div>
                                @endif
                            </div>
                        </div>
                        @endforeach
                    </div>
                </div>
                @endif

                {{-- =====================================================
                     TOPIC DOWNLOADS
                ===================================================== --}}
                @php
                    $topicDownloads = $topic->downloads;
                @endphp
                @if($topicDownloads->isNotEmpty())
                <div class="mb-8">
                    <h2 class="text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2">
                        <i class="fas fa-download text-amber-500"></i>
                        Downloadable Resources
                    </h2>
                    <div class="bg-white rounded-xl border border-gray-100 shadow-sm divide-y divide-gray-50">
                        @foreach($topicDownloads as $download)
                        <div class="flex items-center gap-3 px-4 py-3">
                            <span class="w-8 h-8 bg-amber-100 rounded-lg flex items-center justify-center flex-shrink-0">
                                <i class="fas fa-file-download text-amber-600 text-sm"></i>
                            </span>
                            <div class="flex-1 min-w-0">
                                <p class="text-sm font-medium text-gray-700 truncate">{{ $download->title }}</p>
                                <p class="text-xs text-gray-400">{{ $download->file_name }} · {{ $download->getFormattedFileSize() }}</p>
                            </div>
                            <a href="{{ Storage::url($download->file_path) }}"
                               download="{{ $download->file_name }}"
                               class="flex-shrink-0 inline-flex items-center gap-1.5 px-3 py-1.5 bg-amber-50 hover:bg-amber-100 text-amber-700 text-xs font-medium rounded-lg border border-amber-200 transition">
                                <i class="fas fa-download text-xs"></i> Download
                            </a>
                        </div>
                        @endforeach
                    </div>
                </div>
                @endif

            </div>{{-- /content body --}}
        </div>{{-- /overflow-y-auto --}}

        {{-- =============================================================
             STICKY BOTTOM BAR — Mark as Read + Navigation
        ============================================================= --}}
        <div class="flex-shrink-0 bg-white border-t border-gray-200 shadow-[0_-2px_8px_rgba(0,0,0,0.06)]">
            <div class="w-full px-6 sm:px-8 py-3 flex flex-col sm:flex-row items-center gap-3">

                {{-- Mark as Read Button --}}
                <div class="flex-shrink-0 flex flex-col gap-1">
                    {{-- Minimum time countdown (if configured) --}}
                    @if($minTimeSeconds > 0)
                    <div class="text-xs text-center text-gray-500">
                        <span x-show="!canMarkAsRead" class="flex items-center justify-center gap-1">
                            <i class="fas fa-hourglass-end text-amber-500"></i>
                            Complete reading: <span x-text="formattedCountdown" class="font-semibold text-amber-600"></span>
                        </span>
                        <span x-show="canMarkAsRead" class="flex items-center justify-center gap-1 text-green-600">
                            <i class="fas fa-check-circle"></i>
                            Minimum time reached!
                        </span>
                    </div>
                    @endif

                    <button @click="markRead()"
                            :disabled="isRead || markingRead || !canMarkAsRead"
                            class="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-semibold transition"
                            :class="isRead
                                ? 'bg-green-100 text-green-700 cursor-default'
                                : (canMarkAsRead
                                    ? 'bg-indigo-600 hover:bg-indigo-700 text-white shadow-sm active:scale-95'
                                    : 'bg-gray-200 text-gray-400 cursor-not-allowed')">
                        <template x-if="isRead">
                            <span class="flex items-center gap-2">
                                <i class="fas fa-check-circle"></i> Completed
                            </span>
                        </template>
                        <template x-if="!isRead && !markingRead && canMarkAsRead">
                            <span class="flex items-center gap-2">
                                <i class="fas fa-check"></i> Mark as Read
                            </span>
                        </template>
                        <template x-if="!isRead && !markingRead && !canMarkAsRead">
                            <span class="flex items-center gap-2">
                                <i class="fas fa-lock"></i> Wait for timer
                            </span>
                        </template>
                        <template x-if="markingRead">
                            <span class="flex items-center gap-2">
                                <i class="fas fa-spinner fa-spin"></i> Saving...
                            </span>
                        </template>
                    </button>
                </div>

                {{-- Spacer --}}
                <div class="flex-1"></div>

                {{-- Navigation Buttons --}}
                <div class="flex items-center gap-2">

                    {{-- Previous --}}
                    @php
                        // Resolve previous subtopic
                        $prevSubtopic = \App\Models\SelfPaced\CourseSubTopic::where('topic_id', $subtopic->topic_id)
                            ->where('is_published', true)
                            ->where('sort_order', '<', $subtopic->sort_order)
                            ->orderByDesc('sort_order')
                            ->first();

                        if (!$prevSubtopic) {
                            // First subtopic of previous topic
                            $prevTopic = \App\Models\SelfPaced\CourseTopic::where('course_id', $course->id)
                                ->where('is_published', true)
                                ->where('sort_order', '<', $topic->sort_order)
                                ->orderByDesc('sort_order')
                                ->first();
                            $prevSubtopic = $prevTopic
                                ? $prevTopic->subtopics()->where('is_published', true)->orderByDesc('sort_order')->first()
                                : null;
                        }
                    @endphp

                    @if($prevSubtopic)
                    <a href="{{ route('self-paced.learn.content.subtopic', [$course, $prevSubtopic->id]) }}"
                       class="inline-flex items-center gap-1.5 px-3 py-2 bg-gray-100 hover:bg-gray-200 text-gray-600 text-sm font-medium rounded-lg transition">
                        <i class="fas fa-arrow-left text-xs"></i>
                        <span class="hidden sm:inline">Previous</span>
                    </a>
                    @else
                    <a href="{{ route('self-paced.learn.overview', $course) }}"
                       class="inline-flex items-center gap-1.5 px-3 py-2 bg-gray-100 hover:bg-gray-200 text-gray-600 text-sm font-medium rounded-lg transition">
                        <i class="fas fa-arrow-left text-xs"></i>
                        <span class="hidden sm:inline">Overview</span>
                    </a>
                    @endif

                    {{-- Next / Proceed to Exam --}}
                    <template x-if="!allDone">
                        @if($nextSubtopic)
                        <a href="{{ route('self-paced.learn.content.subtopic', [$course, $nextSubtopic->id]) }}"
                           class="inline-flex items-center gap-1.5 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-semibold rounded-lg transition shadow-sm">
                            <span>Next</span>
                            <i class="fas fa-arrow-right text-xs"></i>
                        </a>
                        @else
                        {{-- Last subtopic — all content read but allDone not yet true (progress < 100%) --}}
                        <span class="inline-flex items-center gap-1.5 px-4 py-2 bg-gray-200 text-gray-400 text-sm font-semibold rounded-lg cursor-not-allowed"
                              title="Mark this section as read to complete the course">
                            <span>Next</span>
                            <i class="fas fa-arrow-right text-xs"></i>
                        </span>
                        @endif
                    </template>

                    <template x-if="allDone && isExamUnlocked">
                        <a href="{{ route('self-paced.learn.exam.confirm', $course) }}"
                           class="inline-flex items-center gap-2 px-4 py-2 bg-green-600 hover:bg-green-700 text-white text-sm font-bold rounded-lg transition shadow-sm animate-pulse">
                            <i class="fas fa-clipboard-question"></i>
                            Proceed to Exam
                            <i class="fas fa-arrow-right text-xs"></i>
                        </a>
                    </template>

                    <template x-if="allDone && !isExamUnlocked">
                        <div class="inline-flex items-center gap-2 px-4 py-2 bg-blue-100 text-blue-700 text-sm font-semibold rounded-lg">
                            <i class="fas fa-spinner fa-spin"></i>
                            Exam Unlocking...
                        </div>
                    </template>

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

    </div>{{-- /right content area --}}
</div>{{-- /flex container --}}
@endsection

@push('scripts')
<script>
    // Axios CSRF header is already set globally via bootstrap.js
</script>
@endpush
