import { useMemo } from 'react';
import { useCanvasStore } from '@/lib/store/canvasStore';
import { AppNodeData } from '../types/node';

// Node types that support editing via bottom bar
const EDITABLE_NODE_TYPES = new Set([
    'IMAGE_GENERATOR',
    'VIDEO_GENERATOR',
    'AUDIO_GENERATOR',
    'LYRICS_GENERATOR',
    'IMAGE_EDITOR',
    'PROMPT_GENERATOR',
]);

/**
 * Hook to track the currently selected node for bottom bar editing.
 * Returns edit mode info only when a single editable node is selected.
 */
export function useSelectedNode() {
    const nodes = useCanvasStore((state) => state.nodes);

    return useMemo(() => {
        const selectedAppNodes = nodes.filter(
            n => n.selected && n.type === 'appNode'
        );

        // Only enter edit mode for single selection of an editable node
        if (selectedAppNodes.length === 1) {
            const node = selectedAppNodes[0];
            if (node.type === 'appNode') {
                const data = node.data as AppNodeData;
                if (EDITABLE_NODE_TYPES.has(data.type)) {
                    return {
                        selectedNode: node,
                        selectedNodeData: data,
                        selectedNodeId: node.id,
                        isEditMode: true,
                    };
                }
            }
        }

        return {
            selectedNode: null,
            selectedNodeData: null,
            selectedNodeId: null,
            isEditMode: false,
        };
    }, [nodes]);
}
