<x-app-layout>

<x-module-hero
    title="Training Calendar"
    description="Visual overview of all scheduled training sessions"
    icon="fa-calendar-week">

    <x-slot name="tabs">
        @can('view training packages')
            <a href="{{ route('training.packages.index') }}"
               class="module-hero-tab {{ request()->routeIs('training.packages.index') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-box text-sm"></i> Packages
            </a>
        @endcan
        @can('view training sessions')
            <a href="{{ route('training.sessions.index') }}"
               class="module-hero-tab {{ request()->routeIs('training.sessions.index') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-list text-sm"></i> Sessions
            </a>
            <a href="{{ route('training.sessions.calendar') }}"
               class="module-hero-tab {{ request()->routeIs('training.sessions.calendar') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-calendar-alt text-sm"></i> Calendar
            </a>
        @endcan
        @can('view training registrations')
            <a href="{{ route('training.registrations.index') }}"
               class="module-hero-tab {{ request()->routeIs('training.registrations.index') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-users text-sm"></i> Registrations
            </a>
            <a href="{{ route('training.registrations.pending') }}"
               class="module-hero-tab {{ request()->routeIs('training.registrations.pending') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-clock text-sm"></i> Pending
            </a>
        @endcan
        @can('view training certificates')
            <a href="{{ route('training.certificates.index') }}"
               class="module-hero-tab {{ request()->routeIs('training.certificates.index') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-certificate text-sm"></i> Certificates
            </a>
        @endcan
        @can('view training reports')
            <a href="{{ route('training.reports.index') }}"
               class="module-hero-tab {{ request()->routeIs('training.reports.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-chart-bar text-sm"></i> Reports
            </a>
        @endcan
    </x-slot>

    <x-slot name="actions">
        @can('create training sessions')
            <a href="{{ route('training.sessions.create') }}"
               class="inline-flex items-center gap-2 px-4 py-2 bg-[#1e293b] text-white text-sm font-semibold rounded-lg hover:bg-[#334155] transition">
                <i class="fas fa-plus"></i> New Session
            </a>
        @endcan
    </x-slot>

</x-module-hero>

