$("#data-filter-container").exists(function(){
    $(document).ready(function() {
        $('.preloader-wrapper').show();
        $('#data-filter-container').hide();

        function initIsotopeAfterImagesLoaded() {
            // Wait for all images to load
            // $('#data-filter-container').imagesLoaded(function() {
                // Initialize Isotope after images are loaded
                $dataGrid = $('#data-filter-container').isotope({
                    itemSelector: '.data-content',
                    transitionDuration: 0,
                    visibleStyle: { transform: 'translateY(0)', opacity: 1 },
                    hiddenStyle: { transform: 'translateY(100px)', opacity: 0 },
                    layoutMode: 'fitRows',
                    getSortData: {
                        kapasitas: function(itemElem) {
                            var kapasitas = parseInt($(itemElem).find('.kapasitas').data('value-kapasitas'));
                            return kapasitas;
                        },
                        hotel: function(itemElem) {
                            var hotel = $(itemElem).find('.namaHotel').text();
                            return hotel;
                        },
                        kabupaten: function(itemElem) {
                            var kabupaten = $(itemElem).find('.alamat').data('value-kabupaten');
                            return kabupaten;
                        },
                    },
                    sortBy: 'kapasitas',
                    sortAscending: false
                });

                dataUpdatePagination();
                $dataGrid.isotope('layout');
                $('.preloader-wrapper').hide();

                $('#data-filter-container').show();
            // });
        }

        $.ajax({
            url: 'site/meetingrooms',
            dataType: 'json',
            success: function(json) {
                $('.preloader-wrapper').hide();
                $('#data-filter-container').show();

                var dataJSON = json.RECORDS;
                var $dataItems = [];

                for (var dataCounter = 0; dataCounter < dataJSON.length; dataCounter++) {
                    var hotel = dataJSON[dataCounter];
                    var rooms = hotel.room;
                    var maxRoomCapacity = hotel.max_capacity;
                    var hasRoomAvailable = false;

                    // for (var roomCounter = 0; roomCounter < rooms.length; roomCounter++) {
                    //     var room = rooms[roomCounter];
                    //     var roomCapacity = Object.values(room).some(function(value) {
                    //         return parseInt(value) > 0;
                    //     });
                    //     if (roomCapacity) {
                    //         hasRoomAvailable = true;
                    //         break;
                    //     }
                    // }

                    for (var roomCounter = 0; roomCounter < rooms.length; roomCounter++) {
                        var room = rooms[roomCounter];
                        var roomCapacity = Object.values(room).some(function (value) {
                            return parseInt(value) > 0;
                        });

                        if (roomCapacity) {
                            var roomMaxCapacity = Math.max.apply(
                                Math,
                                Object.values(room).map(function (value) {
                                    return parseInt(value) || 0;
                                })
                            );
                            maxRoomCapacity = Math.max(maxRoomCapacity, roomMaxCapacity);
                        }
                    }

                    if (maxRoomCapacity > 0) {
                        var dataItem = $('<div class="data-content col-md-6 grid-item">\
                            <div class="namaHotel city title-s bold text-purple">' + hotel.hotel + '</div>\
                            <div class="data-detail-wrapper data-detail-wrapper">\
                            <div>\
                                <div class="direktori-detail-content kapasitas copy bold" data-value-kapasitas="' + hotel.max_capacity + '"><span class="copy-xs medium">Kapasitas</span>' + hotel.max_capacity + '</div>\
                            </div>\
                            <div>\
                                <div class="data-detail-content copy-m capitalize alamat" data-value-kabupaten="' + hotel.kota + '"><span class="icon copy icon-location"></span><span>' + hotel.alamat + ', Provinsi <span class="namaProvinsi">' + hotel.provinsi + '</span></span></div>\
                                <div class="data-detail-content copy-m"><span class="icon copy icon-envelope1"></span><a href="">' + hotel.email + '</a></div>\
                                <div class="data-detail-content copy-m"><span class="icon copy icon-phone"></span>' + hotel.telepon + '</div>\
                                <div class="data-detail-content capacity copy-m bold btn btn-small btn-yellow-to-purple btn-rounded" data-toggle="modal" data-target="#direktoriDetailModal">Lihat detail kapasitas ruangan</div>\
                            </div>\
                        </div>');
                    

                    // if (hasRoomAvailable) {
                    //     var dataItem = $('<div class="data-content col-md-6 grid-item">\
                    //         <div class="namaHotel city title-s bold text-purple">' + hotel.hotel + '</div>\
                    //         <div class="data-detail-wrapper data-detail-wrapper">\
                    //         <div>\
                    //             <div class="direktori-detail-content kapasitas copy bold" data-value-kapasitas="LALALA"><span class="copy-xs medium">Kapasitas</span>18</div>\
                    //         </div>\
                    //         <div>\
                    //             <div class="data-detail-content copy-m capitalize"><span class="icon copy icon-location"></span><span>' + hotel.alamat + ', Provinsi <span class="namaProvinsi">' + hotel.provinsi + '</span></span></div>\
                    //             <div class="data-detail-content copy-m"><span class="icon copy icon-envelope1"></span><a href="">' + hotel.email + '</a></div>\
                    //             <div class="data-detail-content copy-m"><span class="icon copy icon-phone"></span>' + hotel.telepon + '</div>\
                    //             <div class="data-detail-content capacity copy-m bold btn btn-small btn-yellow-to-purple btn-rounded" data-toggle="modal" data-target="#direktoriDetailModal">Lihat detail kapasitas ruangan</div>\
                    //         </div>\
                    //     </div>');
                    

                        var popupContent = $('<div class="popup-direktori-content"></div>');

                        for (var roomCounter = 0; roomCounter < rooms.length; roomCounter++) {
                            var room = rooms[roomCounter];
                            var roomName = room.ruangan;


                            var roomElement = $('<div class="room-item mt-4">\
                                <div class="room-name bold title-m mb-3">' + roomName + '</div>\
                            </div>');

                            var propRow = $('<div class="row"></div>');

                            for (var prop in room) {
                                if (room.hasOwnProperty(prop) && prop !== 'ruangan') {
                                    var propValue = room[prop];

                                    var srcImage;
                                    if (prop === 'U-Shape') {
                                        srcImage = 'u-shape.png';
                                    } else if (prop === 'Banquet rounds') {
                                        srcImage = 'banquet-rounds.png';
                                    } else if (prop === 'Boardroom') {
                                        srcImage = 'boardroom.png';
                                    } else if (prop === 'Classroom') {
                                        srcImage = 'classroom.png';
                                    } else if (prop === 'Cocktail rounds') {
                                        srcImage = 'cocktail-rounds.png';
                                    } else if (prop === 'Crescent rounds (Cabaret)') {
                                        srcImage = 'crescent-rounds.png';
                                    } else if (prop === 'E-Shape') {
                                        srcImage = 'e-shape.png';
                                    } else if (prop === 'Hollow square') {
                                        srcImage = 'hollow-square.png';
                                    } else if (prop === 'Perimeter seating') {
                                        srcImage = 'perimeter-seating.png';
                                    } else if (prop === 'Reception') {
                                        srcImage = 'reception.png';
                                    } else if (prop === 'Royal Conference') {
                                        srcImage = 'royal-conference.png';
                                    } else if (prop === 'T-Shape') {
                                        srcImage = 't-shape.png';
                                    } else if (prop === 'Talkshow') {
                                        srcImage = 'talkshow.png';
                                    } else if (prop === 'Theater') {
                                        srcImage = 'theater.png';
                                    }

                                    if (parseInt(propValue) > 0) {
                                        var col = $('<div class="col-6 mb-5">\
                                            <img src="assets/img/room/' + srcImage + '" style="max-width: 250px;width:100%">\
                                            <div class="property-name copy-m pt-3 bold mb-0">' + prop + '</div>\
                                            <div class="property-value copy-m">Kapasitas: <b>' + propValue + ' orang</b></div>\
                                        </div>');

                                        propRow.append(col);
                                    }
                                }
                            }
                            if (propRow.children().length > 0) {
                                roomElement.append(propRow);
                                popupContent.append(roomElement);
                            }
                        }

                        dataItem.find('.data-detail-wrapper').append(popupContent);
                        $dataItems.push(dataItem);
                    }
                }

                $dataGrid = $('#data-filter-container').append($dataItems);
                initIsotopeAfterImagesLoaded();

                $('#direktoriDetailModal').on('show.bs.modal', function(event) {
                    var modal = $(this);
                    var button = $(event.relatedTarget);
                    var popupContent = button.closest('.data-detail-wrapper').find('.popup-direktori-content').clone();
                    modal.find('.popup-text-content').empty();
                    modal.find('.popup-text-content').append(popupContent);
                    popupContent.css({
                        opacity: 1,
                        position: 'relative'
                    });
                });

                $('#direktoriDetailModal').on('hidden.bs.modal', function(event) {
                    var modal = $(this);
                    modal.find('.popup-text-content').empty();
                    popupContent.css({
                        opacity: 0,
                        position: 'fixed'
                    });
                });

                dataUpdatePagination();
                $dataGrid.isotope('layout');
            },
            error: function(json) {
                // Handle the error
                $('.preloader-wrapper').hide();
            }
        });

        var $dataGrid = null;
        var dataItemsPerPage = 20;
        var dataCurrentPage = 1;

        function dataUpdatePagination() {
            var sortedItems = $dataGrid.isotope('getFilteredItemElements');
            var totalItems = sortedItems.length;
            var totalPages = Math.ceil(totalItems / dataItemsPerPage);
            var startIndex = (dataCurrentPage - 1) * dataItemsPerPage;
            var endIndex = startIndex + dataItemsPerPage;

            $dataGrid.children('.data-content').hide();

            $(sortedItems).slice(startIndex, endIndex).show();

            var $paginationContainer = $('#dataPagination');
            $paginationContainer.empty();

            if (totalItems === 0) {
                // Display a message when no results
                $('#noResultMessage').show();
                $('#dataPagination').hide();
                return;
            } else {
                $('#noResultMessage').hide();
                $('#dataPagination').show();
            }

            if (totalPages === 1) {
                var $firstPageBtn = $('<button class="page-item cursor-pointer m-0"><span class="page-link copy bold">1</span></button>');
                $firstPageBtn.addClass('active');
                $paginationContainer.append($firstPageBtn);
            } else {
                var prevPage = dataCurrentPage - 1;
                var nextPage = dataCurrentPage + 1;

                var $firstPageBtn = $('<button class="page-item cursor-pointer m-0"><span class="page-link copy bold">1</span></button>');
                if (dataCurrentPage === 1) {
                    $firstPageBtn.addClass('active');
                }
                $paginationContainer.append($firstPageBtn);

                if (dataCurrentPage > 2) {
                    var ellipsisStart = $('<span class="ellipsis">...</span>');
                    $paginationContainer.append(ellipsisStart);
                }

                for (var i = dataCurrentPage - 1; i <= dataCurrentPage + 1; i++) {
                    if (i > 1 && i < totalPages) {
                        var $pageBtn = $('<button class="page-item cursor-pointer m-0"><span class="page-link copy bold">' + i + '</span></button>');
                        if (i === dataCurrentPage) {
                            $pageBtn.addClass('active');
                        }
                        $paginationContainer.append($pageBtn);
                    }
                }

                if (dataCurrentPage < totalPages - 1) {
                    var ellipsisEnd = $('<span class="ellipsis">...</span>');
                    $paginationContainer.append(ellipsisEnd);
                }

                var $lastPageBtn = $('<button class="page-item cursor-pointer m-0"><span class="page-link copy bold">' + totalPages + '</span></button>');
                if (dataCurrentPage === totalPages) {
                    $lastPageBtn.addClass('active');
                }
                $paginationContainer.append($lastPageBtn);
            }

            $('.page-item').on('click', function () {
                var btnText = $(this).text();
                dataCurrentPage = parseInt(btnText);
                dataUpdatePagination();
            });

            $dataGrid.isotope('layout');
        }



        $('#dataSortResult').on('change', function() {
            var dataSortByValue = this.value;
            var dataOrderBy = $('#dataSortResult').find(":selected").data('sort');

            $dataGrid.isotope({
                sortBy: dataSortByValue,
                sortAscending: dataOrderBy
            });

            dataCurrentPage = 1;
            dataUpdatePagination();
        });

        $('.dataSortResult input[type="radio"]').on('change', function() {
            var dataSortByValue = $(this).val();
            var dataOrderBy = $(this).data('sort');

            $dataGrid.isotope({
                sortBy: dataSortByValue,
                sortAscending: dataOrderBy
            });

            dataCurrentPage = 1;
            dataUpdatePagination();
        });

        var provinsiList; 
        var kabupatenList;

        $.ajax({
            url: 'assets/docs/provinsi-list.json',
            dataType: 'json',
            success: function(json) {
                provinsiList = json.RECORDS;
                var $select = $('#dataSearchResult');
                for (var i = 0; i < json.RECORDS.length; i++) {
                    var provinceName = json.RECORDS[i].name;
                    $select.append('<option value="' + provinceName + '">' + provinceName + '</option>');
                }
            },
            error: function() {
            }
        });
        $('#dataSearchResult').on('change', function() {
            var selectedProvince = $(this).val().trim();
            var selectedProvinceId = getProvinceIdByName(selectedProvince);

            if (selectedProvince !== 'all') {
                $dataGrid.isotope({
                    filter: function() {
                        var hotelProvince = $(this).find('.namaProvinsi').text().toLowerCase();
                        return hotelProvince.includes(selectedProvince.toLowerCase());
                    }
                });

                var filteredKabupaten = filterKabupatenByProvinceId(selectedProvinceId);
                updateKabupatenOptions(filteredKabupaten);

            } else {
                $dataGrid.isotope({ filter: '*' });
            }

            dataCurrentPage = 1;
            dataUpdatePagination();
        });

        function updateKabupatenOptions(filteredKabupaten) {
            var $selectCity = $('#dataSearchCity');
            $selectCity.empty();

            $selectCity.append('<option value="all">All</option>');

            for (var i = 0; i < filteredKabupaten.length; i++) {
                var kabupatenName = filteredKabupaten[i].name;
                $selectCity.append('<option value="' + kabupatenName + '">' + kabupatenName + '</option>');
            }
        }

        function filterKabupatenByProvinceId(provinceId) {
            if (kabupatenList) {
                var filteredKabupaten = kabupatenList.filter(function(item) {
                    return item.id_province === provinceId;
                });
                return filteredKabupaten;
            }
            return [];
        }

        function getProvinceIdByName(provinceName) {
            for (var i = 0; i < provinsiList.length; i++) {
                if (provinsiList[i].name === provinceName) {
                    return provinsiList[i].id;
                }
            }
            return null;
        }

        $.ajax({
            url: 'assets/docs/kabupaten-list.json',
            dataType: 'json',
            success: function(json) {
                kabupatenList = json.RECORDS;
                var $select = $('#dataSearchCity');
                for (var i = 0; i < json.RECORDS.length; i++) {
                    var provinceName = json.RECORDS[i].name;
                    $select.append('<option value="' + provinceName + '">' + provinceName + '</option>');
                }
            },
            error: function() {
                // Handle the error
            }
        });

        $('#dataSearchCity').on('change', function() {
            var selectedKabupaten = $(this).val().trim();

            if (selectedKabupaten === 'all') {
                // Show all data if "All" is selected
                $dataGrid.isotope({ filter: '*' });
            } else {
                // Filter the data based on selected kabupaten
                $dataGrid.isotope({
                    filter: function() {
                        var kabupatenValue = $(this).find('.alamat').data('value-kabupaten');
                        return kabupatenValue === selectedKabupaten;
                    }
                });
            }

            dataCurrentPage = 1;
            dataUpdatePagination();
        });

        $(window).on('resize', function() {
            $dataGrid.isotope('layout');
        });
    });
});