(function ($) {
    'use strict';

    var swFacetWpMapSettings = null;
    var swInfoWindowCloseTimeout = null;
    var swCurrentInfoWindow = null;
    var swCurrentPageLocationsMarkers = {};

    // $(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 swCurrentPageLocationsMarkers !== "undefined" && swCurrentPageLocationsMarkers ) {
            const marker = swCurrentPageLocationsMarkers[propertyId];

            if (marker) {
                if (!marker.getMap()) {
                    marker.setMap(FWP_MAP.map);
                }

                if (marker.content) {
                    if (swInfoWindowCloseTimeout) {
                        clearTimeout(swInfoWindowCloseTimeout);
                        swInfoWindowCloseTimeout = null;
                    }

                    if (swCurrentInfoWindow) {
                        swCurrentInfoWindow.close();
                    }

                    const infoWindow = FWP_MAP.infoWindow;
                    infoWindow.setContent(marker.content);
                    infoWindow.open(FWP_MAP.map, marker);

                    swCurrentInfoWindow = infoWindow;
                }
            }
        }
    }

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

    function maybeCenterFacetMap() {
        if (typeof FWP === 'undefined' || ! FWP.facets.map || ! FWP_MAP.map) {
            return;
        }

        if (0 === FWP_MAP.map.getCenter().lat() && 0 === FWP_MAP.map.getCenter().lng()) {
            return;
        }

        if (
            ! swFacetWpMapSettings
            || JSON.stringify(swFacetWpMapSettings.facetWpSettings) !== JSON.stringify(FWP.facets.map)
        ) {
            swFacetWpMapSettings = {
                facetWpSettings: FWP.facets.map,
                facetWpMapSettings: {
                    lat: FWP_MAP.map.getCenter().lat(),
                    lng: FWP_MAP.map.getCenter().lng()
                }
            }

            return;
        }

        // Map facet settings are same, but center isn't (maybe infoWindow moved center?)
        if (swFacetWpMapSettings.facetWpMapSettings.lat !== FWP_MAP.map.getCenter().lat()
            || swFacetWpMapSettings.facetWpMapSettings.lng !== FWP_MAP.map.getCenter().lng()
        ) {
            // Recenter map (to see all results)
            FWP_MAP.map.panTo(
                new google.maps.LatLng(
                    swFacetWpMapSettings.facetWpMapSettings.lat,
                    swFacetWpMapSettings.facetWpMapSettings.lng
                )
            )
        }
    }

    $(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() {
            swInfoWindowCloseTimeout = setTimeout(function() {
                closeInfoWindow();
                maybeCenterFacetMap();
            }, 3000);
        });

        $(document).on("facetwp-maps-loaded", function() {
            FWP_MAP.is_filtering = true;

            // reset before rebuilding
            swCurrentPageLocationsMarkers = {};

            $.each(FWP.settings.map.current_page_locations, function(_, obj) {
                var postId = obj.post_id;

                if (!postId) return;

                var markers = FWP_MAP.get_post_markers(postId);

                if (markers.length) {
                    swCurrentPageLocationsMarkers[postId] = markers[0];
                }
            });

            maybeCenterFacetMap();
        });
    });
})(jQuery);
