import { FC } from 'react'
import { TextType, ElementType, PersonalityDataType, SectionName } from '../types/Types'
import { usePersonalityStore } from '../store/Store'

interface TextRendererProps {
    texts: TextType[]
    itemId: string
    sectionKey: keyof PersonalityDataType
}

const TextRenderer: FC<TextRendererProps> = ({ texts, itemId, sectionKey }) => {
    const { selectedElement, setSelectedElement } = usePersonalityStore()

    const handleTextClick = (e: React.MouseEvent, textId: string) => {
        // جلوگیری از propagation به parent handlers
        e.stopPropagation()
        e.preventDefault()

        setSelectedElement({
            type: ElementType.TEXT,
            elementId: textId,
            itemId,
            sectionKey: sectionKey as SectionName,
        })
    }

    return (
        <>
            {texts?.map((textItem, textIndex) => (
                <div
                    key={textItem.id}
                    data-element-type="text"
                    onClick={(e) => handleTextClick(e, textItem.id)}
                    style={{
                        cursor: 'pointer',
                        border: selectedElement?.elementId === textItem.id ? '2px dashed #0038FF' : '2px dashed transparent',
                        borderRadius: '4px',
                        padding: '2px',
                        margin: '2px 0',
                        transition: 'border-color 0.2s ease',
                        minHeight: '20px',
                        display: 'inline-block',
                        width: '100%'
                    }}
                >
                    <table width="100%" cellPadding="0" cellSpacing="0" border={0} style={{ borderCollapse: 'collapse' }}>
                        <tbody>
                            <tr>
                                <td
                                    align={textItem.alignment || 'center'}
                                    style={{
                                        color: textItem.color || '#000000',
                                        fontSize: `${textItem.fontSize || 14}px`,
                                        fontWeight: textItem.fontWeight || 400,
                                        lineHeight: '1.4',
                                        paddingBottom: textIndex < (texts?.length || 0) - 1 ? '4px' : '0',
                                        pointerEvents: 'none' // Prevent double click handling
                                    }}
                                    dangerouslySetInnerHTML={{ __html: textItem.text }}
                                />
                            </tr>
                        </tbody>
                    </table>
                </div>
            ))}
        </>
    )
}

export default TextRenderer 