(function (blocks, editor, element, components, $) {
    const { createElement: el, Fragment, useEffect } = wp.element;
    const {
        TextControl,
        TextareaControl,
        __experimentalUnitControl: UnitControl,
        __experimentalNumberControl: NumberControl,
        __experimentalBoxControl: BoxControl,
        __experimentalRadioGroup: RadioGroup,
        __experimentalRadio: Radio,
        Panel,
        PanelBody,
        InspectorControls,
    } = components;

    // Helper: Recursively search an object/array for all objects that contain a given key.
    const deepSearchByKey = (obj, key, matches = []) => {
        if (obj == null) return matches;
        if (Array.isArray(obj)) {
            obj.forEach((item) => deepSearchByKey(item, key, matches));
        } else if (typeof obj === "object") {
            Object.keys(obj).forEach((k) => {
                if (k === key) {
                    matches.push(obj);
                } else {
                    deepSearchByKey(obj[k], key, matches);
                }
            });
        }
        return matches;
    };

    // Generate the CSS based on attributes. Note that we now use a tri‑state for the display overrides.
    function blockStyleBackend(props) {
        // If a width is defined in attributes or via the layout setting, assign it to width_desktop.
        if (typeof props.attributes.width !== "undefined") {
            props.attributes.width_desktop = props.attributes.width;
        }
        if (props.attributes.layout?.contentSize) {
            props.attributes.width_desktop = props.attributes.layout.contentSize;
        }

        // Determine a block selector. (For special blocks, you may use customId.)
        let blockSelector = `#block-${props.clientId}`;
        if (props.name === "stepfox/casino-query-block") {
            blockSelector = `#block_${props.attributes.customId}`;
        }

        // Determine the display override values for each breakpoint.
        const hideDesktopCSS =
            props.attributes.hide_desktop === "hide"
                ? "display: none !important;"
                : props.attributes.hide_desktop === "show"
                    ? "display: block !important;"
                    : "";
        const hideTabletCSS =
            props.attributes.hide_tablet === "hide"
                ? "display: none !important;"
                : props.attributes.hide_tablet === "show"
                    ? "display: block !important;"
                    : "";
        const hideMobileCSS =
            props.attributes.hide_mobile === "hide"
                ? "display: none !important;"
                : props.attributes.hide_mobile === "show"
                    ? "display: block !important;"
                    : "";

        const gap = props.attributes.style?.spacing?.blockGap || "";

        // Build CSS rules for desktop, tablet, and mobile.
        const desktopAttributes = `
      {
        ${hideDesktopCSS}
        order: ${props.attributes.order_desktop} !important;
        width: ${props.attributes.width_desktop} !important;
        gap: ${gap} !important;
        flex-basis: ${props.attributes.width_desktop} !important;
        font-size: ${props.attributes.font_size_desktop} !important;
        line-height: ${props.attributes.line_height_desktop} !important;
        padding-top: ${props.attributes.desktop_padding.top} !important;
        padding-left: ${props.attributes.desktop_padding.left} !important;
        padding-bottom: ${props.attributes.desktop_padding.bottom} !important;
        padding-right: ${props.attributes.desktop_padding.right} !important;
        margin-top: ${props.attributes.desktop_margin.top} !important;
        margin-left: ${props.attributes.desktop_margin.left} !important;
        margin-bottom: ${props.attributes.desktop_margin.bottom} !important;
        margin-right: ${props.attributes.desktop_margin.right} !important;
        border-top-width: ${props.attributes.desktop_border.top} !important;
        border-left-width: ${props.attributes.desktop_border.left} !important;
        border-bottom-width: ${props.attributes.desktop_border.bottom} !important;
        border-right-width: ${props.attributes.desktop_border.right} !important;
      }
    `;
        const tabletAttributes = `
      {
        ${hideTabletCSS}
        text-align: ${props.attributes.text_align_tablet} !important;
        justify-content: ${props.attributes.justify_tablet} !important;
        order: ${props.attributes.order_tablet} !important;
        width: ${props.attributes.width_tablet} !important;
        flex-basis: calc(${props.attributes.width_tablet} - var(--wp--style--block-gap)) !important;
        font-size: ${props.attributes.font_size_tablet} !important;
        line-height: ${props.attributes.line_height_tablet} !important;
        padding-top: ${props.attributes.tablet_padding.top} !important;
        padding-left: ${props.attributes.tablet_padding.left} !important;
        padding-bottom: ${props.attributes.tablet_padding.bottom} !important;
        padding-right: ${props.attributes.tablet_padding.right} !important;
        margin-top: ${props.attributes.tablet_margin.top} !important;
        margin-left: ${props.attributes.tablet_margin.left} !important;
        margin-bottom: ${props.attributes.tablet_margin.bottom} !important;
        margin-right: ${props.attributes.tablet_margin.right} !important;
        border-top-width: ${props.attributes.tablet_border.top} !important;
        border-left-width: ${props.attributes.tablet_border.left} !important;
        border-bottom-width: ${props.attributes.tablet_border.bottom} !important;
        border-right-width: ${props.attributes.tablet_border.right} !important;
      }
    `;
        const mobileAttributes = `
      {
        ${hideMobileCSS}
        text-align: ${props.attributes.text_align_mobile} !important;
        justify-content: ${props.attributes.justify_mobile} !important;
        order: ${props.attributes.order_mobile} !important;
        width: ${props.attributes.width_mobile} !important;
        flex-basis: calc(${props.attributes.width_mobile} - var(--wp--style--block-gap)) !important;
        font-size: ${props.attributes.font_size_mobile} !important;
        line-height: ${props.attributes.line_height_mobile} !important;
        padding-top: ${props.attributes.mobile_padding.top} !important;
        padding-left: ${props.attributes.mobile_padding.left} !important;
        padding-bottom: ${props.attributes.mobile_padding.bottom} !important;
        padding-right: ${props.attributes.mobile_padding.right} !important;
        margin-top: ${props.attributes.mobile_margin.top} !important;
        margin-left: ${props.attributes.mobile_margin.left} !important;
        margin-bottom: ${props.attributes.mobile_margin.bottom} !important;
        margin-right: ${props.attributes.mobile_margin.right} !important;
        border-top-width: ${props.attributes.mobile_border.top} !important;
        border-left-width: ${props.attributes.mobile_border.left} !important;
        border-bottom-width: ${props.attributes.mobile_border.bottom} !important;
        border-right-width: ${props.attributes.mobile_border.right} !important;
      }
    `;

        return `<style>
      ${blockSelector} ${desktopAttributes}
      @media screen and (max-width:1024px) {
        ${blockSelector} ${tabletAttributes}
      }
      @media screen and (max-width:768px) {
        ${blockSelector} ${mobileAttributes}
      }
      ${props.attributes.custom_css.replaceAll("this_block", blockSelector)}
    </style>`;
    }

    // Higher Order Component that adds Inspector Controls and injects editor‑only styles.
    const withInspectorControls = wp.compose.createHigherOrderComponent((BlockEdit) => {
        return (props) => {
            // Update customId based on the anchor attribute.
            if (props.attributes.anchor) {
                if (props.attributes.anchor.length > 0) {
                    props.setAttributes({ customId: `anchor_${props.attributes.anchor}` });
                }
            } else if (
                props.attributes.anchor === "" &&
                props.attributes.customId &&
                props.attributes.customId.includes("anchor_")
            ) {
                props.setAttributes({ customId: "stepfox-not-set-id" });
            }

            // Inject dynamic style rules into the document head (editor only).
            useEffect(() => {
                const styleElement = document.createElement("style");
                styleElement.innerHTML = blockStyleBackend(props);
                document.head.appendChild(styleElement);
                return () => {
                    document.head.removeChild(styleElement);
                };
            }, [
                props.attributes.font_size_desktop,
                props.attributes.line_height_desktop,
                props.attributes.order_desktop,
                props.attributes.width_desktop,
                props.attributes.desktop_padding,
                props.attributes.desktop_margin,
                props.attributes.desktop_border,
                props.attributes.hide_desktop,
                props.attributes.hide_tablet,
                props.attributes.hide_mobile,
                props.attributes.font_size_tablet,
                props.attributes.line_height_tablet,
                props.attributes.order_tablet,
                props.attributes.width_tablet,
                props.attributes.tablet_padding,
                props.attributes.tablet_margin,
                props.attributes.tablet_border,
                props.attributes.font_size_mobile,
                props.attributes.line_height_mobile,
                props.attributes.order_mobile,
                props.attributes.width_mobile,
                props.attributes.mobile_padding,
                props.attributes.mobile_margin,
                props.attributes.mobile_border,
                props.attributes.custom_css,
                props.attributes.customId,
                props.attributes.anchor,
                props.attributes.style,
            ]);

            return el(
                Fragment,
                {},
                el(BlockEdit, props),
                el(
                    InspectorControls,
                    {},
                    el(
                        PanelBody,
                        { title: "Responsive", initialOpen: false },
                        // Desktop Panel
                        el(
                            PanelBody,
                            { title: "Desktop", initialOpen: false },
                            el("h2", { style: { fontSize: "20px" } }, "Desktop"),
                            el(
                                RadioGroup,
                                {
                                    label: "Visibility",
                                    onChange: (value) => props.setAttributes({ hide_desktop: value }),
                                    checked: props.attributes.hide_desktop,
                                },
                                el(Radio, { value: "not-selected" }, "Not Selected"),
                                el(Radio, { value: "show" }, "Show"),
                                el(Radio, { value: "hide" }, "Hide")
                            ),
                            // ... (Other desktop controls remain unchanged)
                            el("h4", { style: { fontSize: "17px" } }, "Font-Size"),
                            el(
                                "div",
                                { style: { display: "flex", gap: "10px" } },
                                el(UnitControl, {
                                    label: "Font Size",
                                    labelPosition: "top",
                                    onChange: (value) =>
                                        props.setAttributes({ font_size_desktop: value }),
                                    type: "number",
                                    value: props.attributes.font_size_desktop,
                                }),
                                el(UnitControl, {
                                    label: "Line Height",
                                    labelPosition: "top",
                                    onChange: (value) =>
                                        props.setAttributes({ line_height_desktop: value }),
                                    type: "number",
                                    value: props.attributes.line_height_desktop,
                                })
                            )
                            // ... additional desktop controls for width, margin, padding, etc.
                        ),
                        // Tablet Panel
                        el(
                            PanelBody,
                            { title: "Tablet", initialOpen: false },
                            el("h2", { style: { fontSize: "20px" } }, "Tablet"),
                            el(
                                RadioGroup,
                                {
                                    label: "Visibility",
                                    onChange: (value) => props.setAttributes({ hide_tablet: value }),
                                    checked: props.attributes.hide_tablet,
                                },
                                el(Radio, { value: "not-selected" }, "Not Selected"),
                                el(Radio, { value: "show" }, "Show"),
                                el(Radio, { value: "hide" }, "Hide")
                            )
                            // ... additional tablet controls (font, line-height, margins, padding, etc.)
                        ),
                        // Mobile Panel
                        el(
                            PanelBody,
                            { title: "Mobile", initialOpen: false },
                            el("h2", { style: { fontSize: "20px" } }, "Mobile"),
                            el(
                                RadioGroup,
                                {
                                    label: "Visibility",
                                    onChange: (value) => props.setAttributes({ hide_mobile: value }),
                                    checked: props.attributes.hide_mobile,
                                },
                                el(Radio, { value: "not-selected" }, "Not Selected"),
                                el(Radio, { value: "show" }, "Show"),
                                el(Radio, { value: "hide" }, "Hide")
                            )
                            // ... additional mobile controls (font, line-height, margins, padding, etc.)
                        ),
                        // Custom CSS Panel
                        el(
                            PanelBody,
                            { title: "Custom Css", initialOpen: false },
                            el(TextareaControl, {
                                label: "Custom Css",
                                help:
                                    "Here you can write custom CSS. For example: (this_block .high-title a { color: #F00; })",
                                onChange: (value) =>
                                    props.setAttributes({ custom_css: value }),
                                value: props.attributes.custom_css,
                            })
                        )
                    )
                )
            );
        };
    }, "withInspectorControls");

    wp.hooks.addFilter("editor.BlockEdit", "core/column", withInspectorControls);

    // Add custom attributes for every block, including our tri‑state visibility attributes.
    const addAttributes = (settings) => {
        settings.attributes = {
            ...settings.attributes,
            // Desktop Attributes
            font_size_desktop: { type: "string", default: "" },
            line_height_desktop: { type: "string", default: "" },
            order_desktop: { type: "string", default: "" },
            width_desktop: { type: "string", default: "" },
            desktop_padding: { type: "object", default: { top: "", left: "", right: "", bottom: "" } },
            desktop_margin: { type: "object", default: { top: "", left: "", right: "", bottom: "" } },
            desktop_border: { type: "object", default: { top: "", left: "", right: "", bottom: "" } },
            hide_desktop: { type: "string", default: "not-selected" },

            // Tablet Attributes
            hide_tablet: { type: "string", default: "not-selected" },
            text_align_tablet: { type: "string", default: "" },
            justify_tablet: { type: "string", default: "" },
            font_size_tablet: { type: "string", default: "" },
            line_height_tablet: { type: "string", default: "" },
            order_tablet: { type: "string", default: "" },
            width_tablet: { type: "string", default: "" },
            tablet_padding: { type: "object", default: { top: "", left: "", right: "", bottom: "" } },
            tablet_margin: { type: "object", default: { top: "", left: "", right: "", bottom: "" } },
            tablet_border: { type: "object", default: { top: "", left: "", right: "", bottom: "" } },

            // Mobile Attributes
            hide_mobile: { type: "string", default: "not-selected" },
            text_align_mobile: { type: "string", default: "" },
            justify_mobile: { type: "string", default: "" },
            font_size_mobile: { type: "string", default: "" },
            line_height_mobile: { type: "string", default: "" },
            order_mobile: { type: "string", default: "" },
            width_mobile: { type: "string", default: "" },
            mobile_padding: { type: "object", default: { top: "", left: "", right: "", bottom: "" } },
            mobile_margin: { type: "object", default: { top: "", left: "", right: "", bottom: "" } },
            mobile_border: { type: "object", default: { top: "", left: "", right: "", bottom: "" } },

            // General Attributes (using customId instead of id)
            customId: { type: "string", default: "stepfox-not-set-id" },
            custom_css: { type: "string", default: "" },
        };
        return settings;
    };

    wp.hooks.addFilter("blocks.registerBlockType", "core/column", addAttributes);
})(window.wp.blocks, window.wp.blockEditor, window.wp.element, window.wp.components, window.jQuery);
