<x-app-layout>
    <x-module-hero
        title="Sessions Calendar"
        description="View all mentorship sessions in calendar format"
        icon="fa-calendar">

        <x-slot name="tabs">
            @can('view mentorship programmes')
                <a href="{{ route('mentorship.programmes.index') }}"
                   class="module-hero-tab {{ request()->routeIs('mentorship.programmes.*') ? '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> Programmes
                </a>
            @endcan
            @can('view mentorship applications')
                <a href="{{ route('mentorship.applications.index') }}"
                   class="module-hero-tab {{ request()->routeIs('mentorship.applications.*') ? '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-file-alt text-sm"></i> Applications
                </a>
            @endcan
            @cannot('view mentorship applications')
                @can('view own mentorship applications')
                    <a href="{{ route('mentorship.applications.index') }}"
                       class="module-hero-tab {{ request()->routeIs('mentorship.applications.*') ? '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-file-alt text-sm"></i> My Applications
                    </a>
                @endcan
            @endcannot
            @can('view mentorship sessions')
                <a href="{{ route('mentorship.sessions.index') }}"
                   class="module-hero-tab {{ request()->routeIs('mentorship.sessions.index') || request()->routeIs('mentorship.sessions.show') || request()->routeIs('mentorship.sessions.create') || request()->routeIs('mentorship.sessions.edit') ? '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> Sessions
                </a>
                <a href="{{ route('mentorship.sessions.calendar') }}"
                   class="module-hero-tab {{ request()->routeIs('mentorship.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 text-sm"></i> Sessions Calendar
                </a>
            @endcan
            @can('view mentorship assignments')
                <a href="{{ route('mentorship.assignments.index') }}"
                   class="module-hero-tab {{ request()->routeIs('mentorship.assignments.*') ? '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-link text-sm"></i> Assignments
                </a>
            @endcan
            @can('view mentorship certificates')
                <a href="{{ route('mentorship.certificates.index') }}"
                   class="module-hero-tab {{ request()->routeIs('mentorship.certificates.*') ? '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('download mentorship certificates')
                @cannot('view mentorship certificates')
                    <a href="{{ route('mentorship.certificates.my-certificates') }}"
                       class="module-hero-tab {{ request()->routeIs('mentorship.certificates.my-certificates') ? '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-award text-sm"></i> My Certificates
                    </a>
                @endcannot
            @endcan
            @can('view mentorship payments')
                <a href="{{ route('mentorship.payments.index') }}"
                   class="module-hero-tab {{ request()->routeIs('mentorship.payments.*') ? '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-credit-card text-sm"></i> Payments
                </a>
            @endcan
            @can('view own mentorship payments')
                @cannot('view mentorship payments')
                    <a href="{{ route('mentorship.payments.my-payments') }}"
                       class="module-hero-tab {{ request()->routeIs('mentorship.payments.my-payments') ? '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-history text-sm"></i> My Payments
                    </a>
                @endcannot
            @endcan
            @can('view mentorship categories')
                <a href="{{ route('mentorship.categories.index') }}"
                   class="module-hero-tab {{ request()->routeIs('mentorship.categories.*') ? '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-folder text-sm"></i> Categories
                </a>
            @endcan
        </x-slot>

        <x-slot name="actions">
            @can('create mentorship sessions')
                <a href="{{ route('mentorship.sessions.create') }}"
                   class="inline-flex items-center gap-2 px-4 py-2 bg-white text-green-800 text-sm font-medium rounded hover:bg-green-50 transition-colors">
                    <i class="fas fa-plus"></i> Schedule Session
                </a>
            @endcan
        </x-slot>
    </x-module-hero>

    <div class="p-6">
        @if(session('success'))
            <div class="mb-4 p-4 bg-green-100 border border-green-400 text-green-700 rounded-lg flex items-center gap-2">
                <i class="fas fa-check-circle"></i> {{ session('success') }}
            </div>
        @endif

        {{-- Legend --}}
        <div class="bg-white rounded-lg border border-gray-200 p-4 mb-4">
            <div class="flex flex-wrap items-center gap-4 text-sm">
                <span class="font-medium text-gray-700">Legend:</span>
                <div class="flex items-center gap-2"><span class="w-3 h-3 rounded-full bg-blue-500 inline-block"></span><span class="text-gray-600">Scheduled</span></div>
                <div class="flex items-center gap-2"><span class="w-3 h-3 rounded-full bg-green-500 inline-block"></span><span class="text-gray-600">Completed</span></div>
                <div class="flex items-center gap-2"><span class="w-3 h-3 rounded-full bg-purple-500 inline-block"></span><span class="text-gray-600">Online</span></div>
                <div class="flex items-center gap-2"><span class="w-3 h-3 rounded-full bg-pink-500 inline-block"></span><span class="text-gray-600">In Person</span></div>
            </div>
        </div>

        {{-- Calendar --}}
        <div class="bg-white rounded-lg border border-gray-200 overflow-hidden mb-4">
            <div id="calendar" class="p-4"></div>
        </div>

        {{-- Quick Stats --}}
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div class="bg-white rounded-lg border border-gray-200 p-4">
                <div class="flex items-center gap-3">
                    <div class="p-2 bg-blue-100 rounded-lg"><i class="fas fa-clock text-blue-600"></i></div>
                    <div>
                        <p class="text-xs text-gray-500">Upcoming</p>
                        <p class="text-xl font-bold text-gray-900" id="upcomingCount">—</p>
                    </div>
                </div>
            </div>
            <div class="bg-white rounded-lg border border-gray-200 p-4">
                <div class="flex items-center gap-3">
                    <div class="p-2 bg-green-100 rounded-lg"><i class="fas fa-check text-green-600"></i></div>
                    <div>
                        <p class="text-xs text-gray-500">This Month</p>
                        <p class="text-xl font-bold text-gray-900" id="monthCount">—</p>
                    </div>
                </div>
            </div>
            <div class="bg-white rounded-lg border border-gray-200 p-4">
                <div class="flex items-center gap-3">
                    <div class="p-2 bg-purple-100 rounded-lg"><i class="fas fa-video text-purple-600"></i></div>
                    <div>
                        <p class="text-xs text-gray-500">Online</p>
                        <p class="text-xl font-bold text-gray-900" id="onlineCount">—</p>
                    </div>
                </div>
            </div>
            <div class="bg-white rounded-lg border border-gray-200 p-4">
                <div class="flex items-center gap-3">
                    <div class="p-2 bg-pink-100 rounded-lg"><i class="fas fa-building text-pink-600"></i></div>
                    <div>
                        <p class="text-xs text-gray-500">In Person</p>
                        <p class="text-xl font-bold text-gray-900" id="inPersonCount">—</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- Session Detail Modal --}}
    <div id="sessionModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex items-center justify-center">
        <div class="bg-white rounded-lg shadow-xl max-w-lg w-full mx-4 overflow-hidden">
            <div class="flex items-center justify-between px-6 py-4 bg-gradient-to-r from-green-800 to-green-700">
                <h3 class="text-base font-semibold text-white flex items-center gap-2" id="modalTitle">
                    <i class="fas fa-calendar-alt"></i> Session Details
                </h3>
                <button onclick="document.getElementById('sessionModal').classList.add('hidden')" class="text-white/80 hover:text-white transition">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="p-6" id="modalContent"></div>
            <div class="bg-gray-50 px-6 py-4 flex justify-end gap-3">
                <button onclick="document.getElementById('sessionModal').classList.add('hidden')"
                        class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 text-sm">Close</button>
                <a id="modalViewBtn" href="#" class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 text-sm">
                    View Session
                </a>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const calendarEl = document.getElementById('calendar');
            const calendar = new Calendar(calendarEl, {
                plugins: [dayGridPlugin, timeGridPlugin, listPlugin],
                initialView: 'dayGridMonth',
                headerToolbar: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
                },
                height: 'auto',
                nowIndicator: true,
                dayMaxEvents: true,
                eventClick: function(info) {
                    showSessionDetails(info.event);
                },
                events: function(info, successCallback, failureCallback) {
                    fetch(`{{ route('mentorship.sessions.calendar.events') }}?start=${info.startStr}&end=${info.endStr}`, {
                        headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
                    })
                    .then(r => r.json())
                    .then(data => {
                        updateStats(data);
                        successCallback(data.map(e => ({
                            id: e.id,
                            title: e.title,
                            start: e.start,
                            end: e.end,
                            backgroundColor: e.type === 'online' ? '#8b5cf6' : '#ec4899',
                            borderColor: e.type === 'online' ? '#7c3aed' : '#db2777',
                            extendedProps: e
                        })));
                    })
                    .catch(failureCallback);
                }
            });
            calendar.render();
        });

        function updateStats(events) {
            const now = new Date();
            const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
            const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);
            let upcoming = 0, thisMonth = 0, online = 0, inPerson = 0;
            events.forEach(e => {
                const d = new Date(e.start);
                if (d > now) upcoming++;
                if (d >= startOfMonth && d <= endOfMonth) thisMonth++;
                if (e.type === 'online') online++; else inPerson++;
            });
            document.getElementById('upcomingCount').textContent = upcoming;
            document.getElementById('monthCount').textContent = thisMonth;
            document.getElementById('onlineCount').textContent = online;
            document.getElementById('inPersonCount').textContent = inPerson;
        }

        function showSessionDetails(event) {
            const p = event.extendedProps;
            document.getElementById('modalTitle').textContent = event.title;
            document.getElementById('modalContent').innerHTML = `
                <div class="space-y-3 text-sm">
                    <div class="grid grid-cols-2 gap-3">
                        <div><p class="text-xs text-gray-500">Programme</p><p class="font-medium">${p.programme_name || 'N/A'}</p></div>
                        <div><p class="text-xs text-gray-500">With</p><p class="font-medium">${p.other_person_name || 'N/A'}</p></div>
                    </div>
                    <div><p class="text-xs text-gray-500">Date & Time</p>
                        <p class="font-medium">${new Date(event.start).toLocaleDateString('en-US', {weekday:'long',year:'numeric',month:'long',day:'numeric'})}</p>
                        <p class="text-xs text-gray-500">${new Date(event.start).toLocaleTimeString('en-US',{hour:'2-digit',minute:'2-digit'})} – ${new Date(event.end).toLocaleTimeString('en-US',{hour:'2-digit',minute:'2-digit'})}</p>
                    </div>
                    ${p.meeting_link ? `<div><p class="text-xs text-gray-500">Meeting Link</p><a href="${p.meeting_link}" target="_blank" class="text-blue-600 hover:text-blue-800"><i class="fas fa-external-link-alt mr-1"></i>Join Meeting</a></div>` : ''}
                    ${p.venue ? `<div><p class="text-xs text-gray-500">Venue</p><p class="font-medium">${p.venue}</p></div>` : ''}
                </div>
            `;
            document.getElementById('modalViewBtn').href = p.url || '#';
            document.getElementById('sessionModal').classList.remove('hidden');
        }

        document.addEventListener('keydown', e => { if (e.key === 'Escape') document.getElementById('sessionModal').classList.add('hidden'); });
        document.getElementById('sessionModal').addEventListener('click', function(e) { if (e.target === this) this.classList.add('hidden'); });
    </script>
    @endpush
</x-app-layout>
