(function () {
    function parseLayout(textarea) {
        try {
            const parsed = JSON.parse(textarea.value || "[]");
            return Array.isArray(parsed) ? parsed : [];
        } catch (error) {
            return [];
        }
    }

    function serializeLayout(textarea, layout) {
        textarea.value = JSON.stringify(layout, null, 2);
    }

    function estimateLoad(layout) {
        let ms = 520;
        const weights = {
            heading: 6,
            text: 8,
            image: 65,
            button: 4,
            html: 20,
            shortcode: 140,
            slider: 280,
            spacer: 1,
        };

        layout.forEach(function (block) {
            if (!block || typeof block !== "object") return;
            const type = String(block.type || "");
            ms += weights[type] || 15;

            if (type === "shortcode") {
                const shortcode = String(
                    block.settings && block.settings.shortcode
                        ? block.settings.shortcode
                        : ""
                );
                if (/\[h4_slider\b/i.test(shortcode)) {
                    ms += 180;
                }
                if (/\[h4_products\b/i.test(shortcode)) {
                    ms += 120;
                }
                if (/\[h4_checkout\b/i.test(shortcode)) {
                    ms += 180;
                }
                if (/\[h4_search\b/i.test(shortcode)) {
                    ms += 90;
                }
            }
        });

        return Math.max(220, ms);
    }

    function updateEstimate(layout, target) {
        if (!target) return;
        const ms = estimateLoad(layout);
        const s = (ms / 1000).toFixed(2);
        const label =
            ms < 1800
                ? "Fast"
                : ms < 2800
                ? "Moderate"
                : "Heavy";
        target.textContent = s + "s (" + ms + " ms, " + label + ")";
    }

    function blockTemplate(type, index) {
        const id = "block_" + type + "_" + Date.now() + "_" + index;
        const map = {
            heading: { text: "New Heading", tag: "h2" },
            text: { text: "Paragraph text." },
            image: { src: "", attachment_id: 0, alt: "" },
            button: { label: "Button", url: "#" },
            shortcode: { shortcode: "[h4_products limit=\"6\"]" },
            slider: { slider_id: 0 },
            html: { html: "<div>Custom HTML</div>" },
        };
        return {
            id: id,
            type: type,
            settings: map[type] || {},
        };
    }

    function bootBuilderAdmin() {
        const textarea = document.querySelector("#h4_builder_layout");
        const estimateTarget = document.querySelector(
            "[data-h4bs-builder-estimate]"
        );
        if (!textarea) {
            return;
        }

        updateEstimate(parseLayout(textarea), estimateTarget);

        textarea.addEventListener("input", function () {
            updateEstimate(parseLayout(textarea), estimateTarget);
        });

        const buttons = document.querySelectorAll("[data-h4bs-add-block]");
        buttons.forEach(function (button, index) {
            button.addEventListener("click", function () {
                const type = button.getAttribute("data-h4bs-add-block");
                if (!type) {
                    return;
                }
                const layout = parseLayout(textarea);
                layout.push(blockTemplate(type, index));
                serializeLayout(textarea, layout);
                updateEstimate(layout, estimateTarget);
                textarea.focus();
            });
        });
    }

    function focusBuilderPanel() {
        const panel = document.getElementById("h4bs-builder");
        if (!panel) {
            return;
        }

        const params = new URLSearchParams(window.location.search || "");
        const modeSelect = document.getElementById("h4_builder_mode");
        const enabled = document.querySelector('input[name="h4_builder_enabled"]');
        const shouldFocus =
            params.get("h4bs_builder") === "1" ||
            (modeSelect && modeSelect.value === "help4") ||
            (enabled && enabled.checked);

        if (!shouldFocus) {
            return;
        }

        const panelToggle = document.getElementById("h4bs-builder-hide");
        if (panelToggle && panel.classList.contains("closed")) {
            panelToggle.click();
        }

        const classicEditor = document.getElementById("postdivrich");
        if (classicEditor) {
            classicEditor.style.display = "none";
        }

        const titleWrap = document.getElementById("titlewrap");
        if (titleWrap) {
            titleWrap.style.display = "none";
        }

        if (modeSelect && modeSelect.value !== "help4") {
            modeSelect.value = "help4";
        }
        if (enabled && !enabled.checked) {
            enabled.checked = true;
        }

        panel.scrollIntoView({ behavior: "smooth", block: "start" });
        const textarea = document.getElementById("h4_builder_layout");
        if (textarea) {
            textarea.focus();
        }
    }

    document.addEventListener("DOMContentLoaded", function () {
        bootBuilderAdmin();
        focusBuilderPanel();
    });
})();
