<x-app-layout>
    <x-module-hero
        title="{{ isset($isOwnOnly) && $isOwnOnly ? 'My Applications' : 'Mentorship Applications' }}"
        description="{{ isset($isOwnOnly) && $isOwnOnly ? 'View and track your own mentorship programme applications' : 'Review and manage mentorship programme applications' }}"
        icon="fa-file-alt">

        <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
            @canany(['view mentorship applications', '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> {{ (isset($isOwnOnly) && $isOwnOnly) ? 'My Applications' : 'Applications' }}
                </a>
            @endcanany
            @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 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 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('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('view mentorship applications')
                <a href="{{ route('mentorship.applications.export', $filters) }}"
                   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-download"></i> Export
                </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

        {{-- Filters --}}
        <div class="bg-white rounded-lg border border-gray-200 p-4 mb-4">
            <form method="GET" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
                <div>
                    <label class="block text-xs font-medium text-gray-600 mb-1">Status</label>
                    <select name="status" class="w-full border-gray-300 rounded-lg text-sm focus:ring-green-500 focus:border-green-500">
                        <option value="">All Status</option>
                        <option value="pending" {{ $filters['status'] === 'pending' ? 'selected' : '' }}>Pending</option>
                        <option value="under_review" {{ $filters['status'] === 'under_review' ? 'selected' : '' }}>Under Review</option>
                        <option value="approved" {{ $filters['status'] === 'approved' ? 'selected' : '' }}>Approved</option>
                        <option value="rejected" {{ $filters['status'] === 'rejected' ? 'selected' : '' }}>Rejected</option>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-600 mb-1">Programme</label>
                    <select name="programme_id" class="w-full border-gray-300 rounded-lg text-sm focus:ring-green-500 focus:border-green-500">
                        <option value="">All Programmes</option>
                        @foreach($programmes as $programme)
                            <option value="{{ $programme->id }}" {{ $filters['programme_id'] == $programme->id ? 'selected' : '' }}>
                                {{ $programme->title }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-600 mb-1">Role</label>
                    <select name="role_preference" class="w-full border-gray-300 rounded-lg text-sm focus:ring-green-500 focus:border-green-500">
                        <option value="">All Roles</option>
                        <option value="mentor" {{ $filters['role_preference'] === 'mentor' ? 'selected' : '' }}>Mentor</option>
                        <option value="mentee" {{ $filters['role_preference'] === 'mentee' ? 'selected' : '' }}>Mentee</option>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-600 mb-1">Search</label>
                    <input type="text" name="search" value="{{ $filters['search'] }}"
                           placeholder="Name or email..."
                           class="w-full border-gray-300 rounded-lg text-sm focus:ring-green-500 focus:border-green-500">
                </div>
                <div class="flex items-end gap-2">
                    <button type="submit" class="px-4 py-2 bg-green-600 text-white text-sm rounded-lg hover:bg-green-700 transition">
                        <i class="fas fa-search mr-1"></i> Filter
                    </button>
                    <a href="{{ route('mentorship.applications.index') }}"
                       class="px-4 py-2 bg-gray-200 text-gray-700 text-sm rounded-lg hover:bg-gray-300 transition">
                        <i class="fas fa-times"></i>
                    </a>
                </div>
            </form>
        </div>

        {{-- Table --}}
        <div class="w-full overflow-x-auto">
            @if($applications->count() > 0)
                <table class="w-full table-zebra">
                    <thead>
                        <tr>
                            <th class="th-col-1 px-4 py-3 text-left">
                                <input type="checkbox" id="select-all" class="w-4 h-4">
                            </th>
                            <th class="th-col-2 px-4 py-3 text-left">Applicant</th>
                            <th class="th-col-3 px-4 py-3 text-left">Programme</th>
                            <th class="th-col-4 px-4 py-3 text-left">Role</th>
                            <th class="th-col-5 px-4 py-3 text-left">Status</th>
                            <th class="th-col-6 px-4 py-3 text-left">Payment</th>
                            <th class="th-col-7 px-4 py-3 text-left">Applied</th>
                            <th class="th-col-8 px-4 py-3 text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($applications as $application)
                            <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                                <td class="px-4 py-3">
                                    <input type="checkbox" name="selected[]" value="{{ $application->id }}"
                                           class="w-4 h-4 application-checkbox">
                                </td>
                                <td class="px-4 py-3">
                                    <div class="font-medium text-gray-900 text-sm">{{ $application->name }}</div>
                                    <div class="text-xs text-gray-500">{{ $application->email }}</div>
                                </td>
                                <td class="px-4 py-3 text-sm text-gray-600">{{ $application->programme->title ?? 'N/A' }}</td>
                                <td class="px-4 py-3">
                                    <span class="px-2 py-0.5 rounded-full text-xs font-semibold
                                        @if($application->role_preference === 'mentor') bg-purple-100 text-purple-800
                                        @else bg-blue-100 text-blue-800 @endif">
                                        {{ ucfirst($application->role_preference) }}
                                    </span>
                                </td>
                                <td class="px-4 py-3">
                                    <span class="px-2 py-0.5 rounded-full text-xs font-semibold
                                        @if($application->status === 'approved') bg-green-100 text-green-800
                                        @elseif($application->status === 'rejected') bg-red-100 text-red-800
                                        @elseif($application->status === 'pending') bg-yellow-100 text-yellow-800
                                        @else bg-gray-100 text-gray-800 @endif">
                                        {{ ucfirst(str_replace('_', ' ', $application->status)) }}
                                    </span>
                                </td>
                                <td class="px-4 py-3">
                                    @if($application->payment_required)
                                        <span class="px-2 py-0.5 rounded-full text-xs font-semibold
                                            @if($application->payment_status === 'paid') bg-green-100 text-green-800
                                            @elseif($application->payment_status === 'pending') bg-yellow-100 text-yellow-800
                                            @else bg-red-100 text-red-800 @endif">
                                            {{ ucfirst($application->payment_status ?? 'unpaid') }}
                                        </span>
                                    @else
                                        <span class="text-gray-400 text-xs">N/A</span>
                                    @endif
                                </td>
                                <td class="px-4 py-3 text-xs text-gray-500">{{ $application->created_at->format('M d, Y') }}</td>
                                <td class="px-4 py-3">
                                    <div class="flex justify-center gap-1">
                                        @can('view mentorship applications')
                                            <a href="{{ route('mentorship.applications.show', $application) }}" class="btn-action-view">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                        @endcan
                                        @can('review mentorship applications')
                                            <a href="{{ route('mentorship.applications.review', $application) }}" class="btn-action-assign">
                                                <i class="fas fa-clipboard-check"></i>
                                            </a>
                                        @endcan
                                        @can('approve mentorship applications')
                                            @if(in_array($application->status, ['pending', 'under_review']))
                                                <button onclick="approveApplication({{ $application->id }})" class="btn-action-approve">
                                                    <i class="fas fa-check"></i>
                                                </button>
                                            @endif
                                        @endcan
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
                <div class="px-4 py-3 border-t border-gray-200 flex justify-between items-center">
                    <div class="flex gap-2">
                        @can('approve mentorship applications')
                            <button onclick="bulkApprove()" class="btn-action-approve">
                                <i class="fas fa-check mr-1"></i> Bulk Approve
                            </button>
                        @endcan
                    </div>
                    {{ $applications->appends($filters)->links() }}
                </div>
            @else
                <div class="text-center py-16">
                    <i class="fas fa-file-alt text-gray-300 text-5xl mb-4"></i>
                    <h3 class="text-lg font-medium text-gray-900 mb-2">No Applications Found</h3>
                    <p class="text-gray-500">Applications will appear here once submitted.</p>
                </div>
            @endif
        </div>
    </div>

    @push('scripts')
    <script>
        document.getElementById('select-all')?.addEventListener('change', function() {
            document.querySelectorAll('.application-checkbox').forEach(cb => cb.checked = this.checked);
        });
        function approveApplication(id) {
            if (!confirm('Approve this application?')) return;
            fetch(`/mentorship/applications/${id}/approve`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content }
            }).then(r => r.json()).then(d => { if (d.success) location.reload(); else alert(d.message || 'Error'); });
        }
        function bulkApprove() {
            const selected = Array.from(document.querySelectorAll('.application-checkbox:checked')).map(cb => parseInt(cb.value));
            if (selected.length === 0) { alert('Please select applications to approve'); return; }
            if (!confirm(`Approve ${selected.length} applications?`)) return;
            fetch("{{ route('mentorship.applications.bulk-approve') }}", {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
                body: JSON.stringify({ application_ids: selected })
            }).then(r => r.json()).then(d => { if (d.success) { alert(d.message); location.reload(); } else alert(d.message || 'Error'); });
        }
    </script>
    @endpush
</x-app-layout>
