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

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

    const style = {
        color: s.textColor || '#50575e',
        fontSize: `${s.fontSize || 14}px`,
        fontWeight: s.fontWeight || '400',
        textAlign: s.alignment || 'center',
        lineHeight: s.lineHeight || 1.6,
        marginTop: `${s.marginTop || 0}px`,
        marginBottom: `${s.marginBottom || 16}px`,
        fontFamily: s.fontFamily && s.fontFamily !== 'inherit' ? `'${s.fontFamily}', sans-serif` : 'inherit',
        outline: 'none',
        padding: 0,
    };

    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 (
        <p
            className="lpcd-block-text-preview"
            style={style}
            onDoubleClick={handleDoubleClick}
            onBlur={handleBlur}
            suppressContentEditableWarning
        >
            {s.text || 'Please sign in to continue.'}
        </p>
    );
}
