// Track the currently open info window
let currentOpenInfoWindow = null;
let currentActiveDots = null;

// Define showInfoWindow globally so it can be called from anywhere
function showInfoWindow(overlayDiv, dots) {
    // Close any existing open info window first
    if (currentOpenInfoWindow) {
        currentOpenInfoWindow.innerHTML = '';
        if (currentActiveDots) {
            handleColorStateChange(false, currentActiveDots);
        }
    }

    // Set this as the current open info window
    currentOpenInfoWindow = overlayDiv;
    currentActiveDots = dots;

    if (overlayDiv && overlayDiv.children.length === 0) {
        const infoWindow = generateInfoWindow(overlayDiv.getAttribute('data-value'), overlayDiv.id);
        overlayDiv.appendChild(infoWindow);
        if (dots) handleColorStateChange(true, dots);

        infoWindow.addEventListener('mouseenter', () => {
            svgMouseLeave = false; // Prevent svg mouseleave
            // Keep dots active when hovering over the info window
            if (currentActiveDots) {
                handleColorStateChange(true, currentActiveDots);
            }
        });

        infoWindow.addEventListener('mouseleave', () => {
            svgMouseLeave = true; // Set flag to true when leaving infoWindow
            // Small delay to check if mouse went back to the map or completely away
            setTimeout(() => {
                if (svgMouseLeave) {
                    overlayDiv.innerHTML = '';
                    if (dots) handleColorStateChange(false, dots);
                    currentOpenInfoWindow = null;
                    currentActiveDots = null;
                }
            }, 50);
        });
    }
}

function getcountypost() {
    var req = new XMLHttpRequest();
    req.open('POST', '/wp-admin/admin-ajax.php', true);
    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    req.onreadystatechange = function () {
        if (req.readyState === 4) {
            if (this.responseText !== 0) {
                let countyId = this.responseText.replace(/"/g, '');
                let nodeList = (document.querySelectorAll("#" + countyId));
                nodeList.forEach(function (element) {
                    element.classList.add('active'); // Adds the 'active' class
                });

                let htmlString = '<div><p>your region is</p><p class="title-medium">' + this.responseText + '</p></div><div class="button">view details</div>';
                const parentElement = document.querySelector('g.' + countyId);

                // Check if the parent element exists
                if (parentElement) {
                    // Create a new div element
                    const newElement = document.createElement('div');

                    // Set the innerHTML of the new element to the HTML string
                    newElement.innerHTML = htmlString;

                    // Append the new element to the parent element
                    parentElement.appendChild(newElement);
                    parentElement.classList.toggle('active');

                    // Call the global showInfoWindow with the appropriate overlay
                    const overlayDiv = document.querySelector('#' + countyId);
                    if (overlayDiv) {
                        showInfoWindow(overlayDiv, parentElement);
                        overlayDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    }
                } else {
                    console.error("Parent element not found: g." + countyId);
                }
            }
        }
    }
    var action = 'action=getcountypost&value=' + document.getElementById('county-dropdown').value;
    req.send(action);
}

// Your map element selection and event binding code remains the same
const map = document.querySelector('#map');
const svg = map.querySelector('svg');
const pathArr = Array.from(svg.children).filter(child => child.tagName === 'path');
let svgMouseLeave = true; // Global flag to track svg mouseleave

pathArr.forEach(path => {
    const divisionID = `#${path.className.baseVal}`;
    const overlayDiv = map.querySelector(divisionID);
    const dots = svg.querySelector(`g.${path.classList[0]}`);

    const handleMouseEnter = () => {
        handleColorStateChange(true, dots);
        showInfoWindow(overlayDiv, dots);
    };

    const handleMouseLeave = () => {
        // Only handle mouseleave if we're not hovering the info window
        if (svgMouseLeave) {
            overlayDiv.innerHTML = '';
            if (currentOpenInfoWindow === overlayDiv) {
                currentOpenInfoWindow = null;
                currentActiveDots = null;
            }
            handleColorStateChange(false, dots);
        }
    };

    path.addEventListener('mouseenter', handleMouseEnter);
    path.addEventListener('mouseleave', handleMouseLeave);
    dots.addEventListener('mouseenter', handleMouseEnter);
    dots.addEventListener('mouseleave', handleMouseLeave);
});

function generateInfoWindow(name, slug) {
    const infoWindow = document.createElement('a');
    infoWindow.href = `#${slug}`;
    infoWindow.classList.add('division_infoWindow');
    infoWindow.innerHTML = `
        <p>Your Region is</p>
        <p class="title-medium">${name}</p>
        <a class="button" href="#${slug}">View details</a>`;
    return infoWindow;
}

function handleColorStateChange(newState, el) {
    el.classList.toggle('active', newState);
}