
(function () {
    if (window.__annie && window.__annie.widgetInitialized) {
        return;
    }
    const getStoredWidgetState = () => {
        try {
            const data = sessionStorage.getItem("annie-session-data");
            if (data) {
                const parsed = JSON.parse(data);
                return parsed.widgetState;
            }
        } catch (error) {
            console.error("Failed to read widget state:", error);
        }
        return null;
    };

    const updateStoredWidgetState = (isOpen) => {
        try {
            const data = sessionStorage.getItem("annie-session-data");
            const parsed = data ? JSON.parse(data) : {};
            parsed.widgetState = isOpen;
            sessionStorage.setItem("annie-session-data", JSON.stringify(parsed));
        } catch (error) {
            console.error("Failed to store widget state:", error);
        }
    };

    // Add new functions for label state
    const getLabelState = () => {
        try {
            const data = sessionStorage.getItem("annie-session-data");
            if (data) {
                const parsed = JSON.parse(data);
                return parsed.labelHidden;
            }
        } catch (error) {
            console.error("Failed to read label state:", error);
        }
        return false;
    };

    const updateLabelState = (isHidden) => {
        try {
            const data = sessionStorage.getItem("annie-session-data");
            const parsed = data ? JSON.parse(data) : {};
            parsed.labelHidden = isHidden;
            sessionStorage.setItem("annie-session-data", JSON.stringify(parsed));
        } catch (error) {
            console.error("Failed to store label state:", error);
        }
    };

    const WIDGET_BASE = "https://widget.helloannie.co"
    const WIDGET_CONTAINER_ID = "annie-widget-container-05075285-127a-45a5-a543-aed91740c3b8"

    // Clean up any existing widget containers
    const existingContainer = document.getElementById(WIDGET_CONTAINER_ID)
    if (existingContainer) {
        existingContainer.remove()
    }

    const script = document.createElement("script")
    script.src = "https://widget.helloannie.co/client/widget-client.global.js"

    script.onload = function () {
        if (window.__annie.widgetInitialized) {
            return;
        }

        const innerContainer = document.createElement("div")

        innerContainer.style.cssText = `
            display: flex;
            z-index: 2147483647;
            width: 100%;
            height: 100%;
            flex-direction: column;
            align-items: flex-end;
            justify-content: flex-end;
            gap: 4px;
        `

        // Add label element
        const label = document.createElement("div")
        label.innerText = "Hello, how may I help you today?"
        label.style.cssText = `
            background-color: #9A6C28;
            color: white;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
            font-family: system-ui, -apple-system, sans-serif;
            font-weight: 500;
            opacity: 0;
            transition: opacity 0.3s ease;
            white-space: normal;
            display: none;
            cursor: pointer;
            position: relative;
            padding-left: 48px;
            width: 325px;
            line-height: 1.4;
        `

        // Add close button for label
        const closeButton = document.createElement("button")
        closeButton.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>'
        closeButton.style.cssText = `
            position: absolute;
            top: -34px;
            right: 0px;
            background: rgba(209, 213, 219, 0.50);
            border: none;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            padding: 3px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: black;
            cursor: pointer;
            transition: background-color 0.2s ease;
        `

        closeButton.addEventListener("click", (e) => {
            e.stopPropagation(); // Prevent label click event from firing
            label.style.opacity = "0";
            updateLabelState(true); // Store that label has been hidden
            setTimeout(() => {
                label.style.display = "none";
            }, 300); // Match transition duration
        })

        closeButton.onmouseenter = function (e) {
            e.stopPropagation() // Stop the hover event from bubbling up to the label
            closeButton.style.background = "rgba(209, 213, 219, 1)"
        }

        closeButton.onmouseleave = function (e) {
            e.stopPropagation() // Stop the hover event from bubbling up to the label
            closeButton.style.background = "rgba(209, 213, 219, 0.50)"
        }

        label.appendChild(closeButton)

        // Add the dot indicator
        const dot = document.createElement("div")
        dot.style.cssText = `
            position: absolute;
            left: 22px;
            top: 50%;
            transform: translateY(-50%);
            width: 8px;
            height: 8px;
            background-color: white;
            border-radius: 50%;
            box-shadow: 0 0 0 4px rgba(255, 255, 255, 0.3);
        `
        
        label.appendChild(dot)

        const container = document.createElement("div")
        container.id = WIDGET_CONTAINER_ID
        container.className = "annie-widget-container"

        container.style.cssText = `
            display: flex;
            flex: 1;
            overflow: visible;
            z-index: 2147483647;
            width: 65px;
            height: 65px;
            position: fixed;
                 bottom: 12px; 
                 right: 12px;
        `

        if (window.innerWidth > 640) {
            container.style.cssText += `
                max-height: 680px;
                right: 24px; bottom: 24px;
            `
        }

        if (false) {
            container.style.minHeight = "600px";
        }

        const iframe = document.createElement("iframe")

        iframe.id = "05075285-127a-45a5-a543-aed91740c3b8"
        iframe.src = WIDGET_BASE
        iframe.title = "Annie Chat Widget"
        iframe.style.cssText = `
            width: 100%; 
            height: 0;
            position: absolute;
            z-index: 2147483647;
            background: transparent;
            border: none;
            pointer-events: none;
            visibility: hidden;
        `

        if (window.innerWidth > 640) {
            iframe.style.cssText += `
                width: 100%; 
                height: 100%;
                position: static;
            `
        }

        iframe.setAttribute("allow-top-navigation", "true")

        const toggleButton = document.createElement("button")
        toggleButton.setAttribute("aria-label", "Toggle chat widget")
        toggleButton.id = "annie-widget-toggle-button"
        const chatSvg = `<svg xmlns="https://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-message-circle" aria-hidden="true" role="img"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>`
        const chatClose = `<svg xmlns="https://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-circle-x" aria-hidden="true" role="img"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>`
        const toggleButtonDefaultStyles = `
            padding: 6px;
            font-size: 16px;
            border: none;
            color: white;
            cursor: pointer;
            transition: all 0.1s ease-in;
            width: 64px;
            height: 64px;
            min-width: 64px;
            min-height: 64px;
            max-width: 64px;
            max-height: 64px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        `

        const toggleButtonClosedStyles = `
            border-radius: 50%;
            background-color: #9A6C28;
        `

        const toggleButtonOpenStyles = `
            border-radius: 50%;
            background-color: #9A6C28;
        `

        toggleButton.innerHTML = chatSvg
        toggleButton.style.cssText = toggleButtonDefaultStyles + toggleButtonClosedStyles
        toggleButton.style.opacity = "0"
        innerContainer.appendChild(iframe)
        innerContainer.appendChild(label)
        innerContainer.appendChild(toggleButton)
        

        container.appendChild(innerContainer)

        if (false) {
            // Find the script that inserted this code and use its parent as container
            const targetContainer = document.getElementById('annie-widget-wrapper');

            if (targetContainer) {
                targetContainer.style.cssText = `
                    position: fixed;
                    top: 0;
                    right: 0;
                    bottom: 0;
                    left: 0;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    z-index: 2147483647;
                `
                targetContainer.appendChild(container);
            } else {
                document.body.appendChild(container);
            }
        } else {
            document.body.appendChild(container)
        }

        const widget = window.__annie.createWidgetClient({
            id: "05075285-127a-45a5-a543-aed91740c3b8",
            orgId: "5d3a6f09-0858-4fb5-8920-01f0f4c367f8",
            
            
            context: { position: "right", altOrgs: "" },
            onReady: () => {
                console.log("Widget is ready.")
                toggleButton.style.opacity = "1"
                window.__annie.widgetInitialized = true;
                
                // Show label after delay if widget is in preview state and label hasn't been hidden
                // Use mobile state for mobile screens, desktop state otherwise
                const isPreviewState = window.innerWidth <= 640 
                    ? true
                    : true;

                if (isPreviewState && !getLabelState()) {
                    setTimeout(() => {
                        label.style.display = "block"
                        setTimeout(() => {
                            label.style.opacity = "1"
                        }, 50) // Small delay to ensure transition works
                    }, 0)
                }
                
                const storedState = getStoredWidgetState();
                if (storedState !== null && storedState !== undefined) {
                    if (storedState) {
                        widget.toggle();
                    }
                } else {
                    if (window.innerWidth <= 640) {
                         //here
                    } else {
                         //here
                    }
                }
            },
            onStateChange: state => {
                updateStoredWidgetState(state);
                if(state === true) {
                    label.style.display = "none"  // Hide label when widget is open
                    toggleButton.innerHTML = chatClose
                    toggleButton.style.cssText = toggleButtonDefaultStyles + toggleButtonOpenStyles
                    
                    // Show and enable iframe when open
                    iframe.style.visibility = "visible"
                    iframe.style.pointerEvents = "auto"
                    
                    if (window.innerWidth <= 640) {
                        // Mobile styles
                        container.style.cssText = `
                            display: flex;
                            flex: 1;
                            overflow: hidden;
                            z-index: 2147483647;
                            width: 100%;
                            height: 100%;
                            pointer-events: auto;
                            position: fixed;
                                 bottom: 0;
                                 right: 0;
                        `
                    } else {
                        // Desktop styles
                        container.style.cssText = `
                            display: flex;
                            flex: 1;
                            overflow: hidden;
                            z-index: 2147483647;
                            width: 380px;
                            height: 680px;
                            pointer-events: auto;
                            position: fixed;
                                 bottom: 24px; 
                                 right: 24px;
                        `
                    }
                } else {
                    label.style.display = "block"
                    toggleButton.innerHTML = chatSvg
                    toggleButton.style.cssText = toggleButtonDefaultStyles + toggleButtonClosedStyles
                    
                    // Hide and disable iframe when closed
                    iframe.style.visibility = "hidden"
                    iframe.style.pointerEvents = "none"
                    
                    container.style.cssText = `
                        display: flex;
                        flex: 1;
                        overflow: visible;
                        z-index: 2147483647;
                        width: auto;
                        min-width: 65px;
                        height: auto;
                        pointer-events: auto;
                        position: fixed;
                             bottom: 24px; 
                             right: 24px;
                    `
                    if (window.innerWidth <= 640) {
                        container.style.cssText += `
                            
                            right: 12px;
                                   bottom: 12px;
                        `
                    }
                }
            }
        })

        toggleButton.addEventListener("click", function () {
            widget.toggle ? widget.toggle() : console.log("Toggle function not implemented")
        })

        toggleButton.onmousedown = function () {
            toggleButton.style.scale = "0.95"

            if (widget.isOpen()) {
                toggleButton.style.borderRadius = "50%"
            } else {
                toggleButton.style.borderRadius = "12px"
            }
        }

        toggleButton.onmouseup = function () {
            toggleButton.style.scale = "1"

            if (widget.isOpen()) {
                toggleButton.style.borderRadius = "50%"
            } else {
                toggleButton.style.borderRadius = "6px"
            }
        }

        toggleButton.onmouseenter = function () {
            toggleButton.style.backgroundColor = "#673900"
        }

        toggleButton.onmouseleave = function () {
            toggleButton.style.backgroundColor = "#9A6C28"
        }

        // Add click handler for label (add this near the other event listeners)
        label.addEventListener("click", function () {
            widget.toggle ? widget.toggle() : console.log("Toggle function not implemented")
        })

        // Add hover effects for label (modify this part)
        label.onmouseenter = function (e) {
            // Only change label color if we're not hovering the close button
            if (e.target === label) {
                label.style.backgroundColor = "#673900"
            }
        }

        label.onmouseleave = function (e) {
            // Only change label color if we're not hovering the close button
            if (e.target === label) {
                label.style.backgroundColor = "#9A6C28"
            }
        }
    }

    document.head.appendChild(script)
})();
