// <![CDATA[

// Prevent duplicate script execution
if (window.idxWebhookScriptLoaded) {
    console.warn("⚠️ IDX Webhook script already loaded, skipping duplicate execution");
} else {
    window.idxWebhookScriptLoaded = true;

var webhookId = "4a870b00b7b7fbfa4231031405edfd9c",
    webhookUrl = "https://idxaddons.com/webhook/index.php",
    idx_userdata = getCookie("IDX-userData"),
    idx_potential_userdata = getCookie("IDX-potentialUserData");

// Function to get cookie value
function getCookie(name) {
    var cookieName = name + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var cookieArray = decodedCookie.split(";");
    for (var i = 0; i < cookieArray.length; i++) {
        var cookie = cookieArray[i];
        while (cookie.charAt(0) == " ") {
            cookie = cookie.substring(1);
        }
        if (cookie.indexOf(cookieName) == 0) {
            return cookie.substring(cookieName.length, cookie.length);
        }
    }
    return "";
}

function handleFormSubmission() {
    console.log("Initializing IDX form observer...");

    const formConfigs = [
        {
            selector: "#IDX-detailscontactContactForm",
            responseSelector: "#IDX-detailscontactformResponse",
            action: "contactedAgent"
        },
        {
            selector: "#IDX-scheduleshowingContactForm",
            responseSelector: "#IDX-scheduleshowingformResponse",
            action: "scheduleShowing"
        },
        {
            selector: "#IDX-moreinfoContactForm",
            responseSelector: "#IDX-moreinfoformResponse",
            action: "requestedMoreInfo"
        },
        {
            selector: "#IDX-homevaluationContactForm",
            responseSelector: "#IDX-homevaluationformResponse",
            action: "homeValuation"
        }
    ];

    const formDataCache = new WeakMap();

    formConfigs.forEach(config => {
        const forms = Array.from(document.querySelectorAll(config.selector));
        const responseContainer = document.querySelector(config.responseSelector);

        if (!forms.length || !responseContainer) {
            console.log(`Form or response container not found for selector: ${config.selector}`);
            return;
        }

        forms.forEach(form => {
            // 1. Capture data at submit time
            form.addEventListener("submit", () => {
                const getValue = name =>
                    form.querySelector(`[name="${name}"]`)?.value?.trim() || "";

                const sendData = {
                    webhook_id: webhookId,
                    websiteurl: window.location.href,
                    pathname: window.location.pathname,
                    idx_userdata: idx_userdata,
                    idx_potential_userdata: idx_potential_userdata,
                    url: window.location.href,
                    action: config.action,
                    firstName: getValue("firstName"),
                    lastName: getValue("lastName"),
                    email: getValue("email"),
                    phone: getValue("phone"),
                    message: getValue("message"),
                    agentOwner: getValue("agentOwner"),
                    idxID: getValue("idxID"),
                    listingID: getValue("listingID")
                };

                if (config.action === "scheduleShowing") {
                    sendData.firstDate = getValue("firstDate");
                    sendData.firstTime = getValue("firstTime");
                    sendData.secondDate = getValue("secondDate");
                    sendData.secondTime = getValue("secondTime");
                }

                if (config.action === "homeValuation") {
                    sendData.address = getValue("hvAddress");
                    sendData.cityAndState = getValue("hvCityState");
                    sendData.zipCode = getValue("hvZipcode");
                    sendData.propertyType = getValue("hvPropType");
                    sendData.condition = form.querySelector(`[name="hvCondition"]:checked`)?.value || "";
                    sendData.bedrooms = getValue("hvBedrooms");
                    sendData.bathrooms = getValue("hvBathrooms");
                    sendData.features = getValue("hvFeatures");
                    sendData.size = getValue("hvSize");
                    sendData.kitchenAge = getValue("hvKitchenAge");
                    sendData.bathroomAge = getValue("hvBathsAge");
                    sendData.message = getValue("hvMessage");
                }

                // Cache data to send later
                formDataCache.set(form, sendData);
            });

            // 2. Watch for successful submission (via DOM change)
            const observer = new MutationObserver(mutations => {
                for (const mutation of mutations) {
                    if (mutation.type === "childList" && mutation.addedNodes.length > 0) {
                        const responseText = responseContainer.textContent.toLowerCase();
                        if (responseText.includes("thank you") || responseText.includes("submitted")) {
                            const cachedData = formDataCache.get(form);
                            if (cachedData) {
                                idx.ajax({
                                    url: webhookUrl,
                                    dataType: "json",
                                    data: cachedData,
                                    cache: false
                                });
                                console.log("✅ Lead sent via webhook:", cachedData);
                                formDataCache.delete(form); // cleanup
                            } else {
                                console.warn("⚠️ No cached data found for form");
                            }
                        }
                    }
                }
            });

            observer.observe(responseContainer, { childList: true, subtree: true });
        });
    });
}

function handleLeadContactFormSubmission() {
    const formSelector = "#IDX-contactContactForm";
    const responseSelector = "#IDX-contactformResponse";
    const action = "contactForm";

    const contactForm = document.querySelector(formSelector);
    const responseContainer = document.querySelector(responseSelector);

    if (!contactForm || !responseContainer) {
        console.log("Lead contact form or response container not found.");
        return;
    }

    const formDataCache = new WeakMap();

    // Step 1: Capture data on submit
    contactForm.addEventListener("submit", function () {
        const getValue = name =>
            contactForm.querySelector(`[name="${name}"]`)?.value?.trim() || "";

        const sendData = {
            webhook_id: webhookId,
            websiteurl: window.location.href,
            pathname: window.location.pathname,
            idx_userdata: idx_userdata,
            idx_potential_userdata: idx_potential_userdata,
            url: window.location.href,
            action: action,
            leadID: getValue("leadID"),
            agentOwner: getValue("agentOwner"),
            message: getValue("message")
        };

        // Cache form data
        formDataCache.set(contactForm, sendData);
        console.log("📥 Lead contact form data cached:", sendData);
    });

    // Step 2: Observe response container for changes
    const observer = new MutationObserver(mutations => {
        for (const mutation of mutations) {
            if (mutation.type === "childList" && mutation.addedNodes.length > 0) {
                const responseText = responseContainer.textContent.toLowerCase();

                if (responseText.includes("thank you") || responseText.includes("submitted")) {
                    const cachedData = formDataCache.get(contactForm);

                    if (cachedData) {
                        const errorMessages = responseContainer.querySelectorAll(".IDX-errorMessage");

                        if (errorMessages.length > 0) {
                            console.warn("❌ Errors detected in lead contact form:");
                            errorMessages.forEach(msg => console.warn(msg.textContent));
                        } else {
                            idx.ajax({
                                url: webhookUrl,
                                dataType: "json",
                                data: cachedData,
                                cache: false
                            });

                            console.log("✅ Lead contact form submitted via webhook:", cachedData);
                            formDataCache.delete(contactForm); // clean up
                        }
                    }
                }
            }
        }
    });

    observer.observe(responseContainer, { childList: true, subtree: true });
}

function handleContactFormSubmission() {
    const formSelector = "#IDX-contactContactForm";
    const responseSelector = "#IDX-contactformResponse";
    const action = "contactForm";

    const contactForm = document.querySelector(formSelector);
    const responseContainer = document.querySelector(responseSelector);

    if (!contactForm || !responseContainer) {
        console.log("Contact form or response container not found.");
        return;
    }

    const formDataCache = new WeakMap();

    // Step 1: Capture data on submit
    contactForm.addEventListener("submit", function () {
        const getValue = name =>
            contactForm.querySelector(`[name="${name}"]`)?.value?.trim() || "";

        const sendData = {
            webhook_id: webhookId,
            websiteurl: window.location.href,
            pathname: window.location.pathname,
            idx_userdata: idx_userdata,
            idx_potential_userdata: idx_potential_userdata,
            url: window.location.href,
            action: action,
            firstName: getValue("firstName"),
            lastName: getValue("lastName"),
            email: getValue("email"),
            phone: getValue("phone"),
            message: getValue("message"),
            agentOwner: getValue("agentOwner")
        };

        // Cache form data
        formDataCache.set(contactForm, sendData);
        console.log("📥 Contact form data cached:", sendData);
    });

    // Step 2: Observe response container for changes
    const observer = new MutationObserver(mutations => {
        for (const mutation of mutations) {
            if (mutation.type === "childList" && mutation.addedNodes.length > 0) {
                const responseText = responseContainer.textContent.toLowerCase();

                if (responseText.includes("thank you") || responseText.includes("submitted")) {
                    const cachedData = formDataCache.get(contactForm);

                    if (cachedData) {
                        const errorMessages = responseContainer.querySelectorAll(".IDX-errorMessage");

                        if (errorMessages.length > 0) {
                            console.warn("❌ Errors detected in contact form:");
                            errorMessages.forEach(msg => console.warn(msg.textContent));
                        } else {
                            idx.ajax({
                                url: webhookUrl,
                                dataType: "json",
                                data: cachedData,
                                cache: false
                            });

                            console.log("✅ Contact form submitted via webhook:", cachedData);
                            formDataCache.delete(contactForm); // clean up
                        }
                    }
                }
            }
        }
    });

    observer.observe(responseContainer, { childList: true, subtree: true });
}

// Handle ListingPro modal contact form submission
var listingProHandlerInitialized = false;
function handleListingProContactFormSubmission() {
    // Prevent multiple initializations
    if (listingProHandlerInitialized) return;
    listingProHandlerInitialized = true;
    
    var formInitialized = false;
    
    // Listen for contact button click
    document.body.addEventListener("click", function(event) {
        var target = event.target;
        
        if (target.id === "idx-contact-button" || target.closest("#idx-contact-button")) {
            if (formInitialized) return;
            
            formInitialized = true;
            
            // Wait for modal to render
            setTimeout(function() {
                var contactForm = document.querySelector("#idx-contact-form");
                
                if (!contactForm) {
                    formInitialized = false;
                    return;
                }
                
                var webhookSent = false;
                var isProcessing = false;
                
                // Handle submit button click
                var submitButton = document.querySelector("#idx-contact-submit-button");
                if (submitButton) {
                    submitButton.addEventListener("click", function() {
                        
                        // Prevent multiple submissions while processing
                        if (isProcessing || webhookSent) return;
                        isProcessing = true;
                        
                        // Wait for form validation to complete
                        setTimeout(function() {
                            // Check for validation errors
                            var errorAlert = contactForm.querySelector(".idx-alert-danger");
                            if (errorAlert && errorAlert.textContent.trim() !== "") {
                                isProcessing = false;
                                return;
                            }
                            
                            // Helper to get field values
                            var getValue = function(name) {
                                var field = contactForm.querySelector("[name='" + name + "']");
                                return field ? (field.value || "").trim() : "";
                            };
                            
                            // Check if user is logged in
                            var isLoggedIn = idx_userdata && idx_userdata.trim() !== "";
                            
                            var firstName = "";
                            var lastName = "";
                            var email = "";
                            var phone = "";
                            var message = getValue("message");
                            
                            if (isLoggedIn) {
                                // User is logged in: only capture message
                                // Backend will extract user data from idx_userdata cookie
                                if (!message) {
                                    isProcessing = false;
                                    return;
                                }
                            } else {
                                // User is not logged in: extract data from form fields
                                var firstNameField = contactForm.querySelector("[name='first-name']");
                                var lastNameField = contactForm.querySelector("[name='last-name']");
                                var emailField = contactForm.querySelector("[name='email-address']");
                                
                                if (!firstNameField || !lastNameField || !emailField) {
                                    isProcessing = false;
                                    return;
                                }
                                
                                firstName = (firstNameField.value || "").trim();
                                lastName = (lastNameField.value || "").trim();
                                email = (emailField.value || "").trim();
                                phone = getValue("phone-number-used-as-password");
                                
                                // Validate required fields for non-logged users
                                if (!firstName || !lastName || !email) {
                                    isProcessing = false;
                                    return;
                                }
                            }
                            
                            // Extract listing info from URL or DOM
                            var idxID = "";
                            var listingID = "";
                            var pathParts = window.location.pathname.split("/");
                            
                            if (pathParts.length >= 5 && pathParts[1] === "idx" && pathParts[2] === "details") {
                                idxID = pathParts[4] || "";
                                listingID = pathParts[5] || "";
                            }
                            
                            if (!idxID || !listingID) {
                                var detailsContainer = document.querySelector("[data-idxid]") || document.querySelector("[idxid]");
                                if (detailsContainer) {
                                    idxID = detailsContainer.getAttribute("data-idxid") || detailsContainer.getAttribute("idxid") || "";
                                    listingID = detailsContainer.getAttribute("data-listingid") || detailsContainer.getAttribute("listingid") || "";
                                }
                            }
                            
                            // Build webhook data
                            var formData = {
                                webhook_id: webhookId,
                                websiteurl: window.location.href,
                                pathname: window.location.pathname,
                                idx_userdata: idx_userdata,
                                idx_potential_userdata: idx_potential_userdata,
                                url: window.location.href,
                                action: "requestedMoreInfo",
                                firstName: firstName,
                                lastName: lastName,
                                email: email,
                                phone: phone,
                                message: message,
                                idxID: idxID,
                                listingID: listingID
                            };
                            
                            // Mark as sent before ajax to prevent race condition
                            webhookSent = true;
                            
                            // Send webhook
                            idx.ajax({
                                url: webhookUrl,
                                data: formData,
                                cache: false,
                                success: function() {
                                    console.log("ListingPro contact form submitted");
                                    isProcessing = false;
                                },
                                error: function() {
                                    webhookSent = false;
                                    isProcessing = false;
                                }
                            });
                            
                        }, 500);
                    });
                }
                
                // Reset state when modal closes
                var closeButton = document.querySelector(".idx-dialog__dismiss button");
                if (closeButton) {
                    closeButton.addEventListener("click", function() {
                        webhookSent = false;
                        formInitialized = false;
                    });
                }
                
            }, 300);
        }
    });
}

// Global flag to track if user was logged in before save search (to prevent duplicate tracking)
var wasLoggedInBeforeSaveSearch = false;

// Function to handle save search tracking with support for soft login
function handleSaveSearchTracking() {
console.log("Initializing save search tracking...");

    // Check if we have a pending save search after page reload (from login/registration)
    var pendingSaveProcessed = false; // Flag to prevent duplicate processing
    var checkPendingSaveSearch = function() {
        try {
            // Check if we already processed a pending save
            if (pendingSaveProcessed) {
                console.log("⏭️ Pending save already processed, skipping duplicate check");
                return;
            }

            var pendingSave = sessionStorage.getItem("pendingSaveSearch");
            if (pendingSave) {
                console.log("🔄 Found pending save search after page reload:", pendingSave);
                var saveData = JSON.parse(pendingSave);

                // Check if user is now logged in
                var isLoggedIn = idx("#IDX-main").hasClass("IDX-loggedIn");
                var userData = getCookie("IDX-userData");

                console.log("Post-reload login check:", {
                    isLoggedIn: isLoggedIn,
                    hasUserData: !!userData
                });

                if (isLoggedIn && userData) {
                    console.log("✅ User is now logged in after reload, tracking save search...");

                    // Mark as processed IMMEDIATELY to prevent duplicates
                    pendingSaveProcessed = true;
                    sessionStorage.removeItem("pendingSaveSearch");

                    idx.ajax({
                        url: webhookUrl,
                        dataType: "json",
                        data: {
                            webhook_id: webhookId,
                            websiteurl: saveData.url || window.location.href,
                            pathname: saveData.pathname || window.location.pathname,
                            idx_userdata: userData,
                            idx_potential_userdata: getCookie("IDX-potentialUserData"),
                            savedLinkQueryString: saveData.queryString,
                            savedLink: saveData.searchPageID,
                            action: "saveSearch"
                        },
                        cache: false,
                        success: function() {
                            console.log("✅ Pending save search webhook sent successfully after reload");
                        },
                        error: function(xhr, status, error) {
                            console.error("❌ Webhook error:", status, error);
                        }
                    });
                } else {
                    console.log("⏳ User still not logged in, will retry on next check");
                }
            }
        } catch (e) {
            console.error("❌ Error checking pending save search:", e);
        }
    };

    // Check for pending saves on page load
    checkPendingSaveSearch();

    // Also check after a short delay (in case cookies/DOM arent ready immediately)
    setTimeout(checkPendingSaveSearch, 500);
    setTimeout(checkPendingSaveSearch, 1500);

    // Track immediate clicks on save search button
    document.body.addEventListener("click", function(event) {
        var target = event.target.hash ? event.target.hash : (event.target.parentNode ? event.target.parentNode.hash : null);
        if (target && target.slice(1) == "saveSearch") {
            console.log("🔵 Save search button clicked");
            var softLoggedIn = idx("#IDX-registration").attr("data-softLoggedIn");
            var isLoggedIn = idx("#IDX-main").hasClass("IDX-loggedIn");

            console.log("📋 Login status check:", {
                isLoggedIn: isLoggedIn,
                softLoggedIn: softLoggedIn,
                hasIDXMain: idx("#IDX-main").length > 0,
                hasIDXRegistration: idx("#IDX-registration").length > 0
            });

            // Only track if user is fully logged in (not soft-logged)
            if (isLoggedIn && !softLoggedIn) {
                console.log("✅ User is fully logged in, sending save search webhook immediately");

                // Set flag to prevent duplicate tracking in callback
                wasLoggedInBeforeSaveSearch = true;

                var savedSearchForm = document.getElementById("IDX-saveSearchForm");
                var savedLinkQueryStringElement;
                var savedLinkElement;
                if (savedSearchForm) {
                    savedLinkQueryStringElement = savedSearchForm.querySelector("input[name='savedLinkQueryString']");
                    savedLinkElement = savedSearchForm.querySelector("input[name='savedLink']");
                }
                var savedLink = savedLinkElement ? savedLinkElement.value : null;
                var savedLinkQueryString = savedLinkQueryStringElement ? savedLinkQueryStringElement.value : null;

                console.log("📊 Form data:", {
                    savedLink: savedLink,
                    savedLinkQueryString: savedLinkQueryString
                });

                idx.ajax({
                    url: webhookUrl,
                    dataType: "json",
                    data: {
                        webhook_id: webhookId,
                        websiteurl: window.location.href,
                        pathname: window.location.pathname,
                        idx_userdata: idx_userdata,
                        idx_potential_userdata: idx_potential_userdata,
                        savedLink: savedLink,
                        savedLinkQueryString: savedLinkQueryString,
                        action: "saveSearch"
                    },
                    cache: false,
                    success: function() {
                        console.log("✅ Immediate save search webhook sent successfully");
                    },
                    error: function(xhr, status, error) {
                        console.error("❌ Webhook error:", status, error);
                    }
                });
            } else {
                console.log("⏳ User not fully logged in - storing intent for post-login tracking");

                // Store the save search intent in sessionStorage for after login/reload
                try {
                    var savedSearchForm = document.getElementById("IDX-saveSearchForm");
                    var queryStringElement = savedSearchForm ? savedSearchForm.querySelector("input[name='savedLinkQueryString']") : null;
                    var searchPageIDElement = savedSearchForm ? savedSearchForm.querySelector("input[name='savedLink']") : null;
                    var queryString = queryStringElement ? queryStringElement.value : null;
                    var searchPageID = searchPageIDElement ? searchPageIDElement.value : null;

                    // Also try to get from the form inputs if they exist
                    if (!queryString) {
                        queryString = idx("#IDX-saveSearchForm .IDX-queryString").val();
                    }
                    if (!searchPageID) {
                        searchPageID = idx("#IDX-saveSearchForm .IDX-searchPageID").val();
                    }

                    var pendingData = {
                        queryString: queryString,
                        searchPageID: searchPageID,
                        url: window.location.href,
                        pathname: window.location.pathname,
                        timestamp: Date.now()
                    };

                    sessionStorage.setItem("pendingSaveSearch", JSON.stringify(pendingData));
                    console.log("💾 Saved pending search to sessionStorage:", pendingData);
                } catch (e) {
                    console.error("❌ Error saving pending save search:", e);
                }
            }
        }
    });

    // Watch for successful save search after registration/login
    // This captures the case when user had to login first
    var setupSaveSearchWrapper = function() {
        if (typeof window.saveSearchSuccess === "function") {
            console.log("✅ Found window.saveSearchSuccess, wrapping it now");
            var originalSaveSearchSuccess = window.saveSearchSuccess;
            window.saveSearchSuccess = function(responseText, statusText, xhr, $form) {
                console.log("🎯 saveSearchSuccess callback fired!", responseText);

                // Call original function first
                originalSaveSearchSuccess(responseText, statusText, xhr, $form);

                // Track the event after successful save
                if (responseText && responseText.status === "success") {
                    // Check if user was already logged in before the save
                    // If they were, the click handler already tracked it, so skip this
                    var currentUserData = getCookie("IDX-userData");
                    var wasAlreadyLoggedIn = idx_userdata && idx_userdata === currentUserData;

                    console.log("📋 Callback tracking check:", {
                        wasAlreadyLoggedIn: wasAlreadyLoggedIn,
                        wasLoggedInBeforeSaveSearch: wasLoggedInBeforeSaveSearch,
                        willTrack: !wasAlreadyLoggedIn && !wasLoggedInBeforeSaveSearch
                    });

                    // Only track if user was NOT already logged in (they just registered/logged in)
                    if (!wasAlreadyLoggedIn && !wasLoggedInBeforeSaveSearch) {
                        console.log("✅ User just logged in, tracking save search now...");
                        var queryString = idx("#IDX-saveSearchForm .IDX-queryString").val();
                        var searchPageID = idx("#IDX-saveSearchForm .IDX-searchPageID").val();
                        var newUserData = getCookie("IDX-userData");

                        console.log("📊 Tracking data:", {
                            queryString: queryString,
                            searchPageID: searchPageID,
                            userData: newUserData
                        });

                        idx.ajax({
                            url: webhookUrl,
                            dataType: "json",
                            data: {
                                webhook_id: webhookId,
                                websiteurl: window.location.href,
                                pathname: window.location.pathname,
                                idx_userdata: newUserData,
                                idx_potential_userdata: getCookie("IDX-potentialUserData"),
                                savedLinkQueryString: queryString,
                                savedLink: searchPageID,
                                action: "saveSearch"
                            },
                            cache: false,
                            success: function() {
                                console.log("✅ Save search webhook sent successfully");
                            },
                            error: function(xhr, status, error) {
                                console.error("❌ Webhook error:", status, error);
                            }
                        });
                        console.log("✅ Save search tracked after registration/login");
                    } else {
                        console.log("⏭️ User was already logged in - skipping callback tracking (already tracked by click handler)");
                    }

                    // Reset the flag
                    wasLoggedInBeforeSaveSearch = false;
                } else {
                    console.warn("⚠️ saveSearchSuccess callback fired but status is not success:", responseText);
                }
            };
            return true;
        } else {
            console.warn("⚠️ window.saveSearchSuccess not found yet (type: " + typeof window.saveSearchSuccess + ")");
            return false;
        }
    };

    // Try to setup wrapper immediately
    if (!setupSaveSearchWrapper()) {
        // Retry multiple times with increasing delays
        var retryCount = 0;
        var maxRetries = 5;
        var retryInterval = setInterval(function() {
            retryCount++;
            console.log("🔄 Retry #" + retryCount + " - attempting to wrap saveSearchSuccess...");
            if (setupSaveSearchWrapper() || retryCount >= maxRetries) {
                clearInterval(retryInterval);
                if (retryCount >= maxRetries) {
                    console.error("❌ Could not find window.saveSearchSuccess after " + maxRetries + " retries");
                }
            }
        }, 500);
    }
}

// Global flag to track if user was logged in before save (to prevent duplicate tracking)
var wasLoggedInBeforeSave = false;

// Function to handle save property tracking with support for soft login
function handleSavePropertyTracking() {
    console.log("Initializing save property tracking...");

    // Check if we have a pending save property after page reload (from login/registration)
    var pendingPropertyProcessed = false; // Flag to prevent duplicate processing
    var checkPendingSaveProperty = function() {
        try {
            // Check if we already processed a pending save
            if (pendingPropertyProcessed) {
                console.log("⏭️ Pending property save already processed, skipping duplicate check");
                return;
            }

            var pendingSave = sessionStorage.getItem("pendingSaveProperty");
            if (pendingSave) {
                console.log("🔄 Found pending save property after page reload:", pendingSave);
                var saveData = JSON.parse(pendingSave);

                // Check if user is now logged in
                var isLoggedIn = idx("#IDX-main").hasClass("IDX-loggedIn");
                var userData = getCookie("IDX-userData");

                console.log("📋 Post-reload login check:", {
                    isLoggedIn: isLoggedIn,
                    hasUserData: !!userData
                });

                if (isLoggedIn && userData) {
                    console.log("✅ User is now logged in after reload, tracking save property...");

                    // Mark as processed IMMEDIATELY to prevent duplicates
                    pendingPropertyProcessed = true;
                    sessionStorage.removeItem("pendingSaveProperty");

                    idx.ajax({
                        url: webhookUrl,
                        dataType: "json",
                        data: {
                            webhook_id: webhookId,
                            websiteurl: saveData.url || window.location.href,
                            pathname: saveData.pathname || window.location.pathname,
                            idx_userdata: userData,
                            idx_potential_userdata: getCookie("IDX-potentialUserData"),
                            idx_id: saveData.idxID,
                            listing_id: saveData.listingID,
                            action: "saveProperty",
                            url: window.location.origin
                        },
                        cache: false,
                        success: function() {
                            console.log("✅ Pending save property webhook sent successfully after reload");
                        },
                        error: function(xhr, status, error) {
                            console.error("❌ Webhook error:", status, error);
                        }
                    });
                } else {
                    console.log("⏳ User still not logged in, will retry on next check");
                }
            }
        } catch (e) {
            console.error("❌ Error checking pending save property:", e);
        }
    };

    // Check for pending property saves on page load
    checkPendingSaveProperty();

    // Also check after a short delay (in case cookies/DOM arent ready immediately)
    setTimeout(checkPendingSaveProperty, 500);
    setTimeout(checkPendingSaveProperty, 1500);

    // Watch for successful save property after registration/login
    // This captures the case when user had to login first
    var setupSavePropertyWrapper = function() {
        if (typeof window.savePropertySuccess === "function") {
            console.log("✅ Found window.savePropertySuccess, wrapping it now");
            var originalSavePropertySuccess = window.savePropertySuccess;
            window.savePropertySuccess = function(responseText, statusText, xhr, $form) {
                console.log("🎯 savePropertySuccess callback fired!", responseText);

                // Call original function first
                originalSavePropertySuccess(responseText, statusText, xhr, $form);

                // Track the event after successful save
                if (responseText && responseText.status === "success") {
                    // Check if user was already logged in before the save
                    // If they were, the click handler already tracked it, so skip this
                    var currentUserData = getCookie("IDX-userData");
                    var wasAlreadyLoggedIn = idx_userdata && idx_userdata === currentUserData;

                    console.log("📋 Callback tracking check:", {
                        wasAlreadyLoggedIn: wasAlreadyLoggedIn,
                        wasLoggedInBeforeSave: wasLoggedInBeforeSave,
                        willTrack: !wasAlreadyLoggedIn && !wasLoggedInBeforeSave
                    });

                    // Only track if user was NOT already logged in (they just registered/logged in)
                    if (!wasAlreadyLoggedIn && !wasLoggedInBeforeSave) {
                        console.log("✅ User just logged in, tracking save property now...");
                        var newUserData = getCookie("IDX-userData");

                        console.log("📊 Tracking data:", {
                            idxID: responseText.idxID,
                            listingID: responseText.listingID,
                            userData: newUserData
                        });

                        idx.ajax({
                            url: webhookUrl,
                            dataType: "json",
                            data: {
                                webhook_id: webhookId,
                                websiteurl: window.location.href,
                                pathname: window.location.pathname,
                                idx_userdata: newUserData,
                                idx_potential_userdata: getCookie("IDX-potentialUserData"),
                                idx_id: responseText.idxID,
                                listing_id: responseText.listingID,
                                action: "saveProperty",
                                url: window.location.origin
                            },
                            cache: false,
                            success: function() {
                                console.log("✅ Save property webhook sent successfully");
                            },
                            error: function(xhr, status, error) {
                                console.error("❌ Webhook error:", status, error);
                            }
                        });
                        console.log("✅ Save property tracked after registration/login");
                    } else {
                        console.log("⏭️ User was already logged in - skipping callback tracking (already tracked by click handler)");
                    }

                    // Reset the flag
                    wasLoggedInBeforeSave = false;
                } else {
                    console.warn("⚠️ savePropertySuccess callback fired but status is not success:", responseText);
                }
            };
            return true;
        } else {
            console.warn("⚠️ window.savePropertySuccess not found yet (type: " + typeof window.savePropertySuccess + ")");
            return false;
        }
    };

    // Try to setup wrapper immediately
    if (!setupSavePropertyWrapper()) {
        // Retry multiple times with increasing delays
        var retryCount = 0;
        var maxRetries = 5;
        var retryInterval = setInterval(function() {
            retryCount++;
            console.log("🔄 Retry #" + retryCount + " - attempting to wrap savePropertySuccess...");
            if (setupSavePropertyWrapper() || retryCount >= maxRetries) {
                clearInterval(retryInterval);
                if (retryCount >= maxRetries) {
                    console.error("❌ Could not find window.savePropertySuccess after " + maxRetries + " retries");
                }
            }
        }, 500);
    }
}

// Sending AJAX request based on conditions
if (idx_userdata) {
    idx.ajax({
        url: webhookUrl,
        dataType: "json",
        data: {
            webhook_id: webhookId,
            websiteurl: window.location.href,
            pathname: window.location.pathname,
            idx_userdata: idx_userdata,
            idx_potential_userdata: idx_potential_userdata
        },
        cache: false
    });

    // Initialize save search and save property tracking
    handleSaveSearchTracking();
    handleSavePropertyTracking();

    // Adding click event listener
    document.body.addEventListener("click", function(event) {
        var target = event.target.hash ? event.target.hash : (event.target.parentNode ? event.target.parentNode.hash : null);
        if (target) {
            var action = target.slice(1);
            if (action == "saveProperty") {
                var softLoggedIn = idx("#IDX-registration").attr("data-softLoggedIn");
                var isLoggedIn = idx("#IDX-main").hasClass("IDX-loggedIn");

                var idxid = event.target.dataset.idxid ? event.target.dataset.idxid : event.target.parentNode.dataset.idxid;
                var listingid = event.target.dataset.listingid ? event.target.dataset.listingid : event.target.parentNode.dataset.listingid;

                // Only track if user is fully logged in (not soft-logged)
                if (isLoggedIn && !softLoggedIn) {
                    console.log("✅ User fully logged in, tracking save property immediately");

                    // Set flag to prevent duplicate tracking in callback
                    wasLoggedInBeforeSave = true;

                    idx.ajax({
                        url: webhookUrl,
                        dataType: "json",
                        data: {
                            webhook_id: webhookId,
                            websiteurl: window.location.href,
                            pathname: window.location.pathname,
                            idx_userdata: idx_userdata,
                            idx_potential_userdata: idx_potential_userdata,
                            idx_id: idxid,
                            listing_id: listingid,
                            action: action,
                            url: window.location.origin
                        },
                        cache: false
                    });
                } else {
                    console.log("⏳ User not fully logged in - storing property save intent for post-login tracking");
                    try {
                        var pendingData = {
                            idxID: idxid,
                            listingID: listingid,
                            url: window.location.href,
                            pathname: window.location.pathname,
                            timestamp: Date.now()
                        };
                        sessionStorage.setItem("pendingSaveProperty", JSON.stringify(pendingData));
                        console.log("💾 Saved pending property to sessionStorage:", pendingData);
                    } catch (e) {
                        console.error("❌ Error saving pending save property:", e);
                    }
                }
            }
            // Note: saveSearch is now handled by handleSaveSearchTracking()
        }else{
            var target = event.target;
            var closestSaveProperty = target.closest(".IDX-saveProperty");
            if (closestSaveProperty) {
                var softLoggedIn = idx("#IDX-registration").attr("data-softLoggedIn");
                var isLoggedIn = idx("#IDX-main").hasClass("IDX-loggedIn");

                // Only track if user is fully logged in (not soft-logged)
                if (isLoggedIn && !softLoggedIn) {
                    // Set flag to prevent duplicate tracking in callback
                    wasLoggedInBeforeSave = true;

                    var closestCell = target.closest(".IDX-resultsCell") ? target.closest(".IDX-resultsCell") : closestSaveProperty;
                    var idxid = closestCell.getAttribute("data-idxid") ? closestCell.getAttribute("data-idxid") : null;
                    var listingid = closestCell.getAttribute("data-listingid") ? closestCell.getAttribute("data-listingid") : null;
                    idx.ajax({
                        url: webhookUrl,
                        dataType: "json",
                        data: {
                            webhook_id: webhookId,
                            websiteurl: window.location.href,
                            pathname: window.location.pathname,
                            idx_userdata: idx_userdata,
                            idx_potential_userdata: idx_potential_userdata,
                            idx_id: idxid,
                            listing_id: listingid,
                            action: "saveProperty",
                            url: window.location.origin
                        },
                        cache: false
                    });
                }
            } else {
                var closestCardFavorite = target.closest(".listing-card__favorite");
                if (closestCardFavorite) {
                    var softLoggedIn = idx("#IDX-registration").attr("data-softLoggedIn");
                    var isLoggedIn = idx("#IDX-main").hasClass("IDX-loggedIn");

                    // Only track if user is fully logged in (not soft-logged)
                    if (isLoggedIn && !softLoggedIn) {
                        // Set flag to prevent duplicate tracking in callback
                        wasLoggedInBeforeSave = true;

                        var dataContainer = target.closest("[idxid]") || target.closest("[data-idxid]");

                        if (!dataContainer) {
                            dataContainer = target.closest("article") || target.closest(".listing-card_wrap");
                        }

                        var idxid = null;
                        var listingid = null;

                        if (dataContainer) {
                            idxid = dataContainer.getAttribute("idxid") ||
                                   dataContainer.getAttribute("data-idxid");
                            listingid = dataContainer.getAttribute("listingid") ||
                                       dataContainer.getAttribute("data-listingid") ||
                                       dataContainer.getAttribute("listingcertificate");
                        }
                        idx.ajax({
                            url: webhookUrl,
                            dataType: "json",
                            data: {
                                webhook_id: webhookId,
                                websiteurl: window.location.href,
                                pathname: window.location.pathname,
                                idx_userdata: idx_userdata,
                                idx_potential_userdata: idx_potential_userdata,
                                idx_id: idxid,
                                listing_id: listingid,
                                action: "saveProperty",
                                url: window.location.origin
                            },
                            cache: false
                        });
                    }
                }
            }
        }
            
    });
    
    // Dedicated listener for .idx-details__favorite button (ProListings template)
    document.body.addEventListener("click", function(event) {
        var target = event.target;
        var favoriteButton = target.closest(".idx-details__favorite");
        
        if (favoriteButton) {
            var softLoggedIn = idx("#IDX-registration").attr("data-softLoggedIn");
            var isLoggedIn = idx("#IDX-main").hasClass("IDX-loggedIn");
            
            // Only track if user is fully logged in (not soft-logged)
            if (isLoggedIn && !softLoggedIn) {
                // Set flag to prevent duplicate tracking in callback
                wasLoggedInBeforeSave = true;
                
                // Get IDs from the button
                var idxid = favoriteButton.getAttribute("data-idxid") || null;
                var listingid = favoriteButton.getAttribute("data-listingid") || null;
                
                idx.ajax({
                    url: webhookUrl,
                    data: {
                        webhook_id: webhookId,
                        websiteurl: window.location.href,
                        pathname: window.location.pathname,
                        idx_userdata: idx_userdata,
                        idx_potential_userdata: idx_potential_userdata,
                        idx_id: idxid,
                        listing_id: listingid,
                        action: "saveProperty",
                        url: window.location.origin
                    },
                    cache: false
                });
            }
        }
    }, true); // true = use capture phase
    
    if (window.location.href.indexOf("idx/details/") > -1) {
        document.addEventListener("DOMContentLoaded", handleFormSubmission);
        handleListingProContactFormSubmission();
        var action = "recentlyViewedListing";
        idx.ajax({
            url: webhookUrl,
            dataType: "json",
            data: {
                webhook_id: webhookId,
                websiteurl: window.location.href,
                pathname: window.location.pathname,
                idx_userdata: idx_userdata,
                idx_potential_userdata: idx_potential_userdata,
                action: action,
                url: window.location.href
            },
            cache: false
        });
    }
    if (window.location.href.indexOf("idx/results") > -1) {
        var action = "recentSearchActivity";
        idx.ajax({
            url: webhookUrl,
            dataType: "json",
            data: {
                webhook_id: webhookId,
                websiteurl: window.location.href,
                pathname: window.location.pathname,
                idx_userdata: idx_userdata,
                idx_potential_userdata: idx_potential_userdata,
                action: action,
                url: window.location.href
            },
            cache: false
        });
    }
    if(window.location.href.indexOf("idx/scheduleshowing") > -1) {
        console.log("scheduleshowing logged in");
        document.addEventListener("DOMContentLoaded", handleFormSubmission);
    }
    if(window.location.href.indexOf("idx/moreinfo") > -1) {
        console.log("moreinfo logged in");
        document.addEventListener("DOMContentLoaded", handleFormSubmission);
    } 
    if (window.location.href.indexOf("idx/contact") > -1) {
        document.addEventListener("DOMContentLoaded", handleLeadContactFormSubmission);
    }
    if(window.location.href.indexOf("idx/homevaluation") > -1) {
        console.log("homevaluation - logged in");
        document.addEventListener("DOMContentLoaded", handleFormSubmission);
    }
    if(window.location.href.indexOf("idx/market-reports") > -1) {
        console.log("market-reports - logged in");
        document.addEventListener("DOMContentLoaded", () => {
            var locationReport = document.querySelector(".idx-mk-location-title");
            if (locationReport) {
                console.log(locationReport.textContent);
                var action = "marketReportViewed";
                idx.ajax({
                    url: webhookUrl,
                    dataType: "json",
                    data: {
                        webhook_id: webhookId,
                        websiteurl: window.location.href,
                        pathname: window.location.pathname,
                        idx_userdata: idx_userdata,
                        idx_potential_userdata: idx_potential_userdata,
                        action: action,
                        url: window.location.href,
                        location: locationReport.textContent, 
                    },
                    cache: false
                });
                // Use MutationObserver to detect when signup confirmation appears
                var signupDetected = false;
                var observer = new MutationObserver(function(mutations) {
                    if (signupDetected) return;

                    mutations.forEach(function(mutation) {
                        if (signupDetected) return;

                        mutation.addedNodes.forEach(function(node) {
                            if (signupDetected) return;

                            if (node.nodeType === 1) {
                                // Check if the confirmation modal appeared
                                var confirmationModal = node.querySelector ? node.querySelector(".idx-mk-report-confirmation") : null;
                                if (!confirmationModal && node.classList && node.classList.contains("idx-mk-report-confirmation")) {
                                    confirmationModal = node;
                                }

                                if (confirmationModal) {
                                    signupDetected = true;
                                    console.log("Market Report signup confirmation detected");
                                    var action = "marketReportSignup";
                                    idx.ajax({
                                        url: webhookUrl,
                                        dataType: "json",
                                        data: {
                                            webhook_id: webhookId,
                                            websiteurl: window.location.href,
                                            pathname: window.location.pathname,
                                            idx_userdata: idx_userdata,
                                            idx_potential_userdata: idx_potential_userdata,
                                            action: action,
                                            url: window.location.href,
                                            location: locationReport.textContent,
                                        },
                                        cache: false
                                    });
                                    // Disconnect observer after first detection to prevent duplicates
                                    observer.disconnect();
                                }
                            }
                        });
                    });
                });

                // Start observing the document body for changes
                observer.observe(document.body, {
                    childList: true,
                    subtree: true
                });
            }
        });
    }
    if(window.location.href.indexOf("/i/") > -1) {
        console.log("saved link - logged in");
        document.addEventListener("DOMContentLoaded", () => {
            var action = "savedLinkViewed";
            console.log(action);
            idx.ajax({
                url: webhookUrl,
                dataType: "json",
                data: {
                    webhook_id: webhookId,
                    websiteurl: window.location.href,
                    pathname: window.location.pathname,
                    idx_userdata: idx_userdata,
                    idx_potential_userdata: idx_potential_userdata,
                    action: action,
                    url: window.location.href,
                    title: document.title
                },
                cache: false
            });
        });
    }
} else {
    // Initialize save search and save property tracking for non-logged-in users too
    handleSaveSearchTracking();
    handleSavePropertyTracking();

    if(window.location.href.indexOf("idx/details/") > -1) {
        document.addEventListener("DOMContentLoaded", handleFormSubmission);
        handleListingProContactFormSubmission();
        var action = "recentlyViewedListing";
        idx.ajax({
            url: webhookUrl,
            dataType: "json",
            data: {
                webhook_id: webhookId,
                websiteurl: window.location.href,
                pathname: window.location.pathname,
                idx_userdata: idx_userdata,
                idx_potential_userdata: idx_potential_userdata,
                action: action,
                url: window.location.href
            },
            cache: false
        });

}else if(window.location.href.indexOf("idx/scheduleshowing") > -1) {
    console.log("scheduleshowing");
    document.addEventListener("DOMContentLoaded", handleFormSubmission);
} else if(window.location.href.indexOf("idx/contact") > -1) {
    document.addEventListener("DOMContentLoaded", handleContactFormSubmission);
} else if(window.location.href.indexOf("idx/moreinfo") > -1) {
    console.log("moreinfo - not registered");
    document.addEventListener("DOMContentLoaded", handleFormSubmission);
} else if(window.location.href.indexOf("idx/homevaluation") > -1) {
    console.log("homevaluation - not registered");
    document.addEventListener("DOMContentLoaded", handleFormSubmission);
} else if(window.location.href.indexOf("/i/") > -1) {
    console.log("saved link - not registered");
    document.addEventListener("DOMContentLoaded", () => {
        var action = "savedLinkViewed";
            console.log(action);
            idx.ajax({
                url: webhookUrl,
                dataType: "json",
                data: {
                    webhook_id: webhookId,
                    websiteurl: window.location.href,
                    pathname: window.location.pathname,
                    idx_potential_userdata: idx_potential_userdata,
                    action: action,
                    url: window.location.href,
                    title: document.title
                },
                cache: false
            });
        });
    } else if(window.location.href.indexOf("idx/market-reports") > -1) {
    console.log("market-reports - not registered");
    document.addEventListener("DOMContentLoaded", () => {
        var locationReport = document.querySelector(".idx-mk-location-title");
        if (locationReport) {
            var action = "marketReportViewed";
            idx.ajax({
                url: webhookUrl,
                dataType: "json",
                data: {
                    webhook_id: webhookId,
                    websiteurl: window.location.href,
                    pathname: window.location.pathname,
                    idx_userdata: idx_userdata,
                    idx_potential_userdata: idx_potential_userdata,
                    action: action,
                    url: window.location.href,
                    location: locationReport.textContent, 
                },
                cache: false
            });
            // Use MutationObserver to detect when signup confirmation appears
            var signupDetected = false;
            var observer = new MutationObserver(function(mutations) {
                if (signupDetected) return;

                mutations.forEach(function(mutation) {
                    if (signupDetected) return;

                    mutation.addedNodes.forEach(function(node) {
                        if (signupDetected) return;

                        if (node.nodeType === 1) {
                            // Check if the confirmation modal appeared
                            var confirmationModal = node.querySelector ? node.querySelector(".idx-mk-report-confirmation") : null;
                            if (!confirmationModal && node.classList && node.classList.contains("idx-mk-report-confirmation")) {
                                confirmationModal = node;
                            }

                            if (confirmationModal) {
                                signupDetected = true;
                                console.log("Market Report signup confirmation detected");
                                var action = "marketReportSignup";
                                idx.ajax({
                                    url: webhookUrl,
                                    dataType: "json",
                                    data: {
                                        webhook_id: webhookId,
                                        websiteurl: window.location.href,
                                        pathname: window.location.pathname,
                                        idx_userdata: idx_userdata,
                                        idx_potential_userdata: idx_potential_userdata,
                                        action: action,
                                        url: window.location.href,
                                        location: locationReport.textContent,
                                    },
                                    cache: false
                                });
                                // Disconnect observer after first detection to prevent duplicates
                                observer.disconnect();
                            }
                        }
                    });
                });
            });

            // Start observing the document body for changes
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        }
    });
} else {
    // Fallback for pages not covered by specific conditions
    idx.ajax({
        url: webhookUrl,
        dataType: "json",
        data: {
            webhook_id: webhookId,
            websiteurl: window.location.href,
            pathname: window.location.pathname,
            idx_userdata: idx_userdata,
            idx_potential_userdata: idx_potential_userdata
        },
        cache: false
    });
}
} // End of idxWebhookScriptLoaded check
}
// ]]>            
