@extends('layouts.site')

@section('title', 'Training Programs - SSHIA')
@section('description', 'Explore our comprehensive training programs and capacity building opportunities designed for healthcare professionals and organizations.')
@section('keywords', 'training, capacity building, professional development, workshops, certification, healthcare training')

@push('styles')
<style>
    .program-card {
        transition: all 0.3s ease;
        border: 1px solid rgba(0, 0, 0, 0.05);
    }
    .program-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    }
    .status-badge {
        font-size: 0.75rem;
        padding: 0.25rem 0.75rem;
        border-radius: 9999px;
    }
    .apply-btn {
        background: linear-gradient(135deg, #16a34a 0%, #15803d 100%);
        transition: all 0.3s ease;
    }
    .apply-btn:hover {
        transform: scale(1.02);
        box-shadow: 0 10px 15px -3px rgba(22, 163, 74, 0.4);
    }
    .modal-backdrop {
        background-color: rgba(0, 0, 0, 0.5);
        backdrop-filter: blur(4px);
    }
</style>
@endpush

@section('content')
{{-- Hero Section --}}
<div class="bg-gradient-to-r from-green-600 to-emerald-700 shadow-lg">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
        <div class="text-center max-w-4xl mx-auto">
            <div class="inline-flex items-center justify-center w-20 h-20 bg-white/10 backdrop-blur-sm rounded-2xl mb-6">
                <i class="fas fa-chalkboard-teacher text-white text-4xl"></i>
            </div>
            <h1 class="text-4xl md:text-5xl font-bold text-white mb-4">
                Capacity Building & Training Programs
            </h1>
            <p class="text-xl text-green-50 mb-8 leading-relaxed">
                Enhance your skills and knowledge through our comprehensive training programs 
                designed for healthcare professionals and organizations across South Sudan.
            </p>
            <div class="flex flex-wrap items-center justify-center gap-4">
                <a href="#programs" 
                   class="inline-flex items-center px-6 py-3 bg-white text-green-700 font-semibold rounded-lg hover:bg-green-50 transition shadow-lg hover:shadow-xl">
                    <i class="fas fa-list mr-2"></i>
                    Browse Programs
                </a>
                <a href="{{ route('public.training.certificates.verify-page') }}" 
                   class="inline-flex items-center px-6 py-3 border-2 border-white text-white font-semibold rounded-lg hover:bg-white hover:text-green-700 transition">
                    <i class="fas fa-certificate mr-2"></i>
                    Verify Certificate
                </a>
                <a href="{{ route('self-paced.public.index') }}" 
                   class="inline-flex items-center px-6 py-3 bg-yellow-500 text-gray-900 font-semibold rounded-lg hover:bg-yellow-400 transition shadow-lg hover:shadow-xl">
                    <i class="fas fa-graduation-cap mr-2"></i>
                    SSHIA Academy
                </a>
            </div>
        </div>
    </div>
</div>

{{-- Breadcrumb --}}
<div class="bg-gray-50 border-b border-gray-200">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3">
        <nav class="flex items-center space-x-2 text-sm text-gray-600" aria-label="Breadcrumb">
            <a href="{{ url('/') }}" class="hover:text-green-600 transition flex items-center">
                <i class="fas fa-home mr-1"></i>Home
            </a>
            <i class="fas fa-chevron-right text-gray-400 text-xs"></i>
            <span class="text-gray-900 font-medium">Training Programs</span>
        </nav>
    </div>
</div>

{{-- Filter Section --}}
<section class="bg-white py-8 border-b border-gray-200">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex flex-wrap gap-4 items-center">
            {{-- Live Search Input --}}
            <div class="flex-1 min-w-64 relative">
                <input type="text"
                       id="liveSearchInput"
                       placeholder="Search training programs..."
                       value="{{ request('search') }}"
                       autocomplete="off"
                       class="w-full pl-10 pr-10 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 transition">
                <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                <button id="clearSearch"
                        class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 hidden">
                    <i class="fas fa-times"></i>
                </button>
            </div>

            {{-- Category Filter --}}
            <div class="w-64">
                <select id="categoryFilter"
                        name="category"
                        class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 transition">
                    <option value="">All Categories</option>
                    @foreach($categories as $category)
                        <option value="{{ $category->id }}" {{ request('category') == $category->id ? 'selected' : '' }}>
                            {{ $category->name }}
                        </option>
                    @endforeach
                </select>
            </div>

            {{-- Fallback submit for non-JS --}}
            <noscript>
                <form method="GET" action="{{ route('public.training.index') }}" class="flex gap-3">
                    <input type="hidden" name="search" id="noscriptSearch">
                    <input type="hidden" name="category" id="noscriptCategory">
                    <button type="submit" class="px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition font-medium">
                        <i class="fas fa-filter mr-2"></i>Apply Filters
                    </button>
                </form>
            </noscript>

            @if(request('search') || request('category'))
                <a href="{{ route('public.training.index') }}"
                   class="px-4 py-3 text-gray-600 hover:text-gray-800 font-medium transition">
                    <i class="fas fa-times mr-1"></i>Clear All
                </a>
            @endif
        </div>

        {{-- Live Search Results Dropdown --}}
        <div id="searchResultsDropdown"
             class="hidden mt-3 bg-white border border-gray-200 rounded-xl shadow-2xl overflow-hidden max-h-96 overflow-y-auto z-50 relative">
            <div class="px-4 py-2 bg-gray-50 border-b border-gray-200 flex items-center justify-between">
                <span class="text-xs font-semibold text-gray-600 uppercase tracking-wide">
                    Search Results
                </span>
                <span id="searchResultCount" class="text-xs text-gray-500"></span>
            </div>
            <div id="searchResultsList"></div>
        </div>
    </div>
</section>

{{-- Programs Section --}}
<section id="programs" class="py-16 bg-gray-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="mb-10 text-center">
            <h2 class="text-3xl font-bold text-gray-900 mb-3">
                Available Training Programs
            </h2>
            <p class="text-lg text-gray-600 max-w-5xl mx-auto">
                Browse our upcoming training programs and secure your spot today. Each program is designed to enhance your professional skills and knowledge.
            </p>
        </div>
        
        @if($packages->count() > 0)
            {{-- Programs Grid --}}
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-12">
                @foreach($packages as $package)
                    @php
                        $sessions = $upcomingSessions[$package->id] ?? collect([]);
                        $firstSession = $sessions->first();
                        $spotsLeft = $package->capacity - $package->registrations_count;
                    @endphp
                    
                    <article class="program-card bg-white rounded-xl shadow-md overflow-hidden flex flex-col">
                        {{-- Program Image --}}
                        @if($package->featured_image)
                            <div class="h-48 overflow-hidden">
                                <img src="{{ $package->featured_image }}" 
                                     alt="{{ $package->name }}"
                                     class="w-full h-full object-cover">
                            </div>
                        @else
                            <div class="h-48 bg-gradient-to-br from-green-500 to-emerald-600 flex items-center justify-center">
                                <i class="fas fa-chalkboard-teacher text-white text-6xl opacity-50"></i>
                            </div>
                        @endif
                        
                        {{-- Program Content --}}
                        <div class="p-6 flex-1 flex flex-col">
                            {{-- Category & Status Badges --}}
                            <div class="flex items-center gap-2 mb-3 flex-wrap">
                                @if($package->category)
                                    <span class="px-3 py-1 bg-blue-100 text-blue-700 text-xs font-semibold rounded-full">
                                        {{ $package->category->name }}
                                    </span>
                                @endif
                                
                                @if($spotsLeft <= 0)
                                    <span class="status-badge bg-red-100 text-red-700">
                                        <i class="fas fa-times-circle mr-1"></i>Full
                                    </span>
                                @elseif($spotsLeft <= 5)
                                    <span class="status-badge bg-yellow-100 text-yellow-700">
                                        <i class="fas fa-exclamation-circle mr-1"></i>Almost Full
                                    </span>
                                @else
                                    <span class="status-badge bg-green-100 text-green-700">
                                        <i class="fas fa-check-circle mr-1"></i>Available
                                    </span>
                                @endif
                            </div>
                            
                            {{-- Program Title --}}
                            <h3 class="text-xl font-bold text-gray-900 mb-3 line-clamp-2">
                                {{ $package->name }}
                            </h3>
                            
                            {{-- Program Description --}}
                            <p class="text-gray-600 text-sm mb-4 line-clamp-3 flex-1">
                                {{ Str::limit($package->description, 150) }}
                            </p>
                            
                            {{-- Program Details --}}
                            <div class="space-y-2 mb-4">
                                <div class="flex items-center text-sm text-gray-600">
                                    <i class="fas fa-clock w-5 text-green-600"></i>
                                    <span>{{ $package->duration_hours }} hours
                                        @if($package->duration_days > 0)
                                            / {{ $package->duration_days }} days
                                        @endif
                                    </span>
                                </div>
                                
                                @if($sessions->count() > 0)
                                    <div class="flex items-center text-sm text-gray-600">
                                        <i class="fas fa-calendar w-5 text-green-600"></i>
                                        <span>{{ $firstSession->session_date->format('M d, Y') }}</span>
                                    </div>
                                    
                                    @if($firstSession->session_type === 'online')
                                        <div class="flex items-center text-sm text-blue-600">
                                            <i class="fas fa-video w-5"></i>
                                            <span>Online Training</span>
                                        </div>
                                    @elseif($firstSession->venue_name)
                                        <div class="flex items-center text-sm text-gray-600">
                                            <i class="fas fa-map-marker-alt w-5 text-green-600"></i>
                                            <span>{{ Str::limit($firstSession->venue_name, 30) }}</span>
                                        </div>
                                    @endif
                                @else
                                    <div class="flex items-center text-sm text-gray-400">
                                        <i class="fas fa-calendar-times w-5"></i>
                                        <span>Schedule coming soon</span>
                                    </div>
                                @endif
                                
                                <div class="flex items-center text-sm text-gray-600">
                                    <i class="fas fa-users w-5 text-green-600"></i>
                                    <span>{{ $spotsLeft }} spots remaining</span>
                                </div>
                                
                                @if($package->generates_certificate)
                                    <div class="flex items-center text-sm text-green-600">
                                        <i class="fas fa-certificate w-5"></i>
                                        <span>Certificate Included</span>
                                    </div>
                                @endif
                            </div>
                            
                            {{-- Fee & Action --}}
                            <div class="pt-4 border-t border-gray-100 flex items-center justify-between">
                                <div>
                                    @if($package->is_free)
                                        <span class="text-2xl font-bold text-green-600">Free</span>
                                    @else
                                        <div class="text-2xl font-bold text-gray-900">
                                            {{ number_format($package->fee_amount, 0) }}
                                        </div>
                                        <div class="text-sm text-gray-500">{{ $package->currency }}</div>
                                    @endif
                                </div>
                                
                                @if($spotsLeft > 0)
                                    <button onclick="openApplicationModal({{ $package->id }})"
                                            class="apply-btn px-6 py-3 text-white rounded-lg font-medium shadow-md hover:shadow-lg">
                                        <i class="fas fa-user-plus mr-2"></i>
                                        Apply Now
                                    </button>
                                @else
                                    <button disabled 
                                            class="px-6 py-3 bg-gray-200 text-gray-500 rounded-lg cursor-not-allowed">
                                        <i class="fas fa-ban mr-2"></i>
                                        Fully Booked
                                    </button>
                                @endif
                            </div>
                        </div>
                    </article>
                @endforeach
            </div>
            
            {{-- Pagination --}}
            <div class="flex justify-center">
                {{ $packages->links() }}
            </div>
        @else
            <div class="text-center py-20 bg-white rounded-2xl shadow-lg">
                <div class="inline-flex items-center justify-center w-24 h-24 bg-gray-100 rounded-full mb-6">
                    <i class="fas fa-calendar-times text-gray-400 text-4xl"></i>
                </div>
                <h3 class="text-2xl font-bold text-gray-800 mb-3">No Training Programs Available</h3>
                <p class="text-gray-600 mb-8 max-w-md mx-auto">
                    There are no training programs scheduled at the moment. 
                    Please check back later or contact us for more information.
                </p>
                <div class="flex flex-wrap items-center justify-center gap-4">
                    <a href="{{ route('home') }}" class="inline-flex items-center px-6 py-3 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition font-medium">
                        <i class="fas fa-arrow-left mr-2"></i>
                        Return to Home
                    </a>
                    <a href="{{ route('self-paced.public.index') }}" class="inline-flex items-center px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition font-medium">
                        <i class="fas fa-graduation-cap mr-2"></i>
                        Try SSHIA Academy
                    </a>
                </div>
            </div>
        @endif
    </div>
</section>

{{-- Application Modal --}}
<div id="applicationModal" 
     class="fixed inset-0 z-50 hidden overflow-y-auto"
     x-data="applicationForm()"
     x-init="
        // Listen for custom event to update selected program
        window.addEventListener('open-application-modal', e => {
            selectedProgram = e.detail;
        });
     ">
    <div class="modal-backdrop fixed inset-0" @click="closeModal()"></div>
    
    <div class="relative min-h-screen flex items-center justify-center p-4">
        <div class="relative bg-white rounded-2xl shadow-2xl max-w-3xl w-full max-h-[90vh] overflow-y-auto">
            {{-- Modal Header --}}
            <div class="sticky top-0 bg-gradient-to-r from-green-600 to-emerald-700 px-6 py-5 flex items-center justify-between rounded-t-2xl">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 bg-white/20 backdrop-blur-sm rounded-lg flex items-center justify-center">
                        <i class="fas fa-user-graduate text-white text-lg"></i>
                    </div>
                    <h3 class="text-xl font-bold text-white">
                        Training Application Form
                    </h3>
                </div>
                <button @click="closeModal()" class="text-white/80 hover:text-white transition">
                    <i class="fas fa-times text-2xl"></i>
                </button>
            </div>
            
            {{-- Selected Program Info --}}
            <div class="bg-green-50 px-6 py-4 border-b border-green-100">
                <div class="flex items-center gap-4">
                    <div class="w-14 h-14 bg-green-600 rounded-xl flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-chalkboard-teacher text-white text-xl"></i>
                    </div>
                    <div class="flex-1">
                        <h4 class="font-semibold text-gray-900 text-lg" x-text="selectedProgram.name"></h4>
                        <p class="text-sm text-gray-600" x-text="selectedProgram.fee"></p>
                    </div>
                </div>
            </div>
            
            {{-- Application Form --}}
            <form action="" method="POST" id="applicationForm" class="p-6 space-y-6">
                @csrf
                <input type="hidden" name="package_id" id="package_id">
                
                {{-- Personal Information Section --}}
                <div>
                    <h4 class="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
                        <i class="fas fa-user text-green-600"></i>
                        Personal Information
                    </h4>
                    <div class="grid md:grid-cols-2 gap-4">
                        {{-- Name --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Full Name <span class="text-red-500">*</span>
                            </label>
                            <input type="text" 
                                   name="name" 
                                   required
                                   class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 transition"
                                   placeholder="Enter your full name">
                        </div>
                        
                        {{-- Email --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Email Address <span class="text-red-500">*</span>
                            </label>
                            <input type="email" 
                                   name="email" 
                                   required
                                   class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 transition"
                                   placeholder="your@email.com">
                        </div>
                        
                        {{-- Phone --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Phone Number <span class="text-red-500">*</span>
                            </label>
                            <input type="tel" 
                                   name="phone" 
                                   required
                                   class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 transition"
                                   placeholder="e.g., 0771234567">
                        </div>
                        
                        {{-- Payment section (for paid trainings) — uses the shared toggle component --}}
                        <div x-show="selectedProgram.requiresPayment" x-cloak class="col-span-full">
                            <div class="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                                <p class="text-xs font-semibold text-yellow-800 mb-3 flex items-center gap-1.5">
                                    <i class="fas fa-credit-card text-yellow-600"></i>
                                    Payment Required — choose your method
                                </p>
                                <x-payment-method-toggle />
                            </div>
                        </div>
                    </div>
                </div>
                
                {{-- Professional Information Section --}}
                <div>
                    <h4 class="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
                        <i class="fas fa-briefcase text-green-600"></i>
                        Professional Information
                    </h4>
                    <div class="grid md:grid-cols-2 gap-4">
                        {{-- Organization --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Organization
                            </label>
                            <input type="text" 
                                   name="organization"
                                   class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 transition"
                                   placeholder="Your organization name">
                        </div>
                        
                        {{-- Position --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Position / Title
                            </label>
                            <input type="text" 
                                   name="position"
                                   class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 transition"
                                   placeholder="Your job title">
                        </div>
                    </div>
                </div>
                
                {{-- Additional Notes --}}
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-comment-dots text-green-600 mr-1"></i>
                        Additional Notes
                    </label>
                    <textarea name="notes"
                              rows="3"
                              class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 transition resize-none"
                              placeholder="Any special requirements or notes..."></textarea>
                </div>
                
                {{-- Terms --}}
                <div class="bg-gray-50 rounded-lg p-4">
                    <label class="flex items-start gap-3 cursor-pointer">
                        <input type="checkbox" 
                               name="terms" 
                               required
                               class="mt-1 w-5 h-5 text-green-600 border-gray-300 rounded focus:ring-green-500">
                        <span class="text-sm text-gray-700">
                            I agree to the 
                            <a href="#" class="text-green-600 hover:underline font-medium">Terms and Conditions</a> 
                            and confirm that the information provided is accurate and complete.
                        </span>
                    </label>
                </div>
                
                {{-- Submit Buttons --}}
                <div class="flex flex-col sm:flex-row justify-end gap-3 pt-4 border-t border-gray-200">
                    <button type="button" 
                            @click="closeModal()"
                            class="px-6 py-3 border-2 border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition font-medium">
                        <i class="fas fa-times mr-2"></i>
                        Cancel
                    </button>
                    <button type="submit"
                            class="apply-btn px-8 py-3 text-white rounded-lg font-semibold shadow-md hover:shadow-lg">
                        <i class="fas fa-paper-plane mr-2"></i>
                        Submit Application
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

{{-- Why Choose Our Training Section --}}
<section class="py-16 bg-white">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="text-center mb-12">
            <h2 class="text-3xl font-bold text-gray-900 mb-3">
                Why Choose Our Training Programs?
            </h2>
            <p class="text-lg text-gray-600 max-w-5xl mx-auto">
                We provide world-class training designed specifically for healthcare professionals in South Sudan
            </p>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
            <div class="text-center">
                <div class="inline-flex items-center justify-center w-16 h-16 bg-green-100 rounded-2xl mb-4">
                    <i class="fas fa-user-graduate text-green-600 text-2xl"></i>
                </div>
                <h3 class="text-lg font-semibold text-gray-900 mb-2">Expert Trainers</h3>
                <p class="text-gray-600 text-sm">
                    Learn from experienced professionals with deep expertise in health informatics and healthcare management.
                </p>
            </div>

            <div class="text-center">
                <div class="inline-flex items-center justify-center w-16 h-16 bg-blue-100 rounded-2xl mb-4">
                    <i class="fas fa-certificate text-blue-600 text-2xl"></i>
                </div>
                <h3 class="text-lg font-semibold text-gray-900 mb-2">Certification</h3>
                <p class="text-gray-600 text-sm">
                    Receive recognized certificates upon completion to enhance your professional credentials.
                </p>
            </div>

            <div class="text-center">
                <div class="inline-flex items-center justify-center w-16 h-16 bg-purple-100 rounded-2xl mb-4">
                    <i class="fas fa-hands-helping text-purple-600 text-2xl"></i>
                </div>
                <h3 class="text-lg font-semibold text-gray-900 mb-2">Practical Skills</h3>
                <p class="text-gray-600 text-sm">
                    Gain hands-on experience with real-world scenarios and practical applications.
                </p>
            </div>

            <div class="text-center">
                <div class="inline-flex items-center justify-center w-16 h-16 bg-yellow-100 rounded-2xl mb-4">
                    <i class="fas fa-users text-yellow-600 text-2xl"></i>
                </div>
                <h3 class="text-lg font-semibold text-gray-900 mb-2">Networking</h3>
                <p class="text-gray-600 text-sm">
                    Connect with fellow healthcare professionals and build lasting professional relationships.
                </p>
            </div>
        </div>
    </div>
</section>

{{-- Certificate Verification Section --}}
<section class="py-16 bg-gradient-to-br from-gray-50 to-gray-100">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="bg-white rounded-2xl shadow-xl p-8 md:p-12">
            <div class="text-center mb-8">
                <div class="inline-flex items-center justify-center w-20 h-20 bg-green-100 rounded-2xl mb-4">
                    <i class="fas fa-certificate text-green-600 text-3xl"></i>
                </div>
                <h2 class="text-3xl font-bold text-gray-900 mb-3">
                    Verify a Training Certificate
                </h2>
                <p class="text-gray-600 text-lg">
                    Enter the certificate verification code to confirm authenticity and view certificate details.
                </p>
            </div>
            
            <form action="{{ route('public.training.certificates.verify-page') }}" 
                  method="GET"
                  class="max-w-md mx-auto"
                  onsubmit="event.preventDefault(); window.location.href='{{ url('/training/certificates/verify') }}/' + encodeURIComponent(document.getElementById('verification_code').value)">
                <div class="flex gap-3">
                    <input type="text" 
                           id="verification_code"
                           name="code"
                           required
                           placeholder="Enter verification code"
                           class="flex-1 px-4 py-4 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 text-lg">
                    <button type="submit" 
                            class="px-8 py-4 bg-green-600 text-white rounded-lg hover:bg-green-700 transition font-semibold shadow-md hover:shadow-lg">
                        <i class="fas fa-search mr-2"></i>
                        Verify
                    </button>
                </div>
                <p class="text-sm text-gray-500 mt-3 text-center">
                    The verification code can be found on the certificate document
                </p>
            </form>
        </div>
    </div>
</section>
@endsection

@push('scripts')
<script>
    // =========================================================================
    // All training packages data for live search
    // =========================================================================
    @php
        $allPackagesJson = $packages->map(function($p) {
            return [
                'id'              => $p->id,
                'name'            => $p->name,
                'description'     => Str::limit($p->description ?? '', 100),
                'category'        => $p->category->name ?? 'General',
                'fee'             => $p->is_free ? 'Free' : number_format($p->fee_amount, 0) . ' ' . $p->currency,
                'is_free'         => $p->is_free,
                'requiresPayment' => !$p->is_free && $p->fee_amount > 0,
                'duration'        => $p->duration_hours . ' hrs',
                'spots'           => $p->capacity - $p->registrations_count,
                'certificate'     => $p->generates_certificate,
                'url'             => route('public.training.show', $p),
                'applyUrl'        => route('public.training.apply', $p),
            ];
        })->values();
    @endphp
    const allPackagesData = @json($allPackagesJson);

    // =========================================================================
    // Live Search
    // =========================================================================
    const searchInput      = document.getElementById('liveSearchInput');
    const categoryFilter   = document.getElementById('categoryFilter');
    const dropdown         = document.getElementById('searchResultsDropdown');
    const resultsList      = document.getElementById('searchResultsList');
    const resultCount      = document.getElementById('searchResultCount');
    const clearBtn         = document.getElementById('clearSearch');

    let searchDebounce = null;

    function performLiveSearch() {
        const query    = searchInput.value.trim().toLowerCase();
        const catId    = categoryFilter.value;

        // Show/hide clear button
        clearBtn.classList.toggle('hidden', query.length === 0);

        // If empty query and no category, hide dropdown
        if (query.length === 0 && catId === '') {
            dropdown.classList.add('hidden');
            return;
        }

        // Filter packages
        const results = allPackagesData.filter(p => {
            const matchesSearch = query === ''
                || p.name.toLowerCase().includes(query)
                || p.description.toLowerCase().includes(query)
                || p.category.toLowerCase().includes(query);
            const matchesCat = catId === '' || true; // category filter handled server-side on page load
            return matchesSearch && matchesCat;
        });

        // Render results
        if (results.length === 0) {
            resultsList.innerHTML = `
                <div class="px-4 py-8 text-center text-gray-500">
                    <i class="fas fa-search text-3xl mb-3 text-gray-300 block"></i>
                    <p class="text-sm">No programs found matching "<strong>${escapeHtml(searchInput.value)}</strong>"</p>
                </div>`;
        } else {
            resultsList.innerHTML = results.map(p => `
                <a href="${p.url}"
                   class="flex items-center gap-4 px-4 py-3 hover:bg-green-50 border-b border-gray-100 last:border-0 transition group">
                    <div class="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center flex-shrink-0 group-hover:bg-green-200 transition">
                        <i class="fas fa-chalkboard-teacher text-green-600 text-sm"></i>
                    </div>
                    <div class="flex-1 min-w-0">
                        <div class="font-semibold text-gray-900 text-sm truncate">${escapeHtml(p.name)}</div>
                        <div class="text-xs text-gray-500 flex items-center gap-3 mt-0.5">
                            <span><i class="fas fa-tag mr-1"></i>${escapeHtml(p.category)}</span>
                            <span><i class="fas fa-clock mr-1"></i>${p.duration}</span>
                            <span class="${p.is_free ? 'text-green-600' : 'text-gray-600'} font-medium">${p.fee}</span>
                        </div>
                    </div>
                    <div class="flex items-center gap-2 flex-shrink-0">
                        ${p.spots > 0
                            ? `<span class="px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full">${p.spots} spots</span>
                               <button onclick="event.preventDefault(); openApplicationModal(${p.id})"
                                       class="px-3 py-1.5 bg-green-600 text-white text-xs rounded-lg hover:bg-green-700 transition">
                                   Apply
                               </button>`
                            : `<span class="px-2 py-1 bg-red-100 text-red-700 text-xs rounded-full">Full</span>`
                        }
                    </div>
                </a>`).join('');
        }

        resultCount.textContent = `${results.length} result${results.length !== 1 ? 's' : ''}`;
        dropdown.classList.remove('hidden');
    }

    function escapeHtml(str) {
        const d = document.createElement('div');
        d.appendChild(document.createTextNode(str));
        return d.innerHTML;
    }

    // Debounced input handler
    searchInput.addEventListener('input', function() {
        clearTimeout(searchDebounce);
        searchDebounce = setTimeout(performLiveSearch, 200);
    });

    // Category change triggers search too
    categoryFilter.addEventListener('change', function() {
        // For category, also navigate to filtered page
        const url = new URL(window.location.href);
        if (this.value) {
            url.searchParams.set('category', this.value);
        } else {
            url.searchParams.delete('category');
        }
        if (searchInput.value.trim()) {
            url.searchParams.set('search', searchInput.value.trim());
        }
        window.location.href = url.toString();
    });

    // Clear button
    clearBtn.addEventListener('click', function() {
        searchInput.value = '';
        dropdown.classList.add('hidden');
        clearBtn.classList.add('hidden');
        searchInput.focus();
    });

    // Close dropdown when clicking outside
    document.addEventListener('click', function(e) {
        if (!searchInput.contains(e.target) && !dropdown.contains(e.target)) {
            dropdown.classList.add('hidden');
        }
    });

    // Keyboard navigation
    searchInput.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            dropdown.classList.add('hidden');
        }
        if (e.key === 'Enter') {
            e.preventDefault();
            const url = new URL(window.location.href);
            url.searchParams.set('search', this.value.trim());
            if (categoryFilter.value) url.searchParams.set('category', categoryFilter.value);
            window.location.href = url.toString();
        }
    });

    // Run search on page load if there's a pre-filled value
    if (searchInput.value.trim()) {
        performLiveSearch();
    }

    // =========================================================================
    // Application Modal — Alpine-compatible
    // =========================================================================
    @php
        $programsJson = $packages->map(function($p) {
            return [
                'id'              => $p->id,
                'name'            => $p->name,
                'fee'             => $p->is_free ? 'Free' : number_format($p->fee_amount, 0) . ' ' . $p->currency,
                'requiresPayment' => !$p->is_free && $p->fee_amount > 0,
            ];
        })->values();
    @endphp
    const programsData = @json($programsJson);

    function openApplicationModal(packageId) {
        const program = programsData.find(p => p.id === packageId);
        if (!program) return;

        // Update form action
        const form = document.getElementById('applicationForm');
        form.action = '{{ url("/training") }}/' + packageId + '/apply';

        // Dispatch custom event so Alpine component updates selectedProgram
        window.dispatchEvent(new CustomEvent('open-application-modal', { detail: program }));

        // Show modal
        const modalEl = document.getElementById('applicationModal');
        modalEl.classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    }

    function closeModal() {
        document.getElementById('applicationModal').classList.add('hidden');
        document.body.style.overflow = 'auto';
    }

    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') closeModal();
    });

    // =========================================================================
    // Alpine applicationForm component
    // =========================================================================
    function applicationForm() {
        return {
            selectedProgram: {
                id: null,
                name: '',
                fee: '',
                requiresPayment: false,
            },
            closeModal() {
                document.getElementById('applicationModal').classList.add('hidden');
                document.body.style.overflow = 'auto';
            }
        };
    }
</script>
@endpush
