const { registerBlockType } = wp.blocks;
const { RichText, InspectorControls } = wp.blockEditor;
const { PanelBody, ColorPalette } = wp.components;

registerBlockType('theme/test-text-block', {
    title: 'Bubble', // Renamed block title to "Bubble Block"
    icon: 'smiley',
    category: 'common',
    attributes: {
        content: {
            type: 'string',
            default: '',
        },
        selectedColor: {
            type: 'string',
            default: 'black', // Default color slug
        },
    },
    edit: ({ attributes, setAttributes }) => {
        const { content, selectedColor } = attributes;

        // Update content when the user changes the text
        const onChangeContent = (newContent) => {
            setAttributes({ content: newContent });
        };

        // Update selected color when the user selects a new color
        const onChangeColor = (newColor) => {
            setAttributes({ selectedColor: newColor });
        };

        return [
            wp.element.createElement(
                InspectorControls, // Add sidebar for block settings
                {},
                wp.element.createElement(
                    PanelBody, // Panel to hold the color picker
                    { title: 'Text Color' },
                    wp.element.createElement(ColorPalette, {
                        value: selectedColor, // Set selected color
                        onChange: onChangeColor, // Change color when user selects a new one
                    })
                )
            ),
            wp.element.createElement(
                'div', // Wrapper div for the editor
                { className: `color-${selectedColor} bubble` }, // Apply both color class and 'bubble' class
                wp.element.createElement(RichText, {
                    tagName: 'div', // Block tag (can be div, p, etc.)
                    value: content, // Current content
                    onChange: onChangeContent, // Update content when changed
                    placeholder: 'Enter your text here...',
                })
            ),
        ];
    },
    save: ({ attributes }) => {
        const { content, selectedColor } = attributes;

        return wp.element.createElement(
            'div', // Frontend wrapper
            { className: `color-${selectedColor} bubble` }, // Add both color class and 'bubble' class
            wp.element.createElement(RichText.Content, {
                tagName: 'div', // Output tag
                value: content, // Output the saved content
            })
        );
    },
});
