@extends('Template::layouts.frontend')
@section('content')
    <section class="domains my-120">
        <div class="container">
            <div class="row gy-4">
                <div class="col-lg-4 col-xl-3">
                    <div class="offcanvas-lg offcanvas-end filter--offcanvas" tabindex="-1" id="filter-offcanvas">
                        <div class="offcanvas-header">
                            <h5 class="offcanvas-title">@lang('Filter Domains')</h5>
                            <button type="button" class="btn btn--icon btn-soft--secondary btn--sm btn--close" data-bs-dismiss="offcanvas" data-bs-target="#filter-offcanvas" aria-label="Close"></button>
                        </div>
                        <div class="offcanvas-body">
                            <form class="filter-form" id="filterForm">
                                <div class="filter-form-block">
                                    <div class="filter-form-block__header">
                                        <h6 class="filter-form-block__title">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-sparkle-icon lucide-sparkle">
                                                <path d="M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z" />
                                            </svg>
                                            @lang('Price Range')
                                        </h6>
                                    </div>

                                    <div class="filter-form-block__body">
                                        <div class="range-slider" data-min="{{ getAmount($minPrice) }}" data-max="{{ getAmount($maxPrice) }}" data-min-default="{{ getAmount($minPrice) }}" data-max-default="{{ getAmount($maxPrice) }}">
                                            <div class="range-slider__slide"></div>
                                            <div class="range-slider__inputs amount__field">
                                                <div class="input-group">
                                                    <span class="input-group-text">@lang('Min') $</span>
                                                    <input id="min-range" class="form--control" type="number" name="min_price" value="{{ getAmount($minPrice) }}" placeholder="@lang('Min'): {{ $minPrice }}" min="{{ $minPrice }}" max="{{ $maxPrice }}">
                                                </div>

                                                <div class="input-group">
                                                    <span class="input-group-text">@lang('Max') $</span>
                                                    <input id="max-range" class="form--control" type="number" name="max_price" value="{{ getAmount($maxPrice) }}" placeholder="@lang('Max'): {{ $maxPrice }}" min="{{ $minPrice }}" max="{{ $maxPrice }}">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="filter-form-block">
                                    <div class="filter-form-block__header">
                                        <h6 class="filter-form-block__title">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-sparkle-icon lucide-sparkle">
                                                <path d="M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z" />
                                            </svg>
                                            @lang('Domain Extensions')
                                        </h6>
                                    </div>
                                    <div class="filter-form-block__body">
                                        <div class="form--group">
                                            <div class="form--check">
                                                <input class="form-check-input" type="checkbox" name="" id="all-checkbox" checked>
                                                <label class="form-check-label" for="all-checkbox">@lang('All')</label>
                                            </div>
                                        </div>

                                        @foreach ($extensions as $item)
                                            <div class="form--group">
                                                <div class="form--check">
                                                    <input class="form-check-input myExtention" type="checkbox" name="extension" id="chekbox-{{ $item->id }}" value="{{ __($item->name) }}">
                                                    <label class="form-check-label" for="chekbox-{{ $item->id }}">{{ __($item->name) }} </label>
                                                </div>
                                            </div>
                                        @endforeach
                                    </div>
                                </div>
                                <div class="filter-form-block">
                                    <div class="filter-form-block__header">
                                        <h6 class="filter-form-block__title">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-sparkle-icon lucide-sparkle">
                                                <path d="M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z" />
                                            </svg>
                                            @lang('Listing Sort')
                                        </h6>
                                    </div>
                                    <div class="filter-form-block__body">
                                        <div class="form--group">
                                            <div class="form--check">
                                                <input class="form-check-input action-widget__title list_short" type="radio" name="list_sort" id="all" value="" checked>
                                                <label class="form-check-label" for="all">@lang('All')</label>
                                            </div>
                                        </div>
                                        <div class="form--group">
                                            <div class="form--check">
                                                <input class="form-check-input list_short" type="radio" name="list_sort" id="sort2" value="id_desc">
                                                <label class="form-check-label" for="sort2">@lang('Newly Listed')</label>
                                            </div>
                                        </div>
                                        <div class="form--group">
                                            <div class="form--check">
                                                <input class="form-check-input list_short" type="radio" name="list_sort" id="sort3" value="id_asc">
                                                <label class="form-check-label" for="sort3">@lang('Ending Soon')</label>
                                            </div>
                                        </div>
                                        <div class="form--group">
                                            <div class="form--check">
                                                <input class="form-check-input list_short" type="radio" name="list_sort" id="sort4" value="price_asc">
                                                <label class="form-check-label" for="sort4">@lang('Low to High')</label>
                                            </div>
                                        </div>
                                        <div class="form--group">
                                            <div class="form--check">
                                                <input class="form-check-input list_short" type="radio" name="list_sort" id="sort5" value="price_desc">
                                                <label class="form-check-label" for="sort5">@lang('High to Low')</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <div class="col-lg-8 col-xl-9">
                    <div class="domains-main">
                        <div class="domains-main__header">
                            <div class="filter-toolbar">
                                <div class="filter-toolbar__left">
                                    <h6 class="filter-toolbar__title">
                                        @lang('Available Domains')
                                    </h6>
                                </div>
                                <div class="filter-toolbar__right">
                                    <form class="search-form">
                                        <div class="input-group input--group input--group-submit">
                                            <input class="form-control form--control mySearch" name="search" value="{{ request()->search }}" type="text" placeholder="@lang('Type to search')">
                                            <button type="button" class="input-group-text searchBtn">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-search-icon lucide-search">
                                                    <path d="m21 21-4.34-4.34" />
                                                    <circle cx="11" cy="11" r="8" />
                                                </svg>
                                            </button>
                                        </div>
                                    </form>

                                    <select class="form--select select2 form--select DomainPaginate" data-minimum-results-for-search="-1" data-placeholder="Showing 20 Items">
                                        <option value="" selected disabled>@lang('Select One')</option>
                                        <option value="5">@lang('5') @lang('items per page')</option>
                                        <option value="10">@lang('10') @lang('items per page')</option>
                                        <option value="20">@lang('20') @lang('items per page')</option>
                                        <option value="40">@lang('40') @lang('items per page')</option>
                                        <option value="60">@lang('60') @lang('items per page')</option>
                                        <option value="80">@lang('80') @lang('items per page')</option>
                                        <option value="100">@lang('100') @lang('items per page')</option>
                                    </select>
                                    <button class="filter-toolbar__btn d-lg-none" type="button" data-bs-toggle="offcanvas" data-bs-target="#filter-offcanvas">
                                        <i class="fa-solid fa-filter"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="domains-main__body">
                            <div class="loader d-none">
                                <span class="loader__spinner"></span>
                            </div>
                            <div class="row gy-4" id="showDomain">
                                @include('Template::domain.partials.domain_list')
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
@endsection

