/**
 * AIEO Promo Surface — block editor registration.
 *
 * Pairs with the server-side render in
 * class-aieo-dmm-promo-surfaces.php. PHP-only registration is invisible
 * to the editor UI — this file provides the inserter listing + edit
 * component.
 *
 * Editor preview deliberately stays as a static Placeholder rather
 * than ServerSideRender. The latter requires `wp-server-side-render`
 * which is reliable in the post editor but inconsistent across some
 * Site Editor contexts; a static placeholder keeps the block
 * insertable everywhere. The actual render runs server-side on the
 * front-end via the block's render_callback.
 */

(function (wp) {
    if (!wp || !wp.blocks || !wp.blockEditor || !wp.components || !wp.element) { return; }

    var el       = wp.element.createElement;
    var Fragment = wp.element.Fragment;
    var __       = (wp.i18n && wp.i18n.__) ? wp.i18n.__ : function (s) { return s; };
    var _sprintf = (wp.i18n && wp.i18n.sprintf) ? wp.i18n.sprintf : function (s) { return s; };

    var InspectorControls = wp.blockEditor.InspectorControls;
    var useBlockProps     = wp.blockEditor.useBlockProps;

    var PanelBody     = wp.components.PanelBody;
    var TextControl   = wp.components.TextControl;
    var SelectControl = wp.components.SelectControl;
    var Placeholder   = wp.components.Placeholder;

    // Surface list comes from PHP via wp_localize_script. Empty array
    // when no surfaces exist yet — handled gracefully below.
    var cfg = (typeof window !== 'undefined' && window.aieoPromoSurfaceConfig) || { surfaces: [] };
    var surfaces = Array.isArray(cfg.surfaces) ? cfg.surfaces : [];

    function buildSelectOptions() {
        var opts = [{ value: '', label: __('— Pick a surface —', 'ai-eshop-optimizer') }];
        surfaces.forEach(function (s) {
            opts.push({
                value: s.value,
                label: (s.is_active ? '' : '⊘ ') + s.label
            });
        });
        opts.push({ value: '__custom__', label: __('Custom slug (type below)…', 'ai-eshop-optimizer') });
        return opts;
    }

    wp.blocks.registerBlockType('aieo/promo-surface', {
        title:       __('AIEO Promo Surface', 'ai-eshop-optimizer'),
        category:    'theme',
        icon:        'megaphone',
        description: __('Hero carousel + 3 banner row, driven by the Promo surfaces config under Campaigns.', 'ai-eshop-optimizer'),
        keywords:    ['hero', 'banner', 'carousel', 'promo', 'aieo'],
        supports:    { align: ['wide', 'full'], html: false, spacing: { margin: true, padding: true }, typography: { fontSize: true, lineHeight: true }, color: { background: true, text: true } },
        attributes:  {
            surfaceSlug: { type: 'string', default: '' },
            align:       { type: 'string' }
        },

        edit: function (props) {
            var blockProps = useBlockProps({ className: 'aieo-promo-surface-editor-stub' });
            var slug = props.attributes.surfaceSlug || '';

            // The select shows '__custom__' if the current slug doesn't
            // match any registered surface — gives operators a path to
            // reference a slug they're about to create.
            var slugMatchesKnown = surfaces.some(function (s) { return s.value === slug; });
            var selectValue = slug === '' ? '' : (slugMatchesKnown ? slug : '__custom__');
            var showCustomField = (selectValue === '__custom__');

            var inspector = el(
                InspectorControls, null,
                el(PanelBody, { title: __('Promo surface', 'ai-eshop-optimizer'), initialOpen: true },
                    el(SelectControl, {
                        label:    __('Surface', 'ai-eshop-optimizer'),
                        help:     surfaces.length === 0
                            ? __('No surfaces created yet — go to Campaigns → Promo surfaces to add one.', 'ai-eshop-optimizer')
                            : __('Configured under Campaigns → Promo surfaces. ⊘ = inactive.', 'ai-eshop-optimizer'),
                        value:    selectValue,
                        options:  buildSelectOptions(),
                        onChange: function (v) {
                            if (v === '__custom__') {
                                // Keep current slug if any, else empty — the
                                // free-form field below lets the operator type.
                                if (!slug || slugMatchesKnown) { props.setAttributes({ surfaceSlug: '' }); }
                            } else {
                                props.setAttributes({ surfaceSlug: v });
                            }
                        }
                    }),
                    showCustomField && el(TextControl, {
                        label:    __('Custom slug', 'ai-eshop-optimizer'),
                        help:     __('Use this for a surface you plan to create later. The block renders nothing until a matching surface exists.', 'ai-eshop-optimizer'),
                        value:    slug,
                        onChange: function (v) { props.setAttributes({ surfaceSlug: v }); }
                    })
                )
            );

            var instructions;
            if (slug === '') {
                instructions = __('Pick a surface in the sidebar.', 'ai-eshop-optimizer');
            } else if (slugMatchesKnown) {
                var match = surfaces.find(function (s) { return s.value === slug; });
                instructions = (match && match.is_active === 0)
                    /* translators: %s is the surface slug */
                    ? _sprintf( __( 'Surface "%s" is currently inactive — visitors will not see it.', 'ai-eshop-optimizer' ), slug )
                    /* translators: %s is the surface slug */
                    : _sprintf( __( 'Renders surface "%s" on the front-end.', 'ai-eshop-optimizer' ), slug );
            } else {
                /* translators: %s is the surface slug */
                instructions = _sprintf( __( 'Custom slug: "%s" — block stays empty until a matching surface is created in Campaigns → Promo surfaces.', 'ai-eshop-optimizer' ), slug );
            }

            var preview = el(Placeholder, {
                icon: 'megaphone',
                label: __('Promo surface', 'ai-eshop-optimizer'),
                instructions: instructions
            });

            return el(Fragment, null, inspector, el('div', blockProps, preview));
        },

        save: function () { return null; }
    });
})(window.wp);
