import {cloneElement, memo, useRef, useState} from '@wordpress/element';

const Tooltip = ({title, tooltipPosition, arrowPosition = 'center', children}) => {
    const [showTooltip, setShowTooltip] = useState(false);
    const childrenRef = useRef();

    const handleMouseEnter = () => {
        setShowTooltip(true);
    };

    const handleMouseLeave = () => {
        setShowTooltip(false);
    }

    // Preserve existing onClick handler and ensure it fires
    const handleClick = (e) => {
        // Hide tooltip immediately on click
        setShowTooltip(false);
        
        // Call original onClick if it exists
        if (children.props.onClick) {
            children.props.onClick(e);
        }
    };

    const childrenWithEvents = cloneElement(children, {
        onMouseEnter: handleMouseEnter,
        onMouseLeave: handleMouseLeave,
        onClick: handleClick,
        ref: childrenRef,
    });

    return (
        <>
            {childrenWithEvents}
            <div className={`lbaic-tooltip lbaic-tooltip-p-${tooltipPosition} lbaic-tooltip-a-${arrowPosition}`}>
                <div className={`lbaic-tooltip-in${showTooltip ? '' : ' hide'}`}>
                    <div className='lbaic-tooltip-inner'>
                        <span className='lbaic-tooltip-message'>{title}</span>
                    </div>
                </div>
            </div>
        </>
    );
};

export default memo(Tooltip);