@push('script-lib')
    <script src="{{ asset('assets/global/js/jquery-ui.min.js') }}"></script>
@endpush

@push('script')
    <script>
        (function($) {
            'use strict';

            let page = null;
            var defaultPaginate = {{ getPaginate() }};
            $('.DomainPaginate').val(defaultPaginate);

            $('.action-sidebar-open').on('click', function() {
                $('.action-sidebar').addClass('active');
            });

            $('.action-sidebar-close').on('click', function() {
                $('.action-sidebar').removeClass('active');
            });

            $('.action-widget__title').each(function() {
                let ele = $(this).siblings('.action-widget__body');
                $(this).on('click', function() {
                    ele.slideToggle();
                });
            });

            let isInitialLoad = true;
            $('.range-slider__slide').each(function() {
                var rangeSlider = $(this);

                var maxValue = rangeSlider.attr('data-max');
                $(rangeSlider).slider({
                    range: true,
                    min: {{ $minPrice }},
                    max: {{ $maxPrice }},
                    values: [{{ $minPrice }}, {{ $maxPrice }}],
                    slide: function(event, ui) {
                        $('input[name=min_price]').val(ui.values[0]);
                        $('input[name=max_price]').val(ui.values[1]);
                    },
                    change: function() {
                        if (!isInitialLoad) {
                            page = null;
                            fetchDomain();
                        }
                    }

                });
            });


            $('.myExtention, #all-checkbox, .list_short, .searchBtn').on('click', function() {
                page = null;

                const $allCheckbox = $('#all-checkbox');
                const $extensions = $("input[type='checkbox'][name='extension']");

                if (this.id === 'all-checkbox') {
                    if ($allCheckbox.is(':checked')) {
                        $extensions.prop('checked', false);
                    }
                }

                if ($(this).hasClass('myExtention')) {
                    if ($(this).is(':checked')) {
                        $allCheckbox.prop('checked', false);
                    }
                }

                if ($extensions.filter(':checked').length === 0) {
                    $allCheckbox.prop('checked', true);
                }

                fetchDomain();
            });


            $('.DomainPaginate').on('change', function(e) {
                page = null;
                fetchDomain();
            });

            function fetchDomain() {
                $('.loader').removeClass('d-none');
                $('#showDomain').html('');
                let data = {};
                data.sort = $("input[type='radio'][name='list_sort']:checked").val();
                data.min = $('input[name="min_price"]').val();
                data.max = $('input[name="max_price"]').val();
                data.search = $('.mySearch').val();
                var paginateVal = $('.DomainPaginate').val();
                data.paginateValue = paginateVal ? paginateVal : defaultPaginate;

                data.extensions = [];

                $.each($("input[name=extension]:checked"), function() {
                    if ($(this).val()) {
                        data.extensions.push($(this).val());
                    }
                });

                if (page) {
                    data.page = page;
                }

                let url = `{{ route('domain.filter') }}`;

                updateURLParameters(data);

                $.ajax({
                    method: "get",
                    url: url,
                    data: data,
                    success: function(response) {
                        $('#showDomain').html(response);
                        var domainCount = $('#showDomain .domain-card').length;
                        $('.loader').addClass('d-none');
                        isInitialLoad = false;
                    },
                    error: function(xhr, status, error) {
                        console.error('AJAX Error:', error);
                    }
                });
            }

            function updateURLParameters(data) {
                const url = new URL(window.location);
                url.search = '';

                if (data.page) {
                    url.searchParams.set('page', data.page);
                }

                if (data.search) {
                    url.searchParams.set('search', data.search);
                }

                if (data.sort) {
                    url.searchParams.set('sort', data.sort);
                }

                // Only add price parameters if they're different from defaults
                if (data.min && parseInt(data.min) !== {{ $minPrice }}) {
                    url.searchParams.set('min', data.min);
                }
                if (data.max && parseInt(data.max) !== {{ $maxPrice }}) {
                    url.searchParams.set('max', data.max);
                }

                if (data.extensions && data.extensions.length > 0) {
                    url.searchParams.set('extensions', data.extensions.join(','));
                }

                if (data.paginateValue && data.paginateValue != defaultPaginate) {
                    url.searchParams.set('perPage', data.paginateValue);
                }

                window.history.pushState({}, '', url);
            }

            function loadFiltersFromURL() {
                const params = new URLSearchParams(window.location.search);
                let shouldFetch = false;

                // Temporarily disable slider change events
                isInitialLoad = true;

                // Load search
                if (params.has('search') && params.get('search')) {
                    $('.mySearch').val(params.get('search'));
                    shouldFetch = true;
                }

                // Load sort
                if (params.has('sort') && params.get('sort')) {
                    $("input[type='radio'][name='list_sort'][value='" + params.get('sort') + "']").prop('checked', true);
                    shouldFetch = true;
                }

                // Load price range - update UI but don't trigger fetch
                var hasCustomPrice = false;
                if (params.has('min')) {
                    var minVal = params.get('min');
                    $('input[name="min_price"]').val(minVal);
                    hasCustomPrice = true;
                }
                if (params.has('max')) {
                    var maxVal = params.get('max');
                    $('input[name="max_price"]').val(maxVal);
                    hasCustomPrice = true;
                }

                // Update slider if custom price range
                if (hasCustomPrice) {
                    var sliderMin = params.get('min') || {{ $minPrice }};
                    var sliderMax = params.get('max') || {{ $maxPrice }};
                    $('.range-slider__slide').slider('values', [sliderMin, sliderMax]);
                }

                // Load extensions
                if (params.has('extensions') && params.get('extensions')) {
                    var extensions = params.get('extensions').split(',');
                    $('#all-checkbox').prop('checked', false);
                    extensions.forEach(function(ext) {
                        $("input[name='extension'][value='" + ext + "']").prop('checked', true);
                    });
                    shouldFetch = true;
                }

                // Load pagination
                if (params.has('perPage') && params.get('perPage') != defaultPaginate) {
                    $('.DomainPaginate').val(params.get('perPage'));
                    shouldFetch = true;
                }

                // Load page number
                if (params.has('page') && params.get('page') != '1') {
                    page = params.get('page');
                    shouldFetch = true;
                }

                // Only fetch if there are actual filters applied (excluding price)
                if (shouldFetch) {
                    fetchDomain();
                }

                // Re-enable slider change events after initial load
                setTimeout(() => {
                    isInitialLoad = false;
                }, 100);
            }

            // Add this to handle manual interactions with price inputs
            $('input[name="min_price"], input[name="max_price"]').on('change', function() {
                if (!isInitialLoad) {
                    var minVal = parseInt($('input[name="min_price"]').val()) || {{ $minPrice }};
                    var maxVal = parseInt($('input[name="max_price"]').val()) || {{ $maxPrice }};

                    // Update slider
                    $('.range-slider__slide').slider('values', [minVal, maxVal]);

                    // Trigger fetch
                    page = null;
                    fetchDomain();
                }
            });

            $(document).on('click', '.pagination a', function(event) {
                event.preventDefault();

                var href = $(this).attr('href');
                if (href && href.indexOf('page=') !== -1) {
                    page = href.split('page=')[1];
                    fetchDomain();
                }
            });

            loadFiltersFromURL();

        })(jQuery);
    </script>
@endpush
