// video-preview-element-selection.js
import { useCallback, useState } from 'react';

export const useElementSelection = (emitter, timelineElements) => {
    // Selection state
    const [selectedElementId, setSelectedElementId] = useState(null);

    // Handle element selection
    const handleElementSelect = useCallback(
        (elementId) => {
            setSelectedElementId(elementId);

            // Find the selected element
            const element = timelineElements.find((el) => el.id === elementId);

            // If it's a text element, emit text-element-selected event
            if (element && element.type === 'text') {
                emitter.emit('text-element-selected', element);
            }
        },
        [emitter, timelineElements],
    );

    // Handle clicking on empty space to deselect
    const handleStageClick = useCallback((e) => {
        // If clicking on stage (not on an element), deselect
        if (e.target === e.target.getStage()) {
            setSelectedElementId(null);
        }
    }, []);

    return {
        selectedElementId,
        setSelectedElementId,
        handleElementSelect,
        handleStageClick,
    };
};
