/**
 * Recast Paywall Block Editor JavaScript
 */

(function() {
    'use strict';

    // === Global toolbar Recast toggle for all blocks (only in Block gating mode) ===
    function withRecastToggle(BlockEdit) {
        return function(props) {
            if (!props.isSelected) {
                return wp.element.createElement(BlockEdit, props);
            }

            var meta = wp.data.select('core/editor').getEditedPostAttribute('meta') || {};
            var gatingMode = meta._recast_gating_mode || 'post';
            if (gatingMode !== 'block') {
                return wp.element.createElement(BlockEdit, props);
            }

            var gated = !!props.attributes.recastGated;
            var toggle = function() { props.setAttributes({ recastGated: !gated }); };

            return wp.element.createElement(
                wp.element.Fragment,
                {},
                wp.element.createElement(BlockEdit, props),
                wp.element.createElement(
                    (wp.blockEditor && wp.blockEditor.BlockControls) || wp.editor.BlockControls,
                    { group: 'other' },
                    wp.element.createElement(
                        wp.components.ToolbarGroup,
                        {},
                        wp.element.createElement(wp.components.ToolbarButton, {
                            icon: (function(){
                                var url = (window.recastPaywallBlock && window.recastPaywallBlock.iconUrl) ? window.recastPaywallBlock.iconUrl : null;
                                if (!url) return gated ? 'lock' : 'unlock';
                                return wp.element.createElement('img', {
                                    src: url,
                                    alt: '',
                                    style: { width: 20, height: 20, filter: gated ? 'brightness(0) invert(1)' : 'none' }
                                });
                            })(),
                            label: gated ? 'Disable Recast gating' : 'Enable Recast gating',
                            isPressed: gated,
                            onClick: toggle
                        })
                    )
                )
            );
        };
    }

    function addRecastAttr(settings, name) {
        settings = settings || {};
        settings.attributes = settings.attributes || {};
        if (!settings.attributes.recastGated) {
            settings.attributes.recastGated = { type: 'boolean', default: false };
        }
        return settings;
    }

    wp.hooks.addFilter('blocks.registerBlockType', 'recast-paywall/add-recast-attr', addRecastAttr);
    wp.hooks.addFilter('editor.BlockEdit', 'recast-paywall/with-recast-toggle', withRecastToggle);

})();
