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

@section('title', $course->title . ' — Overview')
@section('course-title', $course->title)
@section('current-phase', '1')
@section('progress-percentage', $progressPercentage)

@section('content')

{{-- Flash error / warning banners --}}
@if(session('error'))
<div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 pt-4">
    <div class="flex items-start gap-3 bg-red-50 border border-red-200 text-red-800 rounded-xl px-4 py-3 text-sm">
        <i class="fas fa-exclamation-circle text-red-500 mt-0.5 flex-shrink-0"></i>
        <span>{{ session('error') }}</span>
    </div>
</div>
@endif
@if(session('warning'))
<div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 pt-4">
    <div class="flex items-start gap-3 bg-amber-50 border border-amber-200 text-amber-800 rounded-xl px-4 py-3 text-sm">
        <i class="fas fa-exclamation-triangle text-amber-500 mt-0.5 flex-shrink-0"></i>
        <span>{{ session('warning') }}</span>
    </div>
</div>
@endif

{{-- ===================================================================
     HERO HEADER — Full-width, zero-gap, flat corners (Req 2.1, 2.2, 2.3)
=================================================================== --}}
<div class="w-full relative overflow-hidden" style="border-radius:0; margin-top:0; padding-top:0;">
    @php
        $heroStatCards = [
            ['icon' => 'fas fa-clock',     'color' => 'bg-sky-400/30',    'value' => ($course->duration_hours > 0 ? $course->duration_hours . 'h' : '—'), 'label' => 'Duration'],
            ['icon' => 'fas fa-money-bill', 'color' => 'bg-amber-400/30',  'value' => ($course->isFree() ? 'Free' : 'KES ' . number_format((float)$course->getTotalEnrollmentFee(), 0)), 'label' => 'Enrollment Fee'],
            ['icon' => 'fas fa-stopwatch',  'color' => 'bg-rose-400/30',   'value' => ($course->exam_time_limit > 0 ? $course->exam_time_limit . ' min' : '—'), 'label' => 'Exam Limit'],
            ['icon' => 'fas fa-percent',    'color' => 'bg-emerald-400/30','value' => $course->passing_score . '%', 'label' => 'Pass Score'],
        ];
    @endphp

    @if($course->featured_image)
        {{-- Featured image with dark gradient overlay --}}
        <div class="relative">
            <div class="relative h-56 sm:h-64 lg:h-72">
                <img src="{{ asset('storage/' . $course->featured_image) }}"
                     alt="{{ $course->title }}"
                     class="w-full h-full object-cover">
                <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent"></div>
            </div>
            <div class="absolute bottom-0 left-0 right-0 px-6 sm:px-10 lg:px-16 pb-5 pt-4">
                @if($course->category)
                    <span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-white/20 text-white backdrop-blur-sm border border-white/30 mb-2">
                        @if($course->category->icon)<i class="{{ $course->category->icon }} text-xs"></i>@else<i class="fas fa-tag text-xs"></i>@endif
                        {{ $course->category->name }}
                    </span>
                @endif
                <h1 class="text-2xl sm:text-3xl lg:text-4xl font-bold text-white leading-tight w-full">{{ $course->title }}</h1>
                @if($course->instructor)
                    <p class="mt-1 text-sm text-white/80 flex items-center gap-1.5">
                        <i class="fas fa-user-tie text-xs"></i> {{ $course->instructor->name }}
                    </p>
                @endif
                {{-- Stat cards inside hero --}}
                <div class="mt-4 flex flex-wrap gap-2">
                    @foreach($heroStatCards as $card)
                    <div class="flex items-center gap-2 {{ $card['color'] }} backdrop-blur-sm border border-white/20 rounded-lg px-3 py-1.5">
                        <i class="{{ $card['icon'] }} text-white text-xs"></i>
                        <span class="text-sm font-bold text-white">{{ $card['value'] }}</span>
                        <span class="text-xs text-white/70">{{ $card['label'] }}</span>
                    </div>
                    @endforeach
                </div>
            </div>
        </div>
    @else
        {{-- Gradient fallback hero --}}
        <div class="relative bg-gradient-to-br from-indigo-700 via-purple-700 to-indigo-900 px-6 sm:px-10 lg:px-16 pt-12 pb-6 flex flex-col items-start justify-end min-h-[200px] sm:min-h-[240px]">
            <div class="absolute top-0 right-0 w-72 h-72 bg-white/5 rounded-full -translate-y-1/2 translate-x-1/3 pointer-events-none"></div>
            <div class="absolute bottom-0 left-0 w-48 h-48 bg-white/5 rounded-full translate-y-1/2 -translate-x-1/4 pointer-events-none"></div>

            @if($course->category)
                <span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-white/20 text-white border border-white/30 mb-2">
                    @if($course->category->icon)<i class="{{ $course->category->icon }} text-xs"></i>@else<i class="fas fa-tag text-xs"></i>@endif
                    {{ $course->category->name }}
                </span>
            @endif
            <h1 class="text-2xl sm:text-3xl lg:text-4xl font-bold text-white leading-tight w-full">{{ $course->title }}</h1>
            @if($course->instructor)
                <p class="mt-1 text-sm text-indigo-200 flex items-center gap-1.5">
                    <i class="fas fa-user-tie text-xs"></i> {{ $course->instructor->name }}
                </p>
            @endif
            {{-- Stat cards inside hero --}}
            <div class="mt-4 flex flex-wrap gap-2">
                @foreach($heroStatCards as $card)
                <div class="flex items-center gap-2 {{ $card['color'] }} border border-white/20 rounded-lg px-3 py-1.5">
                    <i class="{{ $card['icon'] }} text-white text-xs"></i>
                    <span class="text-sm font-bold text-white">{{ $card['value'] }}</span>
                    <span class="text-xs text-white/70">{{ $card['label'] }}</span>
                </div>
                @endforeach
            </div>
        </div>
    @endif
