import { __ } from '@wordpress/i18n';
import { InnerBlocks, useBlockProps, useInnerBlocksProps, InspectorControls } from '@wordpress/block-editor';
import { PanelBody, ToggleControl } from '@wordpress/components';

export default function Edit({ attributes, setAttributes }) {
    const { showImage, showCustomMessage } = attributes;

    // Get global setting (fallback to false if not set).
    const globalShowImage = window.memberpressBlocks?.showThankyouWelcomeImage ?? false;
    const globalShowCustomMessage = window.memberpressBlocks?.showCustomMessage ?? false;

    // Determine effective value: use block value if set, otherwise use global.
    const effectiveShowImage = showImage ?? globalShowImage;
    const effectiveShowCustomMessage = showCustomMessage ?? globalShowCustomMessage;

    const TEMPLATE = [
        ['memberpress/thank-you-details'],
        ...(effectiveShowImage ? [['memberpress/thank-you-image']] : [])
    ];

    const blockProps = useBlockProps({
        className: `mepr-success alignfull${!effectiveShowImage ? ' mepr-hide-welcome-image' : ''}`
    });

    const innerBlocksProps = useInnerBlocksProps(blockProps, {
        template: TEMPLATE,
        templateLock: "all"
    });

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Settings', 'memberpress')}>
                    <ToggleControl
                        label={__('Show Welcome Image', 'memberpress')}
                        checked={effectiveShowImage}
                        onChange={(value) => setAttributes({ showImage: value })}
                        help={__('Display a welcome image.', 'memberpress')}
                    />
                    <ToggleControl
                        label={__('Show Custom Message', 'memberpress')}
                        checked={effectiveShowCustomMessage}
                        onChange={(value) => setAttributes({ showCustomMessage: value })}
                        help={__('Replace the success details with a custom message.', 'memberpress')}
                    />
                </PanelBody>
            </InspectorControls>

            <div {...innerBlocksProps} />
        </>
    );
}
