(function ($) {
    'use strict';

    $(function () {
        if (typeof FWP !== 'undefined') {
            FWP.auto_refresh = false;
        }
    });

    function processFacets() {
        $('.facetwp-facet').each(function () {
            var facet = $(this);
            var facet_name = facet.attr('data-name');
            var facet_type = facet.attr('data-type');
            var facet_label = FWP.settings.labels[facet_name];

            // Check if this facet should be hidden
            var isHidden = swFacet.preselected_hidden_facets.includes(facet_name);

            if (isHidden) {
                facet.addClass('preselect-hidden');
                return;
            }

            if (swFacet.facet_show_labels) {
                if (!['pager', 'sort', 'reset'].includes(facet_type)) {
                    if (facet.closest('.facet-wrap').length < 1 && facet.closest('.facetwp-flyout').length < 1) {
                        facet.wrap(`<div class="facetwp-facet-wrap-${facet_name} ${swFacet.facet_wrapper_classes}"></div>`)
                            .before(`<p class="facetwp-facet-label-${facet_name} ${swFacet.facet_label_classes}">${facet_label}</p>`);
                    }
                }
            }
        });
    }

    $(document).on('facetwp-loaded', processFacets);


    // Show info window on hover
    function showInfoWindow(propertyId) {
        if ( typeof swFirstPageLocationsMarkers !== "undefined" && swFirstPageLocationsMarkers ) {
            const marker = swFirstPageLocationsMarkers[propertyId];

            if (marker) {
                if (!marker.getMap()) {
                    console.warn("Marker is not assigned to a map. Manually assigning...");
                    marker.setMap(FWP_MAP.map);
                }

                if (marker.content) {
                    FWP_MAP.infoWindow.setContent(marker.content);
                    FWP_MAP.infoWindow.open(FWP_MAP.map, marker);
                }
            }
        }
    }

    // Close info window on mouse leave
    function closeInfoWindow() {
        FWP_MAP.infoWindow.close();
    }

    $(document).ready(function() {
        $(document).on("mouseenter", ".facetwp-remote-data-listing-item", function() {
            const propertyId = $(this).data("post-id");
            showInfoWindow(propertyId);
        });

        $(document).on("mouseleave", ".facetwp-remote-data-listing-item", function() {
            closeInfoWindow();
        });
    });
})(jQuery);