</div>

{{-- ===================================================================
     MAIN CONTENT AREA
=================================================================== --}}
<div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">

    {{-- ===================================================================
         MAIN CONTENT — Full width, stacked sections
    =================================================================== --}}
    <div class="space-y-5">

        {{-- Description --}}
        <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-6">
            <h2 class="text-sm font-semibold text-gray-800 mb-3 flex items-center gap-2">
                <i class="fas fa-align-left text-indigo-500"></i> About This Course
            </h2>
            <p class="text-sm text-gray-600 leading-relaxed">{{ $course->description }}</p>
        </div>

        {{-- Objectives --}}
        @if($course->objectives)
        <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-6">
            <h2 class="text-sm font-semibold text-gray-800 mb-3 flex items-center gap-2">
                <i class="fas fa-bullseye text-green-500"></i> What You Will Learn
            </h2>
            <ul class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-6 gap-y-2">
                @foreach(array_filter(array_map('trim', preg_split('/\r\n|\r|\n/', $course->objectives))) as $objective)
                    @if($objective)
                    <li class="flex items-start gap-2.5 text-sm text-gray-600">
                        <span class="mt-0.5 flex-shrink-0 w-5 h-5 bg-green-100 rounded-full flex items-center justify-center">
                            <i class="fas fa-check text-green-600 text-[10px]"></i>
                        </span>
                        {{ $objective }}
                    </li>
                    @endif
                @endforeach
            </ul>
        </div>
        @endif

        {{-- Prerequisites --}}
        @if($course->prerequisites)
        <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-6">
            <h2 class="text-sm font-semibold text-gray-800 mb-3 flex items-center gap-2">
                <i class="fas fa-list-check text-amber-500"></i> Prerequisites
            </h2>
            <ul class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-6 gap-y-2">
                @foreach(array_filter(array_map('trim', preg_split('/\r\n|\r|\n/', $course->prerequisites))) as $prereq)
                    @if($prereq)
                    <li class="flex items-start gap-2.5 text-sm text-gray-600">
                        <span class="mt-0.5 flex-shrink-0 w-5 h-5 bg-amber-100 rounded-full flex items-center justify-center">
                            <i class="fas fa-arrow-right text-amber-600 text-[10px]"></i>
                        </span>
                        {{ $prereq }}
                    </li>
                    @endif
                @endforeach
            </ul>
        </div>
        @endif

        {{-- Topics Outline --}}
        @php
            $publishedTopics = $course->topics->where('is_published', true);
        @endphp
        @if($publishedTopics->isNotEmpty())
        <div class="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-100 flex items-center gap-2">
                <i class="fas fa-list-ul text-teal-500"></i>
                <h2 class="text-sm font-semibold text-gray-800">Course Outline</h2>
                <span class="ml-auto text-xs text-gray-400">{{ $publishedTopics->count() }} {{ Str::plural('topic', $publishedTopics->count()) }}</span>
            </div>
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 divide-y sm:divide-y-0 divide-gray-50">
                @foreach($publishedTopics->values() as $idx => $topic)
                <div class="flex items-center gap-3 px-6 py-3.5 hover:bg-gray-50/50 transition border-b border-gray-50">
                    <span class="w-7 h-7 bg-indigo-100 rounded-full flex items-center justify-center text-xs font-bold text-indigo-600 flex-shrink-0">
                        {{ $idx + 1 }}
                    </span>
                    <div class="flex-1 min-w-0">
                        <p class="text-sm font-medium text-gray-700 truncate">{{ $topic->title }}</p>
                        @php $subtopicCount = $topic->subtopics->where('is_published', true)->count(); @endphp
                        @if($subtopicCount > 0)
                            <p class="text-xs text-gray-400 mt-0.5">{{ $subtopicCount }} {{ Str::plural('subtopic', $subtopicCount) }}</p>
                        @endif
                    </div>
                    <i class="fas fa-chevron-right text-gray-300 text-xs flex-shrink-0"></i>
                </div>
                @endforeach
            </div>
        </div>
        @endif

        {{-- Course Book Section --}}
        @if($hasBook)
        <div class="bg-gradient-to-br from-purple-50 to-blue-50 rounded-xl border border-purple-200 shadow-sm p-6">
            <div class="flex items-start gap-4">
                <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-book text-purple-600 text-lg"></i>
                </div>
                <div class="flex-1">
                    <h2 class="text-sm font-semibold text-gray-800 mb-1 flex items-center gap-2">
                        <i class="fas fa-book text-purple-500"></i> Course Book
                    </h2>
                    <p class="text-sm text-gray-600 mb-4">
                        @if($bookFee > 0)
                            Access the complete course material as a PDF. Purchase the book for <strong>KES {{ number_format($bookFee, 2) }}</strong>.
                        @else
                            Download the complete course material as a PDF at no additional cost.
                        @endif
                    </p>
                    
                    <div class="flex flex-col sm:flex-row gap-3">
                        @if($bookFee > 0 && !$bookPurchased)
                            {{-- Book needs to be purchased --}}
                            <button type="button"
                                    @click="showBookPaymentModal = true"
                                    class="flex items-center justify-center gap-2 px-5 py-2.5 bg-purple-600 hover:bg-purple-700 text-white font-semibold text-sm rounded-lg transition">
                                <i class="fas fa-lock text-xs"></i>
                                Purchase for KES {{ number_format($bookFee, 2) }}
                            </button>
                        @else
                            {{-- Book is free or already purchased --}}
                            <a href="{{ route('self-paced.learn.book.download', $course) }}"
                               class="flex items-center justify-center gap-2 px-5 py-2.5 bg-purple-600 hover:bg-purple-700 text-white font-semibold text-sm rounded-lg transition">
                                <i class="fas fa-download"></i>
                                Download Book
                            </a>
                        @endif
                    </div>
                </div>
            </div>
        </div>
        @endif

        {{-- How It Works — full width, steps spread horizontally --}}
        <div class="bg-indigo-50 rounded-xl border border-indigo-100 p-5">
            <h3 class="text-xs font-semibold text-indigo-600 uppercase tracking-wide mb-4 flex items-center gap-2">
                <i class="fas fa-lightbulb text-indigo-400"></i> How It Works
            </h3>
            <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
                @foreach([
                    ['num'=>'1','text'=>'Read all topics and subtopics'],
                    ['num'=>'2','text'=>'Mark each subtopic as read'],
                    ['num'=>'3','text'=>'Take the timed exam when ready'],
                    ['num'=>'4','text'=>'Download your certificate on passing'],
                ] as $step)
                <div class="flex items-start gap-2.5 text-xs text-indigo-700">
                    <span class="flex-shrink-0 w-5 h-5 bg-indigo-200 rounded-full flex items-center justify-center text-[10px] font-bold text-indigo-700 mt-0.5">{{ $step['num'] }}</span>
                    <span>{{ $step['text'] }}</span>
                </div>
                @endforeach
            </div>
        </div>

    </div>

