(function () {
    function escapeHtml(value) {
        return String(value || "")
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    function renderPages(items) {
        if (!Array.isArray(items) || !items.length) {
            return "";
        }
        return (
            '<section class="h4bs-search-result-group"><h4>Pages</h4><ul>' +
            items
                .map(function (item) {
                    return (
                        "<li><a href=\"" +
                        escapeHtml(item.url) +
                        "\">" +
                        escapeHtml(item.title) +
                        "</a><p>" +
                        escapeHtml(item.excerpt || "") +
                        "</p></li>"
                    );
                })
                .join("") +
            "</ul></section>"
        );
    }

    function renderPosts(items) {
        if (!Array.isArray(items) || !items.length) {
            return "";
        }
        return (
            '<section class="h4bs-search-result-group"><h4>Posts</h4><ul>' +
            items
                .map(function (item) {
                    return (
                        "<li><a href=\"" +
                        escapeHtml(item.url) +
                        "\">" +
                        escapeHtml(item.title) +
                        "</a><p>" +
                        escapeHtml(item.excerpt || "") +
                        "</p></li>"
                    );
                })
                .join("") +
            "</ul></section>"
        );
    }

    function renderProducts(items) {
        if (!Array.isArray(items) || !items.length) {
            return "";
        }
        return (
            '<section class="h4bs-search-result-group"><h4>Products</h4><ul>' +
            items
                .map(function (item) {
                    return (
                        "<li><strong>" +
                        escapeHtml(item.name) +
                        "</strong> | SKU: " +
                        escapeHtml(item.sku || "-") +
                        " | " +
                        escapeHtml(item.currency) +
                        " " +
                        Number(item.price || 0).toFixed(2) +
                        "</li>"
                    );
                })
                .join("") +
            "</ul></section>"
        );
    }

    function attachSearch(form) {
        if (!(form instanceof HTMLElement)) {
            return;
        }
        if (form.dataset.h4bsSearchInit === "1") {
            return;
        }

        const endpoint =
            (window.h4bsSearchConfig && window.h4bsSearchConfig.endpoint) || "";
        if (!endpoint) {
            return;
        }

        const input = form.querySelector("input[name='q']");
        const results = form.querySelector("[data-h4-search-results]");
        const typeSelect = form.querySelector("select[name='type']");
        const defaultType = form.getAttribute("data-type") || "all";
        const excludePosts = form.getAttribute("data-exclude-posts") || "";
        const excludePages = form.getAttribute("data-exclude-pages") || "";
        const excludeProducts = form.getAttribute("data-exclude-products") || "";
        const googleSite = form.getAttribute("data-google-site") || "";
        const googleExtra = form.getAttribute("data-google-extra") || "";

        form.addEventListener("submit", function (event) {
            event.preventDefault();
            const q = (input && input.value ? input.value : "").trim();
            if (!q) {
                return;
            }
            const selectedType =
                (typeSelect && typeSelect.value ? typeSelect.value : defaultType) || "all";

            if (selectedType === "google") {
                const normalizedHost = String(googleSite || window.location.host || "")
                    .replace(/^https?:\/\//i, "")
                    .replace(/\/.*/, "")
                    .trim();
                const pieces = [];
                if (normalizedHost) {
                    pieces.push("site:" + normalizedHost);
                }
                if (googleExtra.trim()) {
                    pieces.push(googleExtra.trim());
                }
                pieces.push(q);
                const googleQuery = pieces.join(" ").trim();
                const googleUrl = "https://www.google.com/search?q=" + encodeURIComponent(googleQuery);
                window.open(googleUrl, "_blank", "noopener");
                return;
            }

            let url =
                endpoint +
                "?q=" +
                encodeURIComponent(q) +
                "&type=" +
                encodeURIComponent(selectedType);
            if (excludePosts) {
                url += "&exclude_posts=" + encodeURIComponent(excludePosts);
            }
            if (excludePages) {
                url += "&exclude_pages=" + encodeURIComponent(excludePages);
            }
            if (excludeProducts) {
                url += "&exclude_products=" + encodeURIComponent(excludeProducts);
            }
            fetch(url, {
                headers: {
                    "X-WP-Nonce":
                        (window.h4bsSearchConfig && window.h4bsSearchConfig.nonce) || "",
                },
            })
                .then(function (response) {
                    return response.json();
                })
                .then(function (payload) {
                    const html =
                        renderPages(payload.pages || []) +
                        renderPosts(payload.posts || []) +
                        renderProducts(payload.products || []);
                    if (results) {
                        results.innerHTML = html || "<p>No results found.</p>";
                    }
                })
                .catch(function () {
                    if (results) {
                        results.textContent = "Search request failed. Try again.";
                    }
                });
        });

        form.dataset.h4bsSearchInit = "1";
    }

    function initSearch(root) {
        const scope =
            root && root.querySelectorAll
                ? root
                : document;
        scope
            .querySelectorAll("form[data-h4-search]")
            .forEach(attachSearch);
    }

    window.h4bsInitSearch = initSearch;

    if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", function () {
            initSearch(document);
        });
    } else {
        initSearch(document);
    }
})();
