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

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

    // Block props with custom className management
    const blockProps = useBlockProps({
        className: hasSidecontent ? 'has-sidecontent' : '', // Custom class
    });

    // Custom template logic based on hasSidecontent
    const template = [
        hasSidecontent && ['lcp/sidecontent'], // Only include lcp/sidecontent if the toggle is true
        ['lcp/main-area'], // Always include lcp/main-area
    ].filter(Boolean); // Filter out falsey values (e.g., undefined when hasSidecontent is false)

    // Render appender logic to handle block insertion
    const renderAppender = () => {
        return <InnerBlocks.ButtonBlockAppender />;
    };

    return (
        <div {...blockProps}>
            {/* Inspector Controls: Add a toggle for the `hasSidecontent` attribute */}
            <InspectorControls>
                <ToggleControl
                    label={__('Include Side Content', 'lcp-viewport')}
                    checked={hasSidecontent}
                    onChange={(value) => setAttributes({ hasSidecontent: value })}
                />
            </InspectorControls>

            <div id="lcp-viewport-outer">
                <div id="lcp-viewport-inner">
                    {/* Render the InnerBlocks with conditional template */}
                    <InnerBlocks
                        template={template} // Use the template logic here
                        renderAppender={renderAppender} // Custom appender logic
                    />
                </div>
            </div>
        </div>
    );
}
