"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceCommandInterface = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
/**
 * Voice Command Interface - Natural language command execution component
 * Features: Wake word detection, command parsing, contextual actions
 */
const react_1 = require("react");
const useVoiceInput_1 = require("../../hooks/useVoiceInput");
// Default voice commands
const DEFAULT_COMMANDS = [
    {
        id: 'navigate-to',
        pattern: /(?:go to|navigate to|open) (.+)/i,
        description: 'Navigate to a specific page or section',
        category: 'navigation',
        icon: '🧭',
        examples: ['Go to dashboard', 'Navigate to settings', 'Open profile'],
        action: async (matches, context) => {
            const destination = matches[1];
            console.log(`Navigating to: ${destination}`);
            // Implementation would handle actual navigation
        }
    },
    {
        id: 'search-for',
        pattern: /(?:search for|find|look for) (.+)/i,
        description: 'Search for content or items',
        category: 'query',
        icon: '🔍',
        examples: ['Search for documents', 'Find John Smith', 'Look for recent files'],
        action: async (matches, context) => {
            const query = matches[1];
            console.log(`Searching for: ${query}`);
            // Implementation would handle search
        }
    },
    {
        id: 'create-new',
        pattern: /(?:create|new|add) (?:a |an )?(.+)/i,
        description: 'Create new items or content',
        category: 'action',
        icon: '➕',
        examples: ['Create a new document', 'Add a task', 'New project'],
        action: async (matches, context) => {
            const itemType = matches[1];
            console.log(`Creating new: ${itemType}`);
            // Implementation would handle creation
        }
    },
    {
        id: 'delete-item',
        pattern: /(?:delete|remove) (.+)/i,
        description: 'Delete or remove items',
        category: 'action',
        icon: '🗑️',
        examples: ['Delete this file', 'Remove selected items'],
        action: async (matches, context) => {
            const item = matches[1];
            console.log(`Deleting: ${item}`);
            // Implementation would handle deletion with confirmation
        }
    },
    {
        id: 'help-commands',
        pattern: /(?:help|what can you do|show commands)/i,
        description: 'Show available voice commands',
        category: 'control',
        icon: '❓',
        examples: ['Help', 'What can you do?', 'Show commands'],
        action: async (matches, context) => {
            console.log('Showing help...');
            // Implementation would show help interface
        }
    },
    {
        id: 'stop-listening',
        pattern: /(?:stop|cancel|never mind)/i,
        description: 'Stop voice recognition',
        category: 'control',
        icon: '🛑',
        examples: ['Stop', 'Cancel', 'Never mind'],
        action: async (matches, context) => {
            console.log('Stopping voice recognition...');
            // Implementation would stop listening
        }
    }
];
const VoiceCommandInterface = ({ wakeWord = 'hey assistant', commands = DEFAULT_COMMANDS, context = {}, onCommandExecuted, onWakeWordDetected, onError, className = '', style = {}, showVisualFeedback = true, enableHelpMode = true, theme = 'auto' }) => {
    // State management
    const [isAwake, setIsAwake] = (0, react_1.useState)(false);
    const [currentCommand, setCurrentCommand] = (0, react_1.useState)(null);
    const [executionResult, setExecutionResult] = (0, react_1.useState)(null);
    const [isExecuting, setIsExecuting] = (0, react_1.useState)(false);
    const [showHelp, setShowHelp] = (0, react_1.useState)(false);
    const [recognizedText, setRecognizedText] = (0, react_1.useState)('');
    const [lastWakeTime, setLastWakeTime] = (0, react_1.useState)(null);
    // Refs
    const wakeTimeoutRef = (0, react_1.useRef)();
    const feedbackTimeoutRef = (0, react_1.useRef)();
    // Enhanced voice input with command patterns
    const { isListening, startListening, stopListening, transcript, confidence, isSupported, error: voiceError, isWakeWordActive, detectedCommands, clearCommands, resetWakeWord } = (0, useVoiceInput_1.useAdvancedVoiceInput)({
        enabled: true,
        continuous: true,
        interimResults: true,
        wakeWord,
        commandPatterns: commands.map(cmd => ({
            pattern: cmd.pattern,
            action: (matches) => handleCommandDetected(cmd, matches)
        })),
        onResult: (text, conf) => {
            setRecognizedText(text);
        },
        onError: (err) => {
            onError?.(new Error(err.message));
        }
    });
    // Handle wake word detection
    (0, react_1.useEffect)(() => {
        if (isWakeWordActive && !isAwake) {
            setIsAwake(true);
            setLastWakeTime(new Date());
            onWakeWordDetected?.();
            // Auto-sleep after 30 seconds of inactivity
            wakeTimeoutRef.current = setTimeout(() => {
                setIsAwake(false);
                resetWakeWord();
                stopListening();
            }, 30000);
            // Provide audio feedback
            if (showVisualFeedback) {
                playWakeSound();
            }
        }
    }, [isWakeWordActive, isAwake, onWakeWordDetected, showVisualFeedback, resetWakeWord, stopListening]);
    // Handle command detection
    const handleCommandDetected = (0, react_1.useCallback)(async (command, matches) => {
        if (!isAwake)
            return;
        setCurrentCommand(command);
        setIsExecuting(true);
        // Clear wake timeout since we're actively processing
        if (wakeTimeoutRef.current) {
            clearTimeout(wakeTimeoutRef.current);
        }
        try {
            const result = await command.action(matches, context);
            setExecutionResult(result);
            onCommandExecuted?.(command, result);
            // Provide success feedback
            if (showVisualFeedback) {
                playSuccessSound();
            }
        }
        catch (error) {
            const commandError = error instanceof Error ? error : new Error('Command execution failed');
            onError?.(commandError);
            // Provide error feedback
            if (showVisualFeedback) {
                playErrorSound();
            }
        }
        finally {
            setIsExecuting(false);
            // Clear command after 3 seconds
            feedbackTimeoutRef.current = setTimeout(() => {
                setCurrentCommand(null);
                setExecutionResult(null);
            }, 3000);
        }
    }, [isAwake, context, onCommandExecuted, onError, showVisualFeedback]);
    // Toggle listening
    const toggleListening = (0, react_1.useCallback)(() => {
        if (isListening) {
            stopListening();
            setIsAwake(false);
            resetWakeWord();
        }
        else {
            startListening();
        }
    }, [isListening, startListening, stopListening, resetWakeWord]);
    // Show/hide help
    const toggleHelp = (0, react_1.useCallback)(() => {
        setShowHelp(prev => !prev);
    }, []);
    // Audio feedback functions
    const playWakeSound = (0, react_1.useCallback)(() => {
        // In a real implementation, play wake sound
        console.log('🔊 Wake sound');
    }, []);
    const playSuccessSound = (0, react_1.useCallback)(() => {
        // In a real implementation, play success sound
        console.log('🔊 Success sound');
    }, []);
    const playErrorSound = (0, react_1.useCallback)(() => {
        // In a real implementation, play error sound
        console.log('🔊 Error sound');
    }, []);
    // Cleanup timeouts
    (0, react_1.useEffect)(() => {
        return () => {
            if (wakeTimeoutRef.current)
                clearTimeout(wakeTimeoutRef.current);
            if (feedbackTimeoutRef.current)
                clearTimeout(feedbackTimeoutRef.current);
        };
    }, []);
    // Determine theme class
    const themeClass = theme === 'auto'
        ? (window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'voice-interface--dark' : 'voice-interface--light')
        : `voice-interface--${theme}`;
    if (!isSupported) {
        return ((0, jsx_runtime_1.jsx)("div", { className: `voice-interface voice-interface--unsupported ${className}`, style: style, children: (0, jsx_runtime_1.jsxs)("div", { className: "voice-interface__error", children: [(0, jsx_runtime_1.jsx)("span", { className: "voice-interface__icon", children: "\uD83D\uDEAB" }), (0, jsx_runtime_1.jsx)("p", { children: "Voice commands not supported in this browser" })] }) }));
    }
    return ((0, jsx_runtime_1.jsxs)("div", { className: `voice-interface ${themeClass} ${className}`, style: style, children: [(0, jsx_runtime_1.jsxs)("div", { className: "voice-interface__main", children: [(0, jsx_runtime_1.jsxs)("div", { className: `voice-interface__status ${isAwake ? 'voice-interface__status--awake' : ''}`, children: [(0, jsx_runtime_1.jsx)("div", { className: "voice-interface__indicator", children: isListening ? ((0, jsx_runtime_1.jsxs)("div", { className: "voice-interface__listening", children: [(0, jsx_runtime_1.jsx)("div", { className: "voice-wave voice-wave--1" }), (0, jsx_runtime_1.jsx)("div", { className: "voice-wave voice-wave--2" }), (0, jsx_runtime_1.jsx)("div", { className: "voice-wave voice-wave--3" })] })) : ((0, jsx_runtime_1.jsx)("div", { className: "voice-interface__idle", children: (0, jsx_runtime_1.jsx)("span", { className: "voice-interface__microphone", children: "\uD83C\uDFA4" }) })) }), (0, jsx_runtime_1.jsx)("div", { className: "voice-interface__text", children: isAwake ? ((0, jsx_runtime_1.jsx)("span", { className: "voice-interface__awake-text", children: isExecuting ? 'Executing...' : 'Listening for commands' })) : ((0, jsx_runtime_1.jsxs)("span", { className: "voice-interface__sleep-text", children: ["Say \"", wakeWord, "\" to start"] })) })] }), recognizedText && ((0, jsx_runtime_1.jsxs)("div", { className: "voice-interface__recognition", children: [(0, jsx_runtime_1.jsx)("span", { className: "voice-interface__transcript", children: recognizedText }), (0, jsx_runtime_1.jsxs)("span", { className: "voice-interface__confidence", children: [Math.round(confidence * 100), "%"] })] })), currentCommand && ((0, jsx_runtime_1.jsxs)("div", { className: "voice-interface__command-feedback", children: [(0, jsx_runtime_1.jsxs)("div", { className: "command-feedback__header", children: [(0, jsx_runtime_1.jsx)("span", { className: "command-feedback__icon", children: currentCommand.icon }), (0, jsx_runtime_1.jsx)("span", { className: "command-feedback__name", children: currentCommand.description })] }), isExecuting && ((0, jsx_runtime_1.jsxs)("div", { className: "command-feedback__executing", children: [(0, jsx_runtime_1.jsx)("div", { className: "command-feedback__spinner" }), (0, jsx_runtime_1.jsx)("span", { children: "Executing command..." })] })), executionResult && ((0, jsx_runtime_1.jsx)("div", { className: "command-feedback__result", children: (0, jsx_runtime_1.jsx)("span", { className: "command-feedback__success", children: "\u2705 Command completed" }) }))] })), voiceError && ((0, jsx_runtime_1.jsxs)("div", { className: "voice-interface__error", children: [(0, jsx_runtime_1.jsx)("span", { className: "voice-interface__error-icon", children: "\u26A0\uFE0F" }), (0, jsx_runtime_1.jsx)("span", { className: "voice-interface__error-text", children: voiceError })] }))] }), (0, jsx_runtime_1.jsxs)("div", { className: "voice-interface__controls", children: [(0, jsx_runtime_1.jsx)("button", { className: `voice-control voice-control--toggle ${isListening ? 'voice-control--active' : ''}`, onClick: toggleListening, title: isListening ? 'Stop listening' : 'Start listening', children: isListening ? '🛑' : '🎙️' }), enableHelpMode && ((0, jsx_runtime_1.jsx)("button", { className: `voice-control voice-control--help ${showHelp ? 'voice-control--active' : ''}`, onClick: toggleHelp, title: "Show available commands", children: "\u2753" }))] }), showHelp && ((0, jsx_runtime_1.jsx)("div", { className: "voice-interface__help", children: (0, jsx_runtime_1.jsxs)("div", { className: "help-panel", children: [(0, jsx_runtime_1.jsxs)("div", { className: "help-panel__header", children: [(0, jsx_runtime_1.jsx)("h3", { children: "Available Voice Commands" }), (0, jsx_runtime_1.jsx)("button", { className: "help-panel__close", onClick: () => setShowHelp(false), children: "\u00D7" })] }), (0, jsx_runtime_1.jsx)("div", { className: "help-panel__content", children: Object.entries(commands.reduce((acc, cmd) => {
                                if (!acc[cmd.category])
                                    acc[cmd.category] = [];
                                acc[cmd.category].push(cmd);
                                return acc;
                            }, {})).map(([category, categoryCommands]) => ((0, jsx_runtime_1.jsxs)("div", { className: "help-category", children: [(0, jsx_runtime_1.jsx)("h4", { className: "help-category__title", children: category.charAt(0).toUpperCase() + category.slice(1) }), (0, jsx_runtime_1.jsx)("div", { className: "help-category__commands", children: categoryCommands.map(command => ((0, jsx_runtime_1.jsxs)("div", { className: "help-command", children: [(0, jsx_runtime_1.jsxs)("div", { className: "help-command__header", children: [(0, jsx_runtime_1.jsx)("span", { className: "help-command__icon", children: command.icon }), (0, jsx_runtime_1.jsx)("span", { className: "help-command__description", children: command.description })] }), (0, jsx_runtime_1.jsx)("div", { className: "help-command__examples", children: command.examples.slice(0, 2).map((example, index) => ((0, jsx_runtime_1.jsxs)("span", { className: "help-command__example", children: ["\"", example, "\""] }, index))) })] }, command.id))) })] }, category))) }), (0, jsx_runtime_1.jsx)("div", { className: "help-panel__footer", children: (0, jsx_runtime_1.jsxs)("p", { className: "help-panel__tip", children: ["\uD83D\uDCA1 Tip: Say \"", wakeWord, "\" first, then speak your command clearly."] }) })] }) }))] }));
};
exports.VoiceCommandInterface = VoiceCommandInterface;
exports.default = exports.VoiceCommandInterface;
//# sourceMappingURL=VoiceCommandInterface.js.map