/**
 * @file assets/js/blocks/block-esp-signup.js
 * Registers the mbs/esp-signup Gutenberg block.
 * Depends on mbs-blocks-editor (wp.* globals + window.mbsBlocksCore helpers).
 * Helpers used: none
 * @package MyBookShowroom
 * @since   1.0.0
 */

( function ( wp, mbsCore ) {
    'use strict';

    const { registerBlockType } = wp.blocks;
    const { InspectorControls, useBlockProps } = wp.blockEditor;
    const { ServerSideRender } = wp.serverSideRender;
    const { PanelBody, TextControl, ToggleControl } = wp.components;
    const { createElement: el, Fragment } = wp.element;

    // ============================================================================
    registerBlockType('mbs/esp-signup', {
        apiVersion: 3,
        title: 'ESP Signup (PRO)',
        description: 'Email newsletter signup form. Integrates with your ESP provider. Requires PRO license.',
        icon: 'email-alt',
        category: 'mbs',
        keywords: [ 'newsletter', 'signup', 'email', 'subscribe', 'list building', 'esp' ],

        attributes: {
            bookId:           { type: 'number',  default: 0            },
            showConsentField: { type: 'boolean', default: true          },
            buttonLabel:      { type: 'string',  default: 'Subscribe'  },
        },

        edit: function (props) {
            const { attributes, setAttributes } = props;

            return el(
                Fragment,
                {},
                el(
                    InspectorControls,
                    {},
                    el(
                        PanelBody,
                        { title: 'ESP Signup Settings', initialOpen: true },
                        el(TextControl, {
                            label: 'Button Label',
                            value: attributes.buttonLabel,
                            onChange: function (value) {
                                setAttributes({ buttonLabel: value });
                            },
                        }),
                        el(ToggleControl, {
                            label: 'Show consent checkbox',
                            checked: attributes.showConsentField,
                            onChange: function (value) {
                                setAttributes({ showConsentField: value });
                            },
                        })
                    )
                ),
                el(
                    'div',
                    useBlockProps({ className: 'mbs-block mbs-block-esp-signup' }),
                    el(ServerSideRender, {
                        block: 'mbs/esp-signup',
                        attributes: attributes,
                    })
                )
            );
        },

        save: function () {
            return null; // Dynamic block - rendered by PHP via render_callback
        },
    });

} )( window.wp, window.mbsBlocksCore || {} );