</div>{{-- /max-w-6xl --}}


{{-- ===================================================================
     HERO FOOTER — Exam details + CTA (Req 2.4, 2.5, 2.6, 2.7, 2.9)
     Replaces the removed sidebar Exam Details card and Enrollment card.
=================================================================== --}}
<div class="w-full bg-gradient-to-r from-slate-800 to-indigo-900 py-8 px-4 sm:px-6 lg:px-8">
    <div class="max-w-6xl mx-auto">
        <div class="flex flex-col sm:flex-row flex-wrap gap-6 items-start sm:items-center justify-between">

            {{-- LEFT: Exam detail pills --}}
            <div class="flex flex-col sm:flex-row flex-wrap gap-4">

                <div class="flex items-center gap-3 bg-white/10 rounded-xl px-4 py-3 min-w-[140px]">
                    <span class="w-8 h-8 bg-white/20 rounded-lg flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-list-ol text-white text-sm"></i>
                    </span>
                    <div>
                        <p class="text-xs text-white/60 leading-none mb-0.5">Questions / Attempt</p>
                        <p class="text-base font-bold text-white">{{ $course->exam_questions_per_attempt }}</p>
                    </div>
                </div>

                <div class="flex items-center gap-3 bg-white/10 rounded-xl px-4 py-3 min-w-[140px]">
                    <span class="w-8 h-8 bg-white/20 rounded-lg flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-redo text-white text-sm"></i>
                    </span>
                    <div>
                        <p class="text-xs text-white/60 leading-none mb-0.5">Max Attempts</p>
                        <p class="text-base font-bold text-white">{{ $course->exam_attempts_allowed }}</p>
                    </div>
                </div>

                <div class="flex items-center gap-3 bg-white/10 rounded-xl px-4 py-3 min-w-[140px]">
                    <span class="w-8 h-8 bg-white/20 rounded-lg flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-stopwatch text-white text-sm"></i>
                    </span>
                    <div>
                        <p class="text-xs text-white/60 leading-none mb-0.5">Time Limit</p>
                        <p class="text-base font-bold text-white">{{ $course->exam_time_limit }} min</p>
                    </div>
                </div>

                <div class="flex items-center gap-3 bg-white/10 rounded-xl px-4 py-3 min-w-[140px]">
                    <span class="w-8 h-8 bg-white/20 rounded-lg flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-percent text-white text-sm"></i>
                    </span>
                    <div>
                        <p class="text-xs text-white/60 leading-none mb-0.5">Passing Score</p>
                        <p class="text-base font-bold text-white">{{ $course->passing_score }}%</p>
                    </div>
                </div>

            </div>

            {{-- RIGHT: Enrollment status + CTA --}}
            <div class="flex flex-col items-start sm:items-end gap-3">

                {{-- Enrollment status badge --}}
                <div class="flex items-center gap-2 text-xs text-white/70">
                    <i class="fas fa-user-check text-white/50"></i>
                    <span class="capitalize font-medium text-white/90">{{ str_replace('_', ' ', $enrollment->status) }}</span>
                    @if($enrollment->enrolled_at)
                        <span class="text-white/40">·</span>
                        <span>Enrolled {{ $enrollment->enrolled_at->format('d M Y') }}</span>
                    @endif
                </div>

                {{-- Fee breakdown --}}
                @if(!$course->isFree())
                <div class="text-xs text-white/60 space-y-0.5">
                    @if($course->registration_fee > 0)
                    <div class="flex items-center justify-between gap-4">
                        <span>Registration Fee:</span>
                        <span class="font-semibold text-white">KES {{ number_format($course->registration_fee, 2) }}</span>
                    </div>
                    @endif
                    @if($course->application_fee > 0)
                    <div class="flex items-center justify-between gap-4">
                        <span>Application Fee:</span>
                        <span class="font-semibold text-white">KES {{ number_format($course->application_fee, 2) }}</span>
                    </div>
                    @endif
                </div>
                @endif

                {{-- CTA Button --}}
                <a href="{{ route('self-paced.learn.content', $course) }}"
                   class="inline-flex items-center justify-center gap-2.5 px-6 py-3 bg-indigo-500 hover:bg-indigo-400 text-white font-semibold text-sm rounded-xl transition shadow-lg shadow-indigo-900/40 active:scale-95 whitespace-nowrap">
                    @if($progressPercentage > 0)
                        <i class="fas fa-play-circle"></i>
                        Continue Learning
                    @else
                        <i class="fas fa-rocket"></i>
                        Start Learning
                    @endif
                    <i class="fas fa-arrow-right text-xs opacity-70"></i>
                </a>

                <p class="text-xs text-white/40">
                    <i class="fas fa-info-circle mr-1"></i>
                    Complete all topics before taking the exam
                </p>

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