<div class="p-6">

    {{-- Stats Row --}}
    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-lg border border-gray-200 p-4 text-center">
            <div class="text-2xl font-bold text-gray-800">{{ $statistics['this_week'] }}</div>
            <div class="text-xs text-gray-500 mt-1">This Week</div>
        </div>
        <div class="bg-white rounded-lg border border-gray-200 p-4 text-center">
            <div class="text-2xl font-bold text-gray-800">{{ $statistics['this_month'] }}</div>
            <div class="text-xs text-gray-500 mt-1">This Month</div>
        </div>
        <div class="bg-white rounded-lg border border-gray-200 p-4 text-center">
            <div class="text-2xl font-bold text-gray-800">{{ $statistics['online'] }}</div>
            <div class="text-xs text-gray-500 mt-1">Online</div>
        </div>
        <div class="bg-white rounded-lg border border-gray-200 p-4 text-center">
            <div class="text-2xl font-bold text-gray-800">{{ $statistics['physical'] }}</div>
            <div class="text-xs text-gray-500 mt-1">Physical</div>
        </div>
    </div>

    {{-- Calendar Controls --}}
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-4">
        <div class="flex flex-wrap items-center justify-between gap-4">
            <div class="flex items-center gap-2">
                <button onclick="previousMonth()" class="p-2 hover:bg-gray-100 rounded-lg transition">
                    <i class="fas fa-chevron-left text-gray-600"></i>
                </button>
                <h3 id="currentMonth" class="text-lg font-semibold text-gray-800 min-w-44 text-center">
                    {{ $currentMonth }}
                </h3>
                <button onclick="nextMonth()" class="p-2 hover:bg-gray-100 rounded-lg transition">
                    <i class="fas fa-chevron-right text-gray-600"></i>
                </button>
                <button onclick="goToToday()" class="ml-2 px-3 py-1.5 text-sm bg-green-100 text-green-700 rounded-lg hover:bg-green-200 transition">
                    Today
                </button>
            </div>
            <div class="flex items-center gap-4 text-xs">
                <div class="flex items-center gap-1.5"><span class="w-3 h-3 bg-blue-500 rounded-full"></span><span class="text-gray-600">Scheduled</span></div>
                <div class="flex items-center gap-1.5"><span class="w-3 h-3 bg-yellow-500 rounded-full"></span><span class="text-gray-600">Ongoing</span></div>
                <div class="flex items-center gap-1.5"><span class="w-3 h-3 bg-green-500 rounded-full"></span><span class="text-gray-600">Completed</span></div>
                <div class="flex items-center gap-1.5"><span class="w-3 h-3 bg-red-500 rounded-full"></span><span class="text-gray-600">Cancelled</span></div>
            </div>
            <select id="packageFilter" onchange="filterByPackage(this.value)"
                    class="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500">
                <option value="">All Packages</option>
                @foreach($packages as $package)
                    <option value="{{ $package->id }}">{{ $package->name }}</option>
                @endforeach
            </select>
        </div>
    </div>

    {{-- Calendar Grid --}}
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden mb-6">
        <div class="grid grid-cols-7 bg-gray-50 border-b">
            @foreach(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] as $day)
                <div class="px-3 py-2 text-center text-xs font-semibold text-gray-600">{{ $day }}</div>
            @endforeach
        </div>
        <div id="calendarGrid" class="grid grid-cols-7"
             x-data="calendarComponent()"
             x-init="init()">
            <template x-for="day in days" :key="day.date">
                <div class="min-h-28 border-b border-r border-gray-100 p-1.5 hover:bg-gray-50 transition"
                     :class="{ 'bg-gray-50': !day.isCurrentMonth, 'bg-green-50': day.isToday }">
                    <div class="flex items-center justify-between mb-1">
                        <span class="text-xs font-medium"
                              :class="day.isToday ? 'text-green-600 font-bold' : (day.isCurrentMonth ? 'text-gray-800' : 'text-gray-400')"
                              x-text="day.dayNumber"></span>
                        <span x-show="day.sessions.length > 0" class="text-xs text-gray-400"
                              x-text="day.sessions.length + ' session(s)'"></span>
                    </div>
                    <div class="space-y-0.5">
                        <template x-for="session in day.sessions.slice(0, 3)" :key="session.id">
                            <a :href="session.url" class="block p-1 text-xs rounded cursor-pointer transition truncate"
                               :class="{
                                   'bg-blue-100 text-blue-800 hover:bg-blue-200': session.status === 'scheduled',
                                   'bg-yellow-100 text-yellow-800 hover:bg-yellow-200': session.status === 'ongoing',
                                   'bg-green-100 text-green-800 hover:bg-green-200': session.status === 'completed',
                                   'bg-red-100 text-red-800 hover:bg-red-200': session.status === 'cancelled'
                               }">
                                <span class="font-medium" x-text="session.title"></span>
                            </a>
                        </template>
                        <div x-show="day.sessions.length > 3" class="text-xs text-gray-500 text-center cursor-pointer hover:text-gray-700">
                            +<span x-text="day.sessions.length - 3"></span> more
                        </div>
                    </div>
                </div>
            </template>
        </div>
    </div>

    {{-- Today & This Week --}}
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-5">
            <h3 class="font-semibold text-gray-800 mb-4 flex items-center gap-2">
                <i class="fas fa-calendar-day text-green-600"></i> Today's Sessions
            </h3>
            @if($todaySessions->count() > 0)
                <div class="space-y-3">
                    @foreach($todaySessions as $session)
                        <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition">
                            <div>
                                <div class="font-medium text-gray-800 text-sm">{{ $session->session_name }}</div>
                                <div class="text-xs text-gray-500">
                                    {{ \Carbon\Carbon::parse($session->start_time)->format('g:i A') }} – {{ \Carbon\Carbon::parse($session->end_time)->format('g:i A') }}
                                </div>
                            </div>
                            <a href="{{ route('training.sessions.show', $session) }}" class="text-green-600 hover:text-green-800">
                                <i class="fas fa-arrow-right"></i>
                            </a>
                        </div>
                    @endforeach
                </div>
            @else
                <div class="text-center py-6 text-gray-500">
                    <i class="fas fa-calendar-check text-3xl mb-2 text-gray-300 block"></i>
                    <p class="text-sm">No sessions today</p>
                </div>
            @endif
        </div>

        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-5">
            <h3 class="font-semibold text-gray-800 mb-4 flex items-center gap-2">
                <i class="fas fa-calendar-week text-green-600"></i> This Week's Sessions
            </h3>
            @if($weekSessions->count() > 0)
                <div class="space-y-3 max-h-56 overflow-y-auto">
                    @foreach($weekSessions as $session)
                        <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition">
                            <div>
                                <div class="font-medium text-gray-800 text-sm">{{ $session->session_name }}</div>
                                <div class="text-xs text-gray-500">
                                    {{ $session->session_date->format('D, M d') }} at {{ \Carbon\Carbon::parse($session->start_time)->format('g:i A') }}
                                </div>
                            </div>
                            <a href="{{ route('training.sessions.show', $session) }}" class="text-green-600 hover:text-green-800">
                                <i class="fas fa-arrow-right"></i>
                            </a>
                        </div>
                    @endforeach
                </div>
            @else
                <div class="text-center py-6 text-gray-500">
                    <i class="fas fa-calendar-times text-3xl mb-2 text-gray-300 block"></i>
                    <p class="text-sm">No sessions this week</p>
                </div>
            @endif
        </div>
    </div>
