import useEditorStore from '../store/useEditorStore';

export default function HeadingBlock({ block, isSelected }) {
    const s = block.settings || {};
    const updateBlockSettings = useEditorStore((state) => state.updateBlockSettings);

    const Tag = ['h1', 'h2', 'h3', 'h4', 'p'].includes(s.tag) ? s.tag : 'h1';

    const style = {
        color: s.textColor || '#1d2327',
        fontSize: `${s.fontSize || 24}px`,
        fontWeight: s.fontWeight || '700',
        textAlign: s.alignment || 'center',
        letterSpacing: `${s.letterSpacing || 0}px`,
        marginTop: `${s.marginTop || 0}px`,
        marginBottom: `${s.marginBottom || 12}px`,
        fontFamily: s.fontFamily && s.fontFamily !== 'inherit' ? `'${s.fontFamily}', sans-serif` : 'inherit',
        outline: 'none',
        border: 'none',
        background: 'none',
        width: '100%',
        padding: 0,
        lineHeight: 1.3,
    };

    const handleDoubleClick = (e) => {
        if (!isSelected) return;
        e.target.contentEditable = 'true';
        e.target.focus();
    };

    const handleBlur = (e) => {
        e.target.contentEditable = 'false';
        const newText = e.target.textContent;
        if (newText !== s.text) {
            updateBlockSettings(block.id, 'text', newText);
        }
    };

    return (
        <Tag
            className="lpcd-block-heading-preview"
            style={style}
            onDoubleClick={handleDoubleClick}
            onBlur={handleBlur}
            suppressContentEditableWarning
        >
            {s.text || 'Welcome Back'}
        </Tag>
    );
}
