@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-12">
            <div class="locations-grid">
                @include('partials.location-list')
            </div>

            @if($locations->hasMorePages())
                <div class="text-center mt-4">
                    <button id="load-more" class="btn btn-primary">
                        {{ $loadMoreText }}
                    </button>
                </div>
            @endif
        </div>
    </div>
</div>

@push('scripts')
<script>
    $(document).ready(function() {
        let currentPage = 1;
        let isLoading = false;

        $('#load-more').click(function() {
            if (isLoading) return;

            isLoading = true;
            currentPage++;

            const $button = $(this);
            const $spinner = $('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>');
            const originalText = $button.text();

            $button.prop('disabled', true).html($spinner);

            // دریافت پارامترهای فیلتر از URL
            const urlParams = new URLSearchParams(window.location.search);
            const filters = {};
            for (const [key, value] of urlParams.entries()) {
                if (key !== 'page') {
                    filters[key] = value;
                }
            }

            // اضافه کردن شماره صفحه
            filters.page = currentPage;

            $.get('{{ route("locations.index") }}', filters)
                .done(function(response) {
                    $('.locations-grid').append(response.html);

                    if (!response.hasMorePages) {
                        $button.parent().remove();
                    }
                })
                .fail(function() {
                    alert('خطا در بارگذاری مکان‌های بیشتر');
                })
                .always(function() {
                    isLoading = false;
                    $button.prop('disabled', false).text(originalText);
                });
        });
    });
</script>
@endpush
@endsection