</div>

</x-app-layout>

@push('scripts')
<script>
    const sessionsData = @json($sessions->map(function($s) {
        return [
            'id' => $s->id,
            'title' => $s->session_name,
            'date' => $s->session_date->format('Y-m-d'),
            'time' => \Carbon\Carbon::parse($s->start_time)->format('g:i A'),
            'status' => $s->status,
            'url' => route('training.sessions.show', $s),
            'package_id' => $s->training_package_id,
        ];
    }));

    // Global state — shared between Alpine component and external nav buttons
    let calendarState = {
        year: {{ $currentYear }},
        month: {{ $currentMonthNum }},
        selectedPackage: '',
        component: null,   // reference set by Alpine init()
    };

    function calendarComponent() {
        return {
            days: [],

            init() {
                calendarState.component = this;
                this.renderCalendar();
            },

            renderCalendar() {
                const year  = calendarState.year;
                const month = calendarState.month;

                const firstDay        = new Date(year, month - 1, 1);
                const lastDay         = new Date(year, month, 0);
                const startDay        = firstDay.getDay();
                const totalDays       = lastDay.getDate();
                const prevMonthLast   = new Date(year, month - 1, 0).getDate();

                const monthNames = [
                    'January','February','March','April','May','June',
                    'July','August','September','October','November','December'
                ];
                document.getElementById('currentMonth').textContent =
                    monthNames[month - 1] + ' ' + year;

                this.days = [];

                // Previous month overflow days
                for (let i = startDay - 1; i >= 0; i--) {
                    const d = prevMonthLast - i;
                    this.days.push(this._makeDay(d, this._fmt(year, month - 1, d), false));
                }

                // Current month days
                const today = new Date();
                for (let i = 1; i <= totalDays; i++) {
                    const isToday = today.getFullYear() === year
                        && today.getMonth() === month - 1
                        && today.getDate() === i;
                    this.days.push(this._makeDay(i, this._fmt(year, month, i), true, isToday));
                }

                // Next month overflow days (fill to 42 cells)
                const remaining = 42 - this.days.length;
                for (let i = 1; i <= remaining; i++) {
                    this.days.push(this._makeDay(i, this._fmt(year, month + 1, i), false));
                }
            },

            _makeDay(dayNumber, date, isCurrentMonth, isToday = false) {
                let sessions = sessionsData.filter(s => s.date === date);
                if (calendarState.selectedPackage) {
                    sessions = sessions.filter(s => s.package_id == calendarState.selectedPackage);
                }
                return { dayNumber, date, isCurrentMonth, isToday, sessions };
            },

            _fmt(year, month, day) {
                if (month < 1)  { month = 12; year--; }
                if (month > 12) { month = 1;  year++; }
                return `${year}-${String(month).padStart(2,'0')}-${String(day).padStart(2,'0')}`;
            }
        };
    }

    // External navigation helpers — Alpine v3 compatible (no __x internals)
    function previousMonth() {
        calendarState.month--;
        if (calendarState.month < 1) { calendarState.month = 12; calendarState.year--; }
        calendarState.component?.renderCalendar();
    }

    function nextMonth() {
        calendarState.month++;
        if (calendarState.month > 12) { calendarState.month = 1; calendarState.year++; }
        calendarState.component?.renderCalendar();
    }

    function goToToday() {
        const now = new Date();
        calendarState.year  = now.getFullYear();
        calendarState.month = now.getMonth() + 1;
        calendarState.component?.renderCalendar();
    }

    function filterByPackage(packageId) {
        calendarState.selectedPackage = packageId;
        calendarState.component?.renderCalendar();
    }
</script>
@endpush