{{-- Book Payment Modal --}}
@if($hasBook && $bookFee > 0 && !$bookPurchased)
<div x-data="overviewPage()"
     x-show="showBookPaymentModal"
     x-cloak
     @keydown.escape="showBookPaymentModal = 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">Purchase Course Book</h3>
            <button type="button"
                    @click="showBookPaymentModal = 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">
            Download the complete course material as a PDF.
        </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">Book Fee:</span>
                <span class="text-lg font-bold text-indigo-700">KES {{ number_format($bookFee, 2) }}</span>
            </div>
        </div>

        <div class="space-y-2 mb-5">
            @if($course->acceptsOnlinePayment())
            <button type="button"
                    @click="proceedBookPayment()"
                    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="showBookProofForm = 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="showBookPaymentModal = false"
                class="w-full px-4 py-2 text-sm text-gray-600 hover:text-gray-800 transition">
            Cancel
        </button>
    </div>
</div>

{{-- Book Cash Proof Form --}}
<div x-show="showBookProofForm"
     x-cloak
     @keydown.escape="showBookProofForm = 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="showBookProofForm = 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.book.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="showBookProofForm = 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

<script>
function overviewPage() {
    return {
        showBookPaymentModal: false,
        showBookProofForm: false,
        isProcessing: false,

        async proceedBookPayment() {
            this.isProcessing = true;
            try {
                const response = await fetch('{{ route("self-paced.learn.book.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('Book payment error:', error);
                alert('An error occurred. Please try again.');
            } finally {
                this.isProcessing = false;
            }
        }
    };
}
</script>

@endsection
