import { registerBlockType } from '@wordpress/blocks';
import { __ } from '@wordpress/i18n';
import { InnerBlocks, useBlockProps, useInnerBlocksProps } from '@wordpress/block-editor';
import { defaultBlock } from '../../icons';
import metadata from './block.json';

const Edit = ({ context, clientId, attributes, setAttributes }) => {
    const showCustomMessage = context['memberpress/showCustomMessage'];

    // Add global fallback
    const globalShowCustomMessage = window.memberpressBlocks?.showCustomMessage ?? false;

    const effectiveShowCustomMessage = showCustomMessage ?? globalShowCustomMessage;

    // Site-wide default that seeds a freshly created custom-message paragraph.
    // Once a user edits the paragraph, its own inner-block content is the source of truth.
    const effectiveCustomMessage = window.memberpressBlocks?.customMessage ?? '';

    // Keep in sync with the PHP fallback in app/controllers/MeprBlocksCtrl.php::render_details().
    const TEMPLATE = [
        ['core/heading', { textAlign: 'center', level: 1, content: __('Thank you for your purchase', 'memberpress') }],
        ['memberpress/thank-you-icon', {}],
        ['core/group', { className: 'mepr-order-no' }, [
            ['core/paragraph', { content: __('Payment Successful', 'memberpress'), align: 'center' }],
            ['memberpress/thank-you-order-value', { field: 'order_number', label: __('Order:', 'memberpress'), style: { typography: { textAlign: 'center' } } }],
        ]],
        ['memberpress/thank-you-order-value', { field: 'amount', className: 'invoice-amount' }],
        ['memberpress/thank-you-invoice', {}],
        ['memberpress/thank-you-back-link', {}]
    ];

    const TEMPLATE_WITH_CUSTOM = [
        ['core/heading', { textAlign: 'center', level: 1, content: __('Thank you for your purchase', 'memberpress') }],
        ['core/paragraph', {
            content: effectiveCustomMessage,
            placeholder: __('Enter your custom message here...', 'memberpress'),
            align: 'center',
            className: 'mepr-custom-message'
        }],
        ['memberpress/thank-you-back-link', {}]
    ];

    const blockProps = useBlockProps({
        className: 'mepr-success-details'
    });

    // templateLock: "all" drives content-preserving template sync through Gutenberg's
    // synchronizeBlocksWithTemplate, which also swaps the template live when
    // effectiveShowCustomMessage flips — so no manual replaceInnerBlocks effect is needed.
    const innerBlocksProps = useInnerBlocksProps(blockProps, {
        template: effectiveShowCustomMessage ? TEMPLATE_WITH_CUSTOM : TEMPLATE,
        templateLock: "all"
    });


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

const Save = () => {
    return <InnerBlocks.Content />;
};

registerBlockType(metadata.name, {
    ...metadata,
    icon: defaultBlock,
    edit: Edit,
    save: Save
});
