(function () {
    const FILE_BUTTON_STYLE_ID = 'gf-block-file-button-styles';

    function ensureStyleElement() {
        let styleElement = document.getElementById(FILE_BUTTON_STYLE_ID);
        if (!styleElement) {
            styleElement = document.createElement('style');
            styleElement.id = FILE_BUTTON_STYLE_ID;
            document.head.appendChild(styleElement);
        }
        return styleElement;
    }

    function styleFileUploadButtons(root) {
        const inputs = root.querySelectorAll('input[type="file"]');
        if (!inputs.length) {
            return;
        }

        let cssRules = '';
        inputs.forEach((input, index) => {
            const styles = window.getComputedStyle(input);
            const inputId = input.id || 'gf-block-file-input-' + index;
            if (!input.id) {
                input.id = inputId;
            }

            const textColor = styles.color;
            const radius = styles.borderRadius || styles.borderTopLeftRadius || '4px';

            cssRules += '#' + inputId + '::file-selector-button {' +
                'padding: 6px 14px !important;' +
                'margin-right: 0.5rem !important;' +
                'color: ' + textColor + ' !important;' +
                'border-radius: ' + radius + ' !important;' +
                'cursor: pointer !important;' +
                'transition: border-color 0.15s ease-in-out !important;' +
            '}';
        });

        const styleElement = ensureStyleElement();
        styleElement.textContent = cssRules;
    }

    function cssPropertyToCamelCase(prop) {
        return prop.replace(/-([a-z])/g, function (_, letter) {
            return letter.toUpperCase();
        });
    }

    function buildChevronDataUri(strokeColor) {
        const safeColor = strokeColor || '#6c757d';
        const svg = "<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'><polyline points='2,4 6,8 10,4' fill='none' stroke='" + safeColor + "' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'/></svg>";
        return 'url("data:image/svg+xml,' + encodeURIComponent(svg) + '")';
    }

    function stylePhoneInputGroup(group) {
        const children = Array.from(group.children);
        const input = group.querySelector('input[type="tel"]') || group.querySelector('input, select, textarea');
        const countrySelect = group.querySelector('select.gf-bp-phone-select');
        if (!input || children.length < 2) {
            return;
        }

        const styles = window.getComputedStyle(input);
        if (countrySelect) {
            countrySelect.style.setProperty('color', styles.color, 'important');
            const finalSelectColor = window.getComputedStyle(countrySelect).color;
            countrySelect.style.setProperty('--gf-phone-caret-image', buildChevronDataUri(finalSelectColor));
        }
        const inputIndex = children.indexOf(input);
        const firstChild = children[0];
        const lastChild = children[children.length - 1];
        const hasBefore = inputIndex > 0;
        const hasAfter = inputIndex < children.length - 1;

        const hasTopBorder = parseFloat(styles.borderTopWidth) > 0;
        const hasLeftBorder = parseFloat(styles.borderLeftWidth) > 0;
        const hasRadius = parseFloat(styles.borderTopLeftRadius) > 0 || parseFloat(styles.borderTopRightRadius) > 0;
        const isMinimalStyle = !hasTopBorder && !hasLeftBorder && !hasRadius;

        function applyBorderStyles(elem, sides) {
            const borderProps = ['Width', 'Style', 'Color'];
            const radiusMap = {
                left: ['border-top-left-radius', 'border-bottom-left-radius'],
                right: ['border-top-right-radius', 'border-bottom-right-radius'],
            };
            sides.borders.forEach((side) => {
                const capitalSide = side.charAt(0).toUpperCase() + side.slice(1);
                borderProps.forEach((prop) => {
                    const cssProp = 'border-' + side + '-' + prop.toLowerCase();
                    let value = styles['border' + capitalSide + prop];
                    if (value && value !== 'none' && parseFloat(value) !== 0) {
                        elem.style.setProperty(cssProp, value, 'important');
                    }
                });
            });

            sides.zeroBorders.forEach((side) => {
                elem.style.setProperty('border-' + side + '-width', '0', 'important');
                elem.style.setProperty('border-' + side + '-style', 'none', 'important');
            });

            if (!isMinimalStyle) {
                sides.radius.forEach((side) => {
                    radiusMap[side].forEach((radiusProp) => {
                        const camel = cssPropertyToCamelCase(radiusProp);
                        const value = styles[camel];
                        if (value && value !== 'none' && parseFloat(value) !== 0) {
                            elem.style.setProperty(radiusProp, value, 'important');
                        }
                    });
                });
            }

            elem.style.setProperty('color', styles.color, 'important');
            if (elem !== input && !isMinimalStyle) {
                const borderColor = styles.borderTopColor;
                const match = borderColor.match(/rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)(?:,\\s*[\\d.]+)?\\)/);
                if (match) {
                    elem.style.setProperty('background-color', 'rgba(' + match[1] + ', ' + match[2] + ', ' + match[3] + ', 0.1)', 'important');
                }
            }
        }

        if (firstChild !== input) {
            if (isMinimalStyle) {
                firstChild.style.setProperty('border', 'none', 'important');
                firstChild.style.setProperty('background', 'transparent', 'important');
                firstChild.style.setProperty('color', styles.color, 'important');
            } else {
                applyBorderStyles(firstChild, {
                    borders: ['top', 'bottom', 'left'],
                    zeroBorders: ['right'],
                    radius: ['left'],
                });
            }
        }

        if (lastChild !== input && lastChild !== firstChild) {
            if (isMinimalStyle) {
                lastChild.style.setProperty('border', 'none', 'important');
                lastChild.style.setProperty('background', 'transparent', 'important');
                lastChild.style.setProperty('color', styles.color, 'important');
            } else {
                applyBorderStyles(lastChild, {
                    borders: ['top', 'bottom', 'right'],
                    zeroBorders: ['left'],
                    radius: ['right'],
                });
            }
        }

        if (hasBefore && hasAfter) {
            input.style.setProperty('border-left-width', '0', 'important');
            input.style.setProperty('border-right-width', '0', 'important');
            input.style.setProperty('border-left-style', 'none', 'important');
            input.style.setProperty('border-right-style', 'none', 'important');
            input.style.setProperty('border-top-left-radius', '0', 'important');
            input.style.setProperty('border-bottom-left-radius', '0', 'important');
            input.style.setProperty('border-top-right-radius', '0', 'important');
            input.style.setProperty('border-bottom-right-radius', '0', 'important');
        } else if (hasBefore) {
            input.style.setProperty('border-top-left-radius', '0', 'important');
            input.style.setProperty('border-bottom-left-radius', '0', 'important');
        } else if (hasAfter) {
            input.style.setProperty('border-right-width', '0', 'important');
            input.style.setProperty('border-right-style', 'none', 'important');
            input.style.setProperty('border-top-right-radius', '0', 'important');
            input.style.setProperty('border-bottom-right-radius', '0', 'important');
        }
    }

    function stylePhoneGroups(root) {
        const groups = root.querySelectorAll('.griffinforms-phone-input-group');
        if (!groups.length) {
            return;
        }
        groups.forEach(stylePhoneInputGroup);
    }

    const RESPONSIVE_BREAKPOINTS = {
        xs: 480,
        sm: 768,
        md: 992,
    };
    const RESPONSIVE_CLASSES = ['gf-xs', 'gf-sm', 'gf-md', 'gf-lg'];
    const WIDTH_RETRY_LIMIT = 12;
    const WIDTH_RETRY_DELAY = 150;

    function getResponsiveClass(width) {
        if (width < RESPONSIVE_BREAKPOINTS.xs) {
            return 'gf-xs';
        }
        if (width < RESPONSIVE_BREAKPOINTS.sm) {
            return 'gf-sm';
        }
        if (width < RESPONSIVE_BREAKPOINTS.md) {
            return 'gf-md';
        }
        return 'gf-lg';
    }

    function scheduleWidthRetry(preview) {
        if (preview.__gfWidthRetryCount >= WIDTH_RETRY_LIMIT) {
            return;
        }
        preview.__gfWidthRetryCount += 1;
        window.setTimeout(() => {
            applyResponsiveClass(preview);
        }, WIDTH_RETRY_DELAY);
    }

    function applyResponsiveClass(preview) {
        const width = preview.getBoundingClientRect().width || preview.offsetWidth || 0;
        console.log('[GriffinForms][BlockPreview] width:', width, 'node:', preview);
        if (width <= 0) {
            preview.__gfWidthRetryCount = preview.__gfWidthRetryCount || 0;
            RESPONSIVE_CLASSES.forEach((cls) => preview.classList.remove(cls));
            preview.classList.add('gf-xs');
            console.log('[GriffinForms][BlockPreview] width=0, forcing gf-xs and retry', preview.__gfWidthRetryCount);
            scheduleWidthRetry(preview);
            return;
        }
        const targetClass = getResponsiveClass(width);
        RESPONSIVE_CLASSES.forEach((cls) => preview.classList.remove(cls));
        preview.classList.add(targetClass);
        console.log('[GriffinForms][BlockPreview] applied responsive class:', targetClass);
    }

    function initResponsivePreview(preview) {
        if (preview.__gfResponsiveInitialized) {
            return;
        }
        preview.__gfResponsiveInitialized = true;
        applyResponsiveClass(preview);

        if (window.ResizeObserver) {
            let rafScheduled = false;
            const observer = new ResizeObserver(() => {
                if (rafScheduled) {
                    return;
                }
                rafScheduled = true;
                window.requestAnimationFrame(() => {
                    applyResponsiveClass(preview);
                    rafScheduled = false;
                });
            });
            observer.observe(preview);
            preview.__gfResponsiveObserver = observer;
        }
    }

    function applyResponsiveClasses() {
        const previews = document.querySelectorAll('.griffinforms-block-preview');
        previews.forEach(initResponsivePreview);
    }

    function applyOverrides() {
        const previews = document.querySelectorAll('.griffinforms-block-preview');
        previews.forEach((preview) => {
            styleFileUploadButtons(preview);
            stylePhoneGroups(preview);
        });
        applyResponsiveClasses();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', applyOverrides);
    } else {
        applyOverrides();
    }

    const observer = new MutationObserver(function () {
        applyOverrides();
    });

    const startObserver = function () {
        const target = document.body;
        if (target) {
            observer.observe(target, { childList: true, subtree: true });
        }
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', startObserver);
    } else {
        startObserver();
    }
})();
