<x-app-layout>

<x-module-hero
    title="Partnership Portal"
    description="Manage organisational partners and collaborations"
    icon="fa-handshake">

    <x-slot name="tabs">
        @can('view partners')
        <a href="{{ route('partners.index') }}"
           class="module-hero-tab {{ request()->routeIs('partners.index') && !request()->routeIs('partners.forum.*') ? '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-building text-sm"></i> All Partners
        </a>
        @endcan
        @can('create partners')
        <a href="{{ route('partners.create') }}"
           class="module-hero-tab {{ request()->routeIs('partners.create') ? '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-plus text-sm"></i> Add Partner
        </a>
        @endcan
        @can('view forum')
        <a href="{{ route('partners.forum.index') }}"
           class="module-hero-tab {{ request()->routeIs('partners.forum.*') ? '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-comments text-sm"></i> Forum
        </a>
        @endcan
    </x-slot>

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

</x-module-hero>

{{-- Flash Messages --}}
<div class="px-6 pt-4">
    @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
    @if(session('error'))
        <div class="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded-lg flex items-center gap-2">
            <i class="fas fa-exclamation-circle"></i> {{ session('error') }}
        </div>
    @endif
</div>

{{-- Stats Row (managers only) --}}
@if(auth()->user()->hasAnyRole(['Super Manager','Manager']))
<div class="px-6 pb-4">
    <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex items-center gap-3">
            <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center flex-shrink-0">
                <i class="fas fa-building text-blue-600"></i>
            </div>
            <div>
                <p class="text-xs text-gray-500">Total</p>
                <p class="text-xl font-bold text-gray-900">{{ $stats['total'] }}</p>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex items-center gap-3">
            <div class="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center flex-shrink-0">
                <i class="fas fa-check-circle text-green-600"></i>
            </div>
            <div>
                <p class="text-xs text-gray-500">Active</p>
                <p class="text-xl font-bold text-gray-900">{{ $stats['active'] }}</p>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex items-center gap-3">
            <div class="w-10 h-10 bg-yellow-100 rounded-lg flex items-center justify-center flex-shrink-0">
                <i class="fas fa-clock text-yellow-600"></i>
            </div>
            <div>
                <p class="text-xs text-gray-500">Pending</p>
                <p class="text-xl font-bold text-gray-900">{{ $stats['pending'] }}</p>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex items-center gap-3">
            <div class="w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center flex-shrink-0">
                <i class="fas fa-exclamation-triangle text-orange-600"></i>
            </div>
            <div>
                <p class="text-xs text-gray-500">Expiring Soon</p>
                <p class="text-xl font-bold text-gray-900">{{ $stats['expiring_soon'] }}</p>
            </div>
        </div>
    </div>
</div>
@endif

{{-- Filters --}}
<div class="px-6 pb-4">
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4">
        <div class="flex flex-col md:flex-row gap-3">
            <div class="flex-1 relative">
                <input type="text"
                       id="partner-search"
                       value="{{ $filters['search'] ?? '' }}"
                       placeholder="Search partners... (results appear as you type)"
                       autocomplete="off"
                       class="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent transition">
                <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                <div id="search-spinner" class="hidden absolute right-3 top-1/2 -translate-y-1/2">
                    <i class="fas fa-circle-notch fa-spin text-blue-400 text-sm"></i>
                </div>
            </div>
            @if(auth()->user()->hasAnyRole(['Super Manager','Manager']))
            <select id="status-filter"
                    class="md:w-40 px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500">
                <option value="">All Status</option>
                <option value="active"    {{ ($filters['status'] ?? '') == 'active'    ? 'selected' : '' }}>Active</option>
                <option value="pending"   {{ ($filters['status'] ?? '') == 'pending'   ? 'selected' : '' }}>Pending</option>
                <option value="inactive"  {{ ($filters['status'] ?? '') == 'inactive'  ? 'selected' : '' }}>Inactive</option>
                <option value="suspended" {{ ($filters['status'] ?? '') == 'suspended' ? 'selected' : '' }}>Suspended</option>
            </select>
            <select id="type-filter"
                    class="md:w-44 px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500">
                <option value="">All Types</option>
                <option value="government"     {{ ($filters['type'] ?? '') == 'government'     ? 'selected' : '' }}>Government</option>
                <option value="ngo"            {{ ($filters['type'] ?? '') == 'ngo'            ? 'selected' : '' }}>NGO</option>
                <option value="private_sector" {{ ($filters['type'] ?? '') == 'private_sector' ? 'selected' : '' }}>Private Sector</option>
                <option value="academic"       {{ ($filters['type'] ?? '') == 'academic'       ? 'selected' : '' }}>Academic</option>
                <option value="healthcare"     {{ ($filters['type'] ?? '') == 'healthcare'     ? 'selected' : '' }}>Healthcare</option>
                <option value="international"  {{ ($filters['type'] ?? '') == 'international'  ? 'selected' : '' }}>International</option>
            </select>
            @endif
            @if(!empty($filters['search']) || !empty($filters['status']) || !empty($filters['type']))
                <a href="{{ route('partners.index') }}"
                   class="px-4 py-2.5 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition text-sm flex items-center gap-1.5">
                    <i class="fas fa-times"></i> Clear
                </a>
            @endif
        </div>
    </div>
</div>

{{-- Partners Table --}}
<div class="px-6 pb-6" id="partners-container">
    @include('partners.manage._partners_table', ['partners' => $partners])
</div>

@push('scripts')
<script>
const CSRF = document.querySelector('meta[name="csrf-token"]').content;
const searchInput  = document.getElementById('partner-search');
const spinner      = document.getElementById('search-spinner');
const container    = document.getElementById('partners-container');
const statusFilter = document.getElementById('status-filter');
const typeFilter   = document.getElementById('type-filter');

let searchTimeout;

function triggerSearch() {
    clearTimeout(searchTimeout);
    spinner?.classList.remove('hidden');
    searchTimeout = setTimeout(performSearch, 280);
}

searchInput?.addEventListener('input', triggerSearch);
statusFilter?.addEventListener('change', triggerSearch);
typeFilter?.addEventListener('change', triggerSearch);

function performSearch() {
    const q      = searchInput?.value.trim() ?? '';
    const status = statusFilter?.value ?? '';
    const type   = typeFilter?.value ?? '';

    const url = new URL(window.location.href.split('?')[0]);
    if (q)      url.searchParams.set('search', q);
    if (status) url.searchParams.set('status', status);
    if (type)   url.searchParams.set('type', type);
    url.searchParams.set('ajax', '1');

    fetch(url.toString(), {
        headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': CSRF }
    })
    .then(r => r.json())
    .then(data => {
        spinner?.classList.add('hidden');
        if (data.html) container.innerHTML = data.html;
    })
    .catch(() => spinner?.classList.add('hidden'));
}

function verifyPartner(partnerId) {
    if (!confirm('Verify this partner?')) return;
    fetch(`/api/partners/${partnerId}/verify`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF }
    }).then(r => r.json()).then(data => {
        if (data.success) { window.showToast?.(data.message, 'success'); setTimeout(() => location.reload(), 1000); }
        else { window.showToast?.(data.message || 'Failed', 'error'); }
    }).catch(() => window.showToast?.('An error occurred.', 'error'));
}
</script>
@endpush

</x-app-layout>
