/**
 * WCMLIM Product Filter - Redesigned
 * Product search with AJAX suggestions and location filtering with stock/price display
 * 
 * @since 3.0.0
 */

(function($) {
    'use strict';

    let selectedProductId = null;
    let selectedProductUrl = null;
    let searchTimeout = null;

    $(document).ready(function() {
        initProductSearch();
        
        // Wait for map to be initialized, then override marker click handlers
        setTimeout(function() {
            overrideMarkerClickHandlers();
        }, 2000);
    });

    /**
     * Initialize product search functionality
     */
    function initProductSearch() {
        const $searchInput = $('#wcmlim-product-search-input');
        const $suggestions = $('#wcmlim-product-suggestions');
        const $clearBtn = $('#wcmlim-search-clear');

        // Search input handler with debounce
        $searchInput.on('input', function() {
            const query = $(this).val().trim();

            clearTimeout(searchTimeout);

            if (query.length >= 2) {
                searchTimeout = setTimeout(function() {
                    fetchProductSuggestions(query);
                }, 300);
            } else {
                $suggestions.removeClass('visible').empty();
            }
        });

        // Focus handler
        $searchInput.on('focus', function() {
            const query = $(this).val().trim();
            if (query.length >= 2 && $suggestions.children().length > 0) {
                $suggestions.addClass('visible');
            }
        });

        // Click outside to close suggestions
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.wcmlim-product-search-wrapper').length) {
                $suggestions.removeClass('visible');
            }
        });

        // Clear button handler
        $clearBtn.on('click', function() {
            clearProductSelection();
        });
    }

    /**
     * Override marker click handlers after map initialization
     * This intercepts the existing markers created by wcmlim-public.js
     */
    function overrideMarkerClickHandlers() {
        // Wait for markers to be created
        const checkMarkers = setInterval(function() {
            // The markers are stored in the window.markers array or similar
            // We need to find all location cards and set up our override
            const $locationCards = $('.wcmlim-map-sidebar-list');
            
            if ($locationCards.length > 0) {
                clearInterval(checkMarkers);
                
                // Add click event to location cards to trigger marker
                $locationCards.each(function() {
                    const $card = $(this);
                    const locationId = $card.data('location-id');
                    
                    // Store reference for later use
                    $card.data('marker-location-id', locationId);
                });
                
                // Hook into marker clicks by observing DOM changes in info windows
                observeInfoWindowChanges();
            }
        }, 100);
        
        // Stop checking after 10 seconds
        setTimeout(function() {
            clearInterval(checkMarkers);
        }, 10000);
    }

    /**
     * Observe info window changes and enhance them with stock/price
     */
    function observeInfoWindowChanges() {
        // Look for the Google Maps info window
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                mutation.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1) {
                        const $node = $(node);
                        
                        // Check if this is an info window content
                        if ($node.find('.locator-store-block').length > 0 || $node.hasClass('locator-store-block')) {
                            enhanceInfoWindow($node.find('.locator-store-block').length > 0 ? $node.find('.locator-store-block') : $node);
                        }
                    }
                });
            });
        });
        
        // Observe the map container
        const mapContainer = document.getElementById('map');
        if (mapContainer) {
            observer.observe(mapContainer, {
                childList: true,
                subtree: true
            });
        }
        
        // Also observe the entire body for info windows
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }

    /**
     * Enhance info window with stock and price when product is selected
     */
    function enhanceInfoWindow($infoBlock) {
        if (!selectedProductId || !selectedProductUrl) {
            return;
        }
        
        // Get the location name from the info window
        const locationName = $infoBlock.find('h4').text().trim();
        
        // Find the matching location card
        const $matchingCard = $('.wcmlim-map-sidebar-list h4').filter(function() {
            return $(this).text().trim() === locationName;
        }).closest('.wcmlim-map-sidebar-list');
        
        if ($matchingCard.length === 0) {
            return;
        }
        
        const locationId = $matchingCard.data('location-id');
        const stock = $matchingCard.data('product-stock');
        const price = $matchingCard.data('product-price');
        const productUrl = $matchingCard.data('product-url');
        const locationAddress = $matchingCard.find('.location-address span').first().text().trim();
        const locationEmail = $matchingCard.find('.location-address .far.fa-envelope-open').next('span').text().trim();
        
        // Get direction URL
        const directionBtn = $matchingCard.find('button[onclick*="google.com/maps"]');
        let directionUrl = '';
        if (directionBtn.length) {
            const onclickAttr = directionBtn.attr('onclick');
            const match = onclickAttr.match(/window\.open\('([^']+)'/);
            if (match) {
                directionUrl = match[1];
            }
        }
        
        // Build enhanced content
        let enhancedContent = '<div class="wcmlim-marker-info">';
        enhancedContent += '<h4>' + locationName + '</h4>';
        enhancedContent += '<div class="wcmlim-marker-details">';
        
        // Stock information
        if (stock !== undefined) {
            if (stock > 0) {
                enhancedContent += '<p class="wcmlim-stock-info"><strong>Stock:</strong> <span class="in-stock">' + stock + ' available</span></p>';
            } else {
                enhancedContent += '<p class="wcmlim-stock-info"><strong>Stock:</strong> <span class="out-of-stock">Out of Stock</span></p>';
            }
        }
        
        // Price information
        if (price) {
            enhancedContent += '<p class="wcmlim-price-info"><strong>Price:</strong> ' + price + '</p>';
        }
        
        // Address
        if (locationAddress) {
            enhancedContent += '<p class="wcmlim-address-info"><i class="far fa-map"></i> ' + locationAddress + '</p>';
        }
        
        // Email
        if (locationEmail) {
            enhancedContent += '<p class="wcmlim-email-info"><i class="far fa-envelope"></i> ' + locationEmail + '</p>';
        }
        
        // Buttons
        enhancedContent += '<div class="wcmlim-marker-actions">';
        if (directionUrl) {
            enhancedContent += '<a href="' + directionUrl + '" target="_blank" class="wcmlim-btn-direction">Directions</a>';
        }
        if (productUrl) {
            enhancedContent += '<a href="' + productUrl + '" target="_blank" class="wcmlim-btn-shop">Shop Now</a>';
        }
        enhancedContent += '</div>';
        
        enhancedContent += '</div></div>';
        
        // Replace the content
        $infoBlock.replaceWith(enhancedContent);
        
        // Highlight the location in sidebar
        highlightLocation(locationId);
    }

    /**
     * Fetch product suggestions via AJAX
     */
    function fetchProductSuggestions(query) {
        const ajaxUrl = $('#wcmlim-ajax-url').val();
        const nonce = $('#wcmlim-ajax-nonce').val();

        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'wcmlim_search_products',
                query: query,
                security: nonce
            },
            success: function(response) {
                if (response.success && response.data.products) {
                    displayProductSuggestions(response.data.products);
                } else {
                    displayNoSuggestions();
                }
            },
            error: function() {
                displayNoSuggestions();
            }
        });
    }

    /**
     * Display product suggestions dropdown
     */
    function displayProductSuggestions(products) {
        const $suggestions = $('#wcmlim-product-suggestions');
        $suggestions.empty();

        if (products.length === 0) {
            displayNoSuggestions();
            return;
        }

        products.forEach(function(product) {
            const $item = $('<div>')
                .addClass('wcmlim-suggestion-item')
                .data('product-id', product.id)
                .data('product-name', product.name)
                .data('product-url', product.url);

            const $img = $('<img>').attr('src', product.image).attr('alt', product.name);
            
            const $info = $('<div>').addClass('wcmlim-suggestion-info');
            $info.append($('<h5>').text(product.name));
            $info.append($('<div>').addClass('price').html(product.price));

            $item.append($img).append($info);

            $item.on('click', function() {
                selectProduct(product.id, product.name, product.url);
            });

            $suggestions.append($item);
        });

        $suggestions.addClass('visible');
    }

    /**
     * Display no suggestions message
     */
    function displayNoSuggestions() {
        const $suggestions = $('#wcmlim-product-suggestions');
        $suggestions.empty();
        $suggestions.append($('<div>').addClass('wcmlim-no-suggestions').text('No products found'));
        $suggestions.addClass('visible');
    }

    /**
     * Select a product
     */
    function selectProduct(productId, productName, productUrl) {
        selectedProductId = productId;
        selectedProductUrl = productUrl;

        // Update search input
        const $searchInput = $('#wcmlim-product-search-input');
        $searchInput.val(productName);
        $searchInput.addClass('has-selection');

        // Show clear button
        $('#wcmlim-search-clear').addClass('visible');

        // Hide suggestions
        $('#wcmlim-product-suggestions').removeClass('visible');

        // Store selected product ID
        $('#wcmlim-selected-product-id').val(productId);

        // Fetch and display locations for this product
        fetchProductLocations(productId, productUrl);
    }

    /**
     * Clear product selection
     */
    function clearProductSelection() {
        selectedProductId = null;
        selectedProductUrl = null;

        // Clear search input
        const $searchInput = $('#wcmlim-product-search-input');
        $searchInput.val('');
        $searchInput.removeClass('has-selection');

        // Hide clear button
        $('#wcmlim-search-clear').removeClass('visible');

        // Clear selected product ID
        $('#wcmlim-selected-product-id').val('');

        // Reset all locations to default state
        resetLocations();

        // Hide suggestions
        $('#wcmlim-product-suggestions').removeClass('visible');
    }

    /**
     * Fetch locations for selected product
     */
    function fetchProductLocations(productId, productUrl) {
        const ajaxUrl = $('#wcmlim-ajax-url').val();
        const nonce = $('#wcmlim-ajax-nonce').val();

        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'wcmlim_get_product_locations',
                product_id: productId,
                security: nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    updateLocationsWithProductData(response.data.locations, productUrl);
                } else {
                    resetLocations();
                }
            },
            error: function() {
                resetLocations();
            }
        });
    }

    /**
     * Update location cards with product stock and price data
     */
    function updateLocationsWithProductData(locationsData, productUrl) {
        const $locationsContainer = $('#wcmlim-locations-container');
        
        // Check if no locations available
        if (!locationsData || locationsData.length === 0) {
            // Hide all location cards
            $('.wcmlim-map-sidebar-list').hide();
            
            // Show no locations message
            $locationsContainer.prepend(
                '<div class="wcmlim-no-locations-message" style="padding: 30px; text-align: center; background: #fff3cd; border: 2px solid #ffc107; border-radius: 8px; margin: 20px 0;">' +
                '<i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #ff9800; margin-bottom: 15px;"></i>' +
                '<h3 style="color: #856404; margin: 10px 0;">Product Not Available</h3>' +
                '<p style="color: #856404; font-size: 16px;">This product is not available in any location.</p>' +
                '</div>'
            );
            return;
        }
        
        // Remove any previous no locations message
        $('.wcmlim-no-locations-message').remove();
        
        // Hide all locations first
        $('.wcmlim-map-sidebar-list').hide();

        // Create a map of location IDs to data for quick lookup
        const locationDataMap = {};
        locationsData.forEach(function(loc) {
            locationDataMap[loc.term_id] = loc;
        });

        // Update each location card
        $('.wcmlim-map-sidebar-list').each(function() {
            const $card = $(this);
            const locationId = $card.data('location-id');
            const locationData = locationDataMap[locationId];

            if (locationData) {
                // Show this location
                $card.show();
                
                // Store location data on card for marker clicks
                $card.data('product-stock', locationData.stock);
                $card.data('product-price', locationData.price);
                $card.data('product-url', productUrl);

                // Update stock and price info
                const $stockDiv = $card.find('.wcmlim-location-stock');
                let stockHtml = '';

                // Stock info
                if (locationData.stock > 0) {
                    stockHtml += '<div class="wcmlim-stock-info">';
                    stockHtml += '<span class="label">Stock:</span>';
                    stockHtml += '<span class="value in-stock">' + locationData.stock + ' available</span>';
                    stockHtml += '</div>';
                } else {
                    stockHtml += '<div class="wcmlim-stock-info">';
                    stockHtml += '<span class="label">Stock:</span>';
                    stockHtml += '<span class="value out-of-stock">Out of Stock</span>';
                    stockHtml += '</div>';
                }

                // Price info
                if (locationData.price) {
                    stockHtml += '<div class="wcmlim-price-info">';
                    stockHtml += '<span class="label">Price:</span>';
                    stockHtml += '<span class="value">' + locationData.price + '</span>';
                    stockHtml += '</div>';
                }

                $stockDiv.html(stockHtml).show();

                // Update Shop Now button
                const $shopBtn = $card.find('.wcmlim-shop-now-btn');
                $shopBtn.attr('onclick', "window.open('" + productUrl + "', '_blank');");
                $shopBtn.show();
            }
        });
    }

    /**
     * Reset all locations to default state (show all, hide stock/price)
     */
    function resetLocations() {
        // Remove no locations message if exists
        $('.wcmlim-no-locations-message').remove();
        
        $('.wcmlim-map-sidebar-list').each(function() {
            const $card = $(this);
            $card.show();
            $card.find('.wcmlim-location-stock').hide().empty();
            $card.find('.wcmlim-shop-now-btn').hide();
            // Clear stored product data
            $card.removeData('product-stock product-price product-url');
        });
    }

    /**
     * Handle location card click in sidebar
     * When a product is selected and user clicks a location, show stock/price info
     */
    $(document).on('click', '.wcmlim-map-sidebar-list', function() {
        if (selectedProductId && selectedProductUrl) {
            const locationId = $(this).data('location-id');
            highlightLocation(locationId);
        }
    });

    /**
     * Highlight a specific location and ensure its stock/price is visible
     */
    function highlightLocation(locationId) {
        // Remove previous highlights
        $('.wcmlim-map-sidebar-list').css('background-color', '');
        
        // Highlight clicked location
        const $location = $('.wcmlim-map-sidebar-list[data-location-id="' + locationId + '"]');
        $location.css('background-color', '#f0f8ff');
        
        // Scroll to location in sidebar
        const $sidebar = $('.wcmlim-map-sidebar-widgets');
        const locationTop = $location.position().top;
        $sidebar.animate({
            scrollTop: $sidebar.scrollTop() + locationTop - 100
        }, 500);
    }

    /**
     * Initialize event listeners for Google Maps markers
     * This should be called after the map is loaded
     */
    window.wcmlimInitMarkerListeners = function() {
        // This function can be called from the map initialization code
        // to add click listeners to markers that show stock/price for selected product
        if (typeof google !== 'undefined' && google.maps && window.wcmlimMarkers) {
            window.wcmlimMarkers.forEach(function(marker, index) {
                google.maps.event.addListener(marker, 'click', function() {
                    const locationId = marker.locationId; // Assumes locationId is set on marker
                    
                    if (selectedProductId && selectedProductUrl) {
                        highlightLocation(locationId);
                        
                        // Get location data from the card
                        const $locationCard = $('.wcmlim-map-sidebar-list[data-location-id="' + locationId + '"]');
                        const locationName = $locationCard.find('h4').text();
                        const locationAddress = $locationCard.find('.location-address span').first().text().trim();
                        const locationEmail = $locationCard.find('.location-address .far.fa-envelope-open').next('span').text().trim();
                        
                        // Get product data stored on card
                        const stock = $locationCard.data('product-stock');
                        const price = $locationCard.data('product-price');
                        const productUrl = $locationCard.data('product-url');
                        
                        // Get direction URL
                        const directionBtn = $locationCard.find('button[onclick*="google.com/maps"]');
                        let directionUrl = '';
                        if (directionBtn.length) {
                            const onclickAttr = directionBtn.attr('onclick');
                            const match = onclickAttr.match(/window\.open\('([^']+)'/);
                            if (match) {
                                directionUrl = match[1];
                            }
                        }
                        
                        // Create enhanced info window content
                        let infoContent = '<div class="wcmlim-marker-info">';
                        infoContent += '<h4>' + locationName + '</h4>';
                        infoContent += '<div class="wcmlim-marker-details">';
                        
                        // Stock information
                        if (stock > 0) {
                            infoContent += '<p class="wcmlim-stock-info"><strong>Stock:</strong> <span class="in-stock">' + stock + ' available</span></p>';
                        } else {
                            infoContent += '<p class="wcmlim-stock-info"><strong>Stock:</strong> <span class="out-of-stock">Out of Stock</span></p>';
                        }
                        
                        // Price information
                        if (price) {
                            infoContent += '<p class="wcmlim-price-info"><strong>Price:</strong> ' + price + '</p>';
                        }
                        
                        // Address
                        if (locationAddress) {
                            infoContent += '<p class="wcmlim-address-info"><i class="far fa-map"></i> ' + locationAddress + '</p>';
                        }
                        
                        // Email
                        if (locationEmail) {
                            infoContent += '<p class="wcmlim-email-info"><i class="far fa-envelope"></i> ' + locationEmail + '</p>';
                        }
                        
                        // Buttons
                        infoContent += '<div class="wcmlim-marker-actions">';
                        if (directionUrl) {
                            infoContent += '<a href="' + directionUrl + '" target="_blank" class="wcmlim-btn-direction">Directions</a>';
                        }
                        if (productUrl) {
                            infoContent += '<a href="' + productUrl + '" target="_blank" class="wcmlim-btn-shop">Shop Now</a>';
                        }
                        infoContent += '</div>';
                        
                        infoContent += '</div></div>';
                        
                        // Update the info window (if you have a global infoWindow object)
                        if (window.wcmlimInfoWindow) {
                            window.wcmlimInfoWindow.setContent(infoContent);
                            window.wcmlimInfoWindow.open(window.wcmlimMap, marker);
                        }
                    }
                });
            });
        }
    };

})(jQuery);
