(function () {
    if (!window.wp || !window.wp.blocks) {
        return;
    }

    const { registerBlockType } = window.wp.blocks;
    const { __ } = window.wp.i18n || ((text) => text);
    const components = window.wp.components || {};
    const element = window.wp.element || {};
    const apiFetch = window.wp.apiFetch;
    const blockEditor = window.wp.blockEditor || window.wp.editor || {};
    const useBlockProps = blockEditor.useBlockProps;
    const InspectorControls = blockEditor.InspectorControls;
    const SelectControl = components.SelectControl;
    const Notice = components.Notice;
    const Spinner = components.Spinner;
    const PanelBody = components.PanelBody;
    const Disabled = components.Disabled;
    const ServerSideRender = window.wp.serverSideRender;
    const Fragment = element.Fragment || 'div';
    const createElement = element.createElement || window.React?.createElement;
    const useState = element.useState;
    const useEffect = element.useEffect;

    // Core requirements to register the block at all. ServerSideRender,
    // Disabled, InspectorControls and PanelBody are expected (declared as script
    // dependencies) but treated as optional below so an unusual editor still gets
    // a working selector rather than a block that fails to register.
    if (
        !registerBlockType ||
        !apiFetch ||
        !SelectControl ||
        !Notice ||
        !Spinner ||
        !createElement ||
        !useState ||
        !useEffect ||
        !useBlockProps
    ) {
        return;
    }

    const BLOCK_NAME = 'formatrica/form';

    registerBlockType(BLOCK_NAME, {
        title: __('Formatrica', 'formatrica'),
        description: __('Embed a form created with Formatrica.', 'formatrica'),
        icon: 'feedback',
        category: 'widgets',
        keywords: [
            __('form', 'formatrica'),
            __('contact', 'formatrica'),
            __('easy', 'formatrica'),
        ],
        supports: {
            align: ['wide', 'full'],
        },
        attributes: {
            formId: {
                type: 'number',
                default: 0,
            },
        },
        edit({ attributes, setAttributes }) {
            const { formId } = attributes;
            const [forms, setForms] = useState([]);
            const [loading, setLoading] = useState(true);
            const [error, setError] = useState(null);

            useEffect(() => {
                setLoading(true);
                setError(null);

                apiFetch({ path: '/formatrica/v1/forms' })
                    .then((response) => {
                        if (response && Array.isArray(response.forms)) {
                            setForms(
                                response.forms.map((form) => ({
                                    value: Number(form.id),
                                    label:
                                        form.title ||
                                        __('Untitled form', 'formatrica'),
                                }))
                            );
                        } else {
                            setForms([]);
                        }
                        setLoading(false);
                    })
                    .catch((err) => {
                        // Non-fatal: log a warning for developers
                        console.warn('Failed to fetch forms:', err);
                        setError(
                            err.message ||
                                __('Failed to load forms', 'formatrica')
                        );
                        setLoading(false);
                    });
            }, []);

            const options = [
                { value: 0, label: __('Select a form…', 'formatrica') },
                ...forms,
            ];

            const blockProps = useBlockProps({
                className: 'formatrica-block-editor',
            });

            const selector = createElement(SelectControl, {
                label: __('Form', 'formatrica'),
                value: formId || 0,
                options,
                onChange: (value) => setAttributes({ formId: Number(value) }),
            });

            const hasSidebar = InspectorControls && PanelBody;
            const canPreview = ServerSideRender && Disabled;

            // Canvas content by state.
            let canvas;
            if (loading) {
                canvas = createElement(
                    'div',
                    { className: 'formatrica-block-empty' },
                    createElement(Spinner),
                    createElement('p', null, __('Loading forms…', 'formatrica'))
                );
            } else if (error) {
                canvas = createElement(
                    Notice,
                    { status: 'error', isDismissible: false },
                    error
                );
            } else if (!forms.length) {
                canvas = createElement(
                    Notice,
                    { status: 'info', isDismissible: false },
                    __(
                        'Create a form with Formatrica to embed it here.',
                        'formatrica'
                    )
                );
            } else if (!formId) {
                // No form chosen: show the selector in the canvas so the block is
                // immediately actionable, even when the sidebar is present.
                canvas = createElement(
                    'div',
                    { className: 'formatrica-block-empty' },
                    selector
                );
            } else if (canPreview) {
                // Real server-side render of the selected form, made inert so it
                // cannot be edited or submitted from inside the editor.
                canvas = createElement(
                    'div',
                    { className: 'formatrica-block-preview' },
                    !hasSidebar ? selector : null,
                    createElement(
                        Disabled,
                        null,
                        createElement(ServerSideRender, {
                            block: BLOCK_NAME,
                            attributes: { formId },
                            httpMethod: 'GET',
                        })
                    )
                );
            } else {
                // ServerSideRender unavailable: fall back to the selector.
                canvas = createElement(
                    'div',
                    { className: 'formatrica-block-empty' },
                    selector
                );
            }

            const children = [];
            if (hasSidebar) {
                children.push(
                    createElement(
                        InspectorControls,
                        { key: 'inspector' },
                        createElement(
                            PanelBody,
                            {
                                title: __('Form settings', 'formatrica'),
                                initialOpen: true,
                            },
                            selector
                        )
                    )
                );
            }
            children.push(createElement('div', blockProps, canvas));

            return createElement(Fragment, null, ...children);
        },
        save() {
            return null;
        },
    });
})();
