import React from 'react'
// Import des CSS direkt hier
import './Modal.css'

export default function Modal({
    isOpen = true,
    onClose,
    title,
    children,
    message,
    type = 'info',
    isHtml = false,
    className,
    style,
    bodyClassName,
    bodyStyle
}) {
    if (!isOpen) return null

    const handleOverlayClick = (e) => {
        if (e.target === e.currentTarget) {
            onClose()
        }
    }

    const handleKeyDown = (e) => {
        if (e.key === 'Escape') {
            onClose()
        }
        if (e.key === 'Enter') {
            onClose()
        }
    }

    // Automatischer Titel basierend auf type
    const getDefaultTitle = () => {
        switch(type) {
            case 'success': return 'Erfolg'
            case 'error': return 'Fehler'
            case 'warning': return 'Warnung'
            case 'info': return 'Information'
            default: return 'Meldung'
        }
    }

    // CSS-Klasse basierend auf type
    const getModalClass = () => {
        return `modal-content modal-${type}${className ? ' ' + className : ''}`
    }

    const displayTitle = title || getDefaultTitle()
    
    // Content-Behandlung: HTML oder normaler Text
    const getDisplayContent = () => {
        if (children) return children
        
        if (message) {
            if (isHtml) {
                // HTML-Inhalt sicher anzeigen
                return <div dangerouslySetInnerHTML={{ __html: message }} />
            } else {
                // Normaler Text mit Zeilenumbrüchen
                return <p style={{whiteSpace: 'pre-line'}}>{message}</p>
            }
        }
        
        return null
    }

    return (
        <div className="modal-overlay" onClick={handleOverlayClick} onKeyDown={handleKeyDown} tabIndex={0}>
            <div className={getModalClass()} style={style}>
                <div className="modal-header">
                    <h3 className="modal-title">{displayTitle}</h3>
                    <button className="modal-close" onClick={onClose}>&times;</button>
                </div>
                <div className={`modal-body${bodyClassName ? ' ' + bodyClassName : ''}`} style={bodyStyle}>
                    {getDisplayContent()}
                </div>
                <div className="modal-footer">
                    <button className="modal-button" onClick={onClose} autoFocus>OK</button>
                </div>
            </div>
        </div>
    )
}