/* Help4 Builder Suite tutorial search */
(function () {
    "use strict";

    function ready(callback) {
        if (document.readyState === "loading") {
            document.addEventListener("DOMContentLoaded", callback, { once: true });
            return;
        }
        callback();
    }

    function normalize(value) {
        var text = String(value || "").toLowerCase().trim();
        if (typeof text.normalize === "function") {
            text = text.normalize("NFKD").replace(/[\u0300-\u036f]/g, "");
        }
        return text.replace(/\s+/g, " ");
    }

    function hydrateTutorialVideo(video) {
        if (!video || video.getAttribute("data-h4bs-lazy-hydrated") === "1") {
            return;
        }

        var source = video.getAttribute("data-src") || "";
        var poster = video.getAttribute("data-poster") || "";
        if (source) {
            video.setAttribute("src", source);
        }
        if (poster) {
            video.setAttribute("poster", poster);
        }
        video.querySelectorAll("track[data-src]").forEach(function (track) {
            var trackSource = track.getAttribute("data-src") || "";
            if (trackSource) {
                track.setAttribute("src", trackSource);
            }
        });
        video.setAttribute("data-h4bs-lazy-hydrated", "1");
    }

    function prepareTutorialVideos() {
        var videos = Array.prototype.slice.call(
            document.querySelectorAll("video[data-h4bs-lazy-tutorial-video]")
        );
        if (!videos.length) {
            return;
        }

        var observer = null;
        if ("IntersectionObserver" in window) {
            observer = new window.IntersectionObserver(function (entries) {
                entries.forEach(function (entry) {
                    if (!entry.isIntersecting) {
                        return;
                    }
                    hydrateTutorialVideo(entry.target);
                    observer.unobserve(entry.target);
                });
            }, { rootMargin: "240px 0px" });
        }

        videos.forEach(function (video, index) {
            var hydrate = function () {
                hydrateTutorialVideo(video);
                if (observer) {
                    observer.unobserve(video);
                }
            };
            video.addEventListener("focus", hydrate, { once: true });
            video.addEventListener("pointerenter", hydrate, { once: true });
            video.addEventListener("touchstart", hydrate, { once: true, passive: true });
            if (observer) {
                observer.observe(video);
            } else if (index < 2) {
                hydrate();
            }
        });
    }

    ready(function () {
        prepareTutorialVideos();
        var roots = document.querySelectorAll("[data-h4-doc-search-root]");
        roots.forEach(function (root) {
            var input = root.querySelector("[data-h4-doc-search-input]");
            var clear = root.querySelector("[data-h4-doc-search-clear]");
            var status = root.querySelector("[data-h4-doc-search-status]");
            var empty = root.querySelector("[data-h4-doc-search-empty]");
            var items = Array.prototype.slice.call(root.querySelectorAll("[data-h4-doc-item]"));
            var filters = Array.prototype.slice.call(root.querySelectorAll("[data-h4-doc-filter]"));
            if (!input || !clear || !status || !empty || !items.length) {
                return;
            }

            var params = new URLSearchParams(window.location.search);
            var activeCategory = normalize(params.get("topic") || "all");
            var validCategories = filters.map(function (button) {
                return normalize(button.getAttribute("data-h4-doc-filter"));
            });
            if (validCategories.indexOf(activeCategory) === -1) {
                activeCategory = "all";
            }
            input.value = String(params.get("guide") || "").slice(0, 120);

            function updateUrl(query) {
                var next = new URL(window.location.href);
                if (query) {
                    next.searchParams.set("guide", query);
                } else {
                    next.searchParams.delete("guide");
                }
                if (activeCategory !== "all") {
                    next.searchParams.set("topic", activeCategory);
                } else {
                    next.searchParams.delete("topic");
                }
                window.history.replaceState({}, "", next.toString());
            }

            function applyFilters() {
                var query = normalize(input.value).slice(0, 120);
                var terms = query ? query.split(" ").filter(Boolean) : [];
                var visible = 0;

                items.forEach(function (item) {
                    var text = normalize(item.getAttribute("data-h4-doc-text"));
                    var category = normalize(item.getAttribute("data-h4-doc-category"));
                    var categoryMatch = activeCategory === "all" || category === activeCategory;
                    var queryMatch = terms.every(function (term) {
                        return text.indexOf(term) !== -1;
                    });
                    var show = categoryMatch && queryMatch;
                    item.hidden = !show;
                    if (show) {
                        visible += 1;
                    }
                });

                filters.forEach(function (button) {
                    var selected = normalize(button.getAttribute("data-h4-doc-filter")) === activeCategory;
                    button.setAttribute("aria-pressed", selected ? "true" : "false");
                });
                clear.hidden = !query && activeCategory === "all";
                empty.hidden = visible !== 0;
                status.textContent = visible === 1 ? "1 guide found." : visible + " guides found.";
                updateUrl(query);
            }

            filters.forEach(function (button) {
                button.addEventListener("click", function () {
                    activeCategory = normalize(button.getAttribute("data-h4-doc-filter")) || "all";
                    applyFilters();
                });
            });
            input.addEventListener("input", applyFilters);
            input.addEventListener("keydown", function (event) {
                if (event.key === "Escape" && input.value) {
                    input.value = "";
                    applyFilters();
                }
            });
            clear.addEventListener("click", function () {
                input.value = "";
                activeCategory = "all";
                applyFilters();
                input.focus();
            });

            root.setAttribute("data-h4-doc-search-ready", "1");
            applyFilters();
        });
    });
})();
