// ============================================================
// useCanvasInteraction — 画布交互 Hook
//
// 提供：
//   - 键盘快捷键处理（模式切换、全选、删除等）
//   - 模式切换回调
//   - 当前交互模式的状态
// ============================================================

import { useEffect, useCallback } from 'react';
import { useCanvasStore, type InteractionMode } from '../stores/useCanvasStore';

export function useCanvasInteraction() {
    const interactionMode = useCanvasStore((s) => s.interactionMode);
    const setInteractionMode = useCanvasStore((s) => s.setInteractionMode);
    const clearSelection = useCanvasStore((s) => s.clearSelection);

    const switchMode = useCallback(
        (mode: InteractionMode) => {
            setInteractionMode(mode);
            if (mode !== 'SELECT') {
                clearSelection();
            }
        },
        [setInteractionMode, clearSelection],
    );

    // 键盘快捷键
    useEffect(() => {
        const handler = (e: KeyboardEvent) => {
            // 避免在输入框中处理快捷键
            const target = e.target as HTMLElement;
            if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') return;

            switch (e.key) {
                case 'v':
                case 'V':
                    // V → BROWSE mode
                    if (!e.ctrlKey && !e.metaKey) {
                        switchMode('BROWSE');
                    }
                    break;
                case 's':
                case 'S':
                    // S → SELECT mode
                    if (!e.ctrlKey && !e.metaKey) {
                        switchMode('SELECT');
                    }
                    break;
                case 'r':
                case 'R':
                    // R → REORDER mode
                    if (!e.ctrlKey && !e.metaKey) {
                        switchMode('REORDER');
                    }
                    break;
                case 'Escape':
                    // Esc → 取消选择 / 回到 BROWSE
                    clearSelection();
                    if (interactionMode !== 'BROWSE') {
                        switchMode('BROWSE');
                    }
                    break;
            }
        };

        window.addEventListener('keydown', handler);
        return () => window.removeEventListener('keydown', handler);
    }, [switchMode, clearSelection, interactionMode]);

    return { interactionMode, switchMode };
}
