document.addEventListener("DOMContentLoaded", () => {
    const stickyHeader = document.querySelector("[data-sticky-header]");
    const typewriterItems = document.querySelectorAll(".ssa-hero-title .prespa-saas-animated-text");
    const setTypedWidth = (item, words) => {
        if (!words.length) {
            return;
        }

        const computed = window.getComputedStyle(item);
        const measure = document.createElement("span");

        measure.style.position = "absolute";
        measure.style.visibility = "hidden";
        measure.style.whiteSpace = "nowrap";
        measure.style.fontFamily = computed.fontFamily;
        measure.style.fontSize = computed.fontSize;
        measure.style.fontWeight = computed.fontWeight;
        measure.style.letterSpacing = computed.letterSpacing;
        measure.style.textTransform = computed.textTransform;
        document.body.appendChild(measure);

        let maxWidth = 0;

        words.forEach((word) => {
            measure.textContent = word;
            maxWidth = Math.max(maxWidth, measure.getBoundingClientRect().width);
        });

        document.body.removeChild(measure);
        item.style.setProperty("--ssa-typed-width", `${Math.ceil(maxWidth + 18)}px`);
    };

    if (stickyHeader) {
        const onScroll = () => {
            stickyHeader.classList.toggle("is-scrolled", window.scrollY > 16);
        };

        onScroll();
        window.addEventListener("scroll", onScroll, { passive: true });
    }

    const revealItems = document.querySelectorAll(".reveal-on-scroll");

    if (revealItems.length) {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    entry.target.classList.add("is-visible");
                    observer.unobserve(entry.target);
                }
            });
        }, {
            threshold: 0.18,
        });

        revealItems.forEach((item) => observer.observe(item));
    }

    if (typewriterItems.length) {
        const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

        typewriterItems.forEach((item, index) => {
            const explicitWords = (item.dataset.typedWords || "")
                .split("|")
                .map((word) => word.trim())
                .filter(Boolean);
            const originalText = (item.dataset.typedText || item.textContent || "").trim();
            const derivedWords = originalText
                .split(/,|\band\b/i)
                .map((word) => word.trim())
                .filter(Boolean);
            const words = explicitWords.length
                ? explicitWords
                : (derivedWords.length ? derivedWords : [originalText]);

            if (!words.length || !words[0]) {
                return;
            }

            if (
                words.length === 3 &&
                words[0].toLowerCase() === "click" &&
                words[1].toLowerCase() === "lead" &&
                words[2].toLowerCase() === "sale"
            ) {
                words.push("server-side");
            }

            item.dataset.typedText = words.join(", ");
            item.setAttribute("aria-label", words.join(", "));
            setTypedWidth(item, words);

            const typedValue = document.createElement("span");
            typedValue.className = "ssa-typed-value";
            item.replaceChildren(typedValue);

            if (prefersReducedMotion) {
                typedValue.textContent = item.dataset.typedText;
                item.classList.add("is-complete");
                return;
            }

            const startTyping = () => {
                let wordIndex = 0;
                let charIndex = 0;
                let deleting = false;

                const typeNext = () => {
                    const activeWord = words[wordIndex];

                    if (!deleting) {
                        charIndex += 1;
                        typedValue.textContent = activeWord.slice(0, charIndex);

                        if (charIndex < activeWord.length) {
                            window.setTimeout(typeNext, 75);
                            return;
                        }

                        item.classList.add("is-complete");
                        deleting = true;
                        window.setTimeout(typeNext, 1000);
                        return;
                    }

                    charIndex -= 1;
                    item.classList.remove("is-complete");
                    typedValue.textContent = activeWord.slice(0, Math.max(charIndex, 0));

                    if (charIndex > 0) {
                        window.setTimeout(typeNext, 42);
                        return;
                    }

                    deleting = false;
                    wordIndex = (wordIndex + 1) % words.length;
                    window.setTimeout(typeNext, 220);
                };

                typeNext();
            };

            window.setTimeout(startTyping, 350 + (index * 120));

            window.addEventListener("resize", () => {
                setTypedWidth(item, words);
            }, { passive: true });
        });
    }

    const supportChats = document.querySelectorAll("[data-support-chat]");

    if (supportChats.length) {
        supportChats.forEach((chat) => {
            const toggle = chat.querySelector("[data-support-chat-toggle]");
            const panel = chat.querySelector("[data-support-chat-panel]");
            const closeButtons = chat.querySelectorAll("[data-support-chat-close]");

            if (!toggle || !panel) {
                return;
            }

            const setOpen = (isOpen) => {
                chat.classList.toggle("is-open", isOpen);
                toggle.hidden = isOpen;
                panel.hidden = !isOpen;
                toggle.setAttribute("aria-expanded", isOpen ? "true" : "false");
            };

            setOpen(chat.classList.contains("is-open"));

            toggle.addEventListener("click", () => {
                setOpen(true);
            });

            closeButtons.forEach((button) => {
                button.addEventListener("click", () => {
                    setOpen(false);
                });
            });

            document.addEventListener("click", (event) => {
                if (!chat.classList.contains("is-open")) {
                    return;
                }

                if (!chat.contains(event.target)) {
                    setOpen(false);
                }
            });

            window.addEventListener("keydown", (event) => {
                if (event.key === "Escape" && chat.classList.contains("is-open")) {
                    setOpen(false);
                }
            });

            window.addEventListener("open-support-chat", () => {
                setOpen(true);
            });
        });
    }

    const supportChatTriggers = document.querySelectorAll("[data-open-support-chat]");
    if (supportChatTriggers.length) {
        supportChatTriggers.forEach((trigger) => {
            trigger.addEventListener("click", (event) => {
                event.preventDefault();
                window.dispatchEvent(new CustomEvent("open-support-chat"));
            });
        });
    }
});
