import { registerBlockType } from '@wordpress/blocks';
import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import { safeHTML } from '@wordpress/dom';
import { PanelBody, TextareaControl } from '@wordpress/components';
import { defaultBlock } from '../../icons';
import metadata from './block.json';

const Edit = ({ attributes, setAttributes }) => {
    const { svgContent } = attributes;
    const blockProps = useBlockProps();

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Icon Settings', 'memberpress')}>
                    <TextareaControl
                        label={__('SVG Content', 'memberpress')}
                        help={__('Paste your SVG code here. It will display in the editor and frontend.', 'memberpress')}
                        value={svgContent}
                        onChange={(value) => setAttributes({ svgContent: value })}
                        rows={8}
                    />
                </PanelBody>
            </InspectorControls>
            <div {...blockProps}>
                {svgContent ? (
                    <div dangerouslySetInnerHTML={{ __html: safeHTML(svgContent) }} />
                ) : (
                    <p style={{ color: '#999', fontSize: '14px' }}>
                        {__('Add SVG content in the sidebar settings', 'memberpress')}
                    </p>
                )}
            </div>
        </>
    );
};

const Save = () => null;

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