
    (function() {
        console.log('Agency Dashboard Local script loaded');
        const isActiveForAll = 1;
        const locationIds = null;
        const featureList = ["open_map","dashboard_button"];

        const waitForElement = selector => new Promise(resolve => {
            const element = document.querySelector(selector);
            if (element) return resolve(element);
            const observer = new MutationObserver(() => {
                const element = document.querySelector(selector);
                if (element) { observer.disconnect(); resolve(element); }
            });
            observer.observe(document.body, { childList: true, subtree: true });
        });

        const STYLES = `.idxaddons-button{text-align:center;text-decoration:none;color:var(--idxaddons-button-text-color,#4b5563);font-size:15px;border-radius:5px;}.idxaddons-button:hover{background-color:#F2F4F7;color:var(--idxaddons-button-text-hover-color,#f1f5f9);border-color:#9ca3af}.idx-modal{position:fixed;inset:0;background:rgba(0,0,0,0.7);opacity:0;visibility:hidden;transform:scale(1.1);transition:visibility 0s linear 0.25s,opacity 0.25s 0s,transform 0.25s;font-family:"Open Sans","Helvetica Neue",Helvetica,sans-serif;z-index:1000}.idx-modal-content{width:100%;background-color:white;max-width:768px;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);border-radius:12px;max-height:672px!important;transition:max-height 0.15s ease-out;overflow:hidden}@media(min-width:480px){.idx-modal-content{width:100%;height:90%;max-width:1152px}}.idx-close-button{position:absolute;top:0;right:0;display:flex;justify-content:center;align-items:center;width:40px;height:40px;cursor:pointer;border-radius:0.25rem;font-size:25px}.idx-close-button:hover{background-color:#e2e8f0}.idx-show-modal{opacity:1;visibility:visible;transform:scale(1);transition:visibility 0s linear 0s,opacity 0.25s 0s,transform 0.25s}`;

        const BUTTON_SVG = `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 600 262.8" width="30" height="26"><g><path style="fill:#4b5563;" d="M-1,0h64.4v262.8H-1V0z"/><path style="fill:#4b5563;" d="M105.4,262.8V0h108c21.86,0,41.06,3.2,57.6,9.6c16.53,6.4,30.2,15.34,41,26.8c10.8,11.47,18.93,25.34,24.4,41.6c5.46,16.27,8.2,34.27,8.2,54c0,19.74-2.74,37.74-8.2,54c-5.47,16.27-13.6,30.07-24.4,41.4c-10.8,11.34-24.47,20.07-41,26.2c-16.54,6.14-35.74,9.2-57.6,9.2H105.4z M211.8,56.4h-42v150h44c22.4,0,39.26-6.2,50.6-18.6c11.33-12.4,17-31,17-55.8c0-25.33-5.6-44.26-16.8-56.8C253.4,62.67,235.8,56.4,211.8,56.4z"/><path style="fill:#4b5563;" d="M599,262.8h-76l-52.8-105.6l-53.6,105.6h-75.2l78.8-132.4L339.4,0h74.8l56,105.6L525,0h76l-81.2,130.4L599,262.8z"/></g></svg>`;


        // Check if URL has structure: .../location/{locationId}/contacts/detail/...
        const hasValidUrlStructure = (url) => {
            try {
                const parts = new URL(url).pathname.split('/').filter(Boolean);
                const locIndex = parts.indexOf('location');
                return locIndex !== -1 && locIndex + 1 < parts.length && url.includes("contacts/detail");
            } catch { return false; }
        };

        // Extract and validate location ID from URL, returns ID if valid or null
        const getValidLocationId = (url) => {
            try {
                const parts = new URL(url).pathname.split('/').filter(Boolean);
                const locIndex = parts.indexOf('location');
                const locationId = locIndex !== -1 && locIndex + 1 < parts.length ? parts[locIndex + 1] : null;
                return locationId && locationIds.includes(locationId) ? locationId : null;
            } catch { return null; }
        };

        /**
         * Main URL validation function
         * - If active for all: only check URL structure
         * - If not active for all: check URL structure AND validate location ID
         */
        const validateUrl = (url) => {
            if (!hasValidUrlStructure(url)) return false;
            return isActiveForAll || getValidLocationId(url) !== null;
        };

        let messageHandler = null;
        let parentObserver = null;

        // Backward compatibility function to try multiple selectors
        const findParentElement = () => {
            const selectors = [
                // Version 2 selector (new UI) - target the inner flex container
                'div[class*="flex"][class*="justify-between"][class*="items-center"][class*="px-3"][class*="border-b"][class*="border-gray-200"] > div[class*="flex"][class*="items-center"][class*="gap-4"]',
                // Version 1 selector (old UI)
                '.message-header-actions:not(.contact-detail-actions)'
            ];

            for (const selector of selectors) {
                const element = document.querySelector(selector);
                if (element) {
                    console.log(`IDXBroker: Found parent element`);
                    return element;
                }
            }
            return null;
        };

        // Helper function to clean up existing elements
        const cleanupExistingElements = () => {
            document.querySelectorAll('.idxaddons-button, .idx-modal').forEach(el => el.remove());
            if (messageHandler) {
                window.removeEventListener("message", messageHandler);
                messageHandler = null;
            }
            if (parentObserver) {
                parentObserver.disconnect();
                parentObserver = null;
            }
        };

        // Helper function to wait for parent element
        const waitForParentElement = (callback) => {
            console.log('IDXBroker: Parent element not found, waiting for it...');
            Promise.race([
                waitForElement('div[class*="flex"][class*="justify-between"][class*="items-center"][class*="px-3"][class*="border-b"][class*="border-gray-200"] > div[class*="flex"][class*="items-center"][class*="gap-4"]'),
                waitForElement('.message-header-actions:not(.contact-detail-actions)')
            ]).then(foundParent => {
                if (document.querySelector('.idxaddons-button')) return;
                callback(foundParent);
            });
        };

        // Helper function to validate parent element
        const validateParentElement = (parentDiv) => {
            if (!parentDiv) return false;
            if (document.querySelector('.idxaddons-button')) return false;
            if (!document.contains(parentDiv)) {
                return false;
            }
            return true;
        };

        const createIdxButton = url => {
            if (!validateUrl(url)) return;

            // Clean up existing elements
            cleanupExistingElements();

            // Try to find parent element with backward compatibility
            const parentDiv = findParentElement();

            // Handle different scenarios
            if (!parentDiv || !validateParentElement(parentDiv)) {
                waitForParentElement(insertButtonAndModal);
                return;
            }

            insertButtonAndModal(parentDiv);
        };

        const insertButtonAndModal = (parentDiv) => {
            if (!document.querySelector('style[data-idxbroker]')) {
                const style = document.createElement("style");
                style.innerHTML = STYLES;
                style.setAttribute('data-idxbroker', '');
                document.head.appendChild(style);
            }

            const button = Object.assign(document.createElement("button"), {
                innerHTML: BUTTON_SVG,
                className: "idxaddons-button"
            });

            const modal = Object.assign(document.createElement("div"), {
                className: "idx-modal"
            });

            const location_id = window.location.href.split('/')[5];
            const contact_id = window.location.href.split('/').pop().split('?')[0];
            console.log('location_id', location_id);
            console.log('contact_id', contact_id);

            button.addEventListener("click", () => {
                const url = `https://idxaddons.com/embedv2?location_id=${location_id}&p=lead-idx-button&contact_id=${contact_id}&idxbutton=1`;
                const modalContent = Object.assign(document.createElement("div"), {
                    className: "idx-modal-content",
                    innerHTML: `<span class="idx-close-button">&times;</span><iframe src="${url}" style="width:100%;height:670px;border:none;"></iframe>`
                });

                modalContent.querySelector(".idx-close-button").addEventListener("click", () => modal.classList.remove("idx-show-modal"));

                modal.appendChild(modalContent);
                modal.classList.add("idx-show-modal");
            });

            messageHandler = (event) => {
                if (event.data === "buttonClicked") modal.classList.remove("idx-show-modal");
            };
            window.addEventListener("message", messageHandler);

            // Handle different insertion methods for v1 vs v2
            if (parentDiv.classList.contains('message-header-actions')) {
                // Version 1: Insert into .flex child element
                const flexBlock = parentDiv.querySelector('.flex');
                if (flexBlock) {
                    flexBlock.insertBefore(button, flexBlock.firstChild);
                } else {
                    parentDiv.prepend(button);
                }
            } else {
                // Version 2: Direct prepend
                parentDiv.prepend(button);
            }

            document.body.appendChild(modal);

            // Set up observer to watch for parent element removal
            setupParentObserver(parentDiv);
        };

        // Set up mutation observer to detect when parent element is removed
        const setupParentObserver = (parentDiv) => {
            if (parentObserver) {
                parentObserver.disconnect();
            }

            parentObserver = new MutationObserver((mutations) => {
                for (const mutation of mutations) {
                    if (mutation.type === 'childList') {
                        // Check if our button was removed
                        const buttonRemoved = Array.from(mutation.removedNodes).some(node =>
                            node.classList && node.classList.contains('idxaddons-button')
                        );

                        // Check if parent element was removed
                        const parentRemoved = !document.contains(parentDiv);

                        if (buttonRemoved || parentRemoved) {
                            console.log('IDXBroker: Button or parent element removed, recreating...');
                            parentObserver.disconnect();
                            parentObserver = null;

                            // Wait a bit for the DOM to settle, then recreate
                            setTimeout(() => {
                                createIdxButton(location.href);
                            }, 100);
                            break;
                        }
                    }
                }
            });

            // Observe the parent element and its ancestors
            let currentElement = parentDiv;
            while (currentElement && currentElement !== document.body) {
                parentObserver.observe(currentElement, {
                    childList: true,
                    subtree: true
                });
                currentElement = currentElement.parentElement;
            }
        };

        window.waitForElement = waitForElement;

        // Setup route events for both UI versions
        ['routeLoaded', 'routeChangeEvent'].forEach(event =>
            window.addEventListener(event, () =>{
                createIdxButton(location.href)
            })
        );
    })();

