"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.AIConversationCanvas = exports.ConversationSchema = exports.MessageSchema = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
/**
 * AI Conversation Canvas - Revolutionary real-time AI interaction component
 * Features: Voice input, streaming responses, collaborative editing, context visualization
 */
const react_1 = __importStar(require("react"));
const zod_1 = require("zod");
const useAIConversation_1 = require("../hooks/useAIConversation");
const useVoiceInput_1 = require("../hooks/useVoiceInput");
const useRealtimeCollaboration_1 = require("../hooks/useRealtimeCollaboration");
const useContextVisualization_1 = require("../hooks/useContextVisualization");
const useStreamingResponse_1 = require("../hooks/useStreamingResponse");
// Type definitions
exports.MessageSchema = zod_1.z.object({
    id: zod_1.z.string(),
    role: zod_1.z.enum(['user', 'assistant', 'system']),
    content: zod_1.z.string(),
    timestamp: zod_1.z.date(),
    metadata: zod_1.z.object({
        model: zod_1.z.string().optional(),
        provider: zod_1.z.string().optional(),
        tokens: zod_1.z.number().optional(),
        cost: zod_1.z.number().optional(),
        latency: zod_1.z.number().optional(),
        confidence: zod_1.z.number().optional(),
        sources: zod_1.z.array(zod_1.z.string()).optional()
    }).optional(),
    attachments: zod_1.z.array(zod_1.z.object({
        type: zod_1.z.enum(['image', 'audio', 'document', 'code']),
        url: zod_1.z.string(),
        name: zod_1.z.string(),
        size: zod_1.z.number().optional()
    })).optional(),
    reactions: zod_1.z.record(zod_1.z.number()).optional(),
    isStreaming: zod_1.z.boolean().optional(),
    isEditing: zod_1.z.boolean().optional()
});
exports.ConversationSchema = zod_1.z.object({
    id: zod_1.z.string(),
    title: zod_1.z.string(),
    messages: zod_1.z.array(exports.MessageSchema),
    participants: zod_1.z.array(zod_1.z.object({
        id: zod_1.z.string(),
        name: zod_1.z.string(),
        role: zod_1.z.enum(['user', 'ai', 'collaborator']),
        avatar: zod_1.z.string().optional(),
        isActive: zod_1.z.boolean(),
        cursor: zod_1.z.object({
            x: zod_1.z.number(),
            y: zod_1.z.number(),
            color: zod_1.z.string()
        }).optional()
    })),
    context: zod_1.z.object({
        domain: zod_1.z.string().optional(),
        project: zod_1.z.string().optional(),
        tags: zod_1.z.array(zod_1.z.string()).optional(),
        priority: zod_1.z.enum(['low', 'normal', 'high', 'urgent']).optional(),
        mood: zod_1.z.enum(['casual', 'professional', 'creative', 'analytical']).optional()
    }).optional(),
    settings: zod_1.z.object({
        allowVoice: zod_1.z.boolean().default(true),
        enableCollaboration: zod_1.z.boolean().default(true),
        showContext: zod_1.z.boolean().default(true),
        autoSave: zod_1.z.boolean().default(true),
        theme: zod_1.z.enum(['light', 'dark', 'system']).default('system'),
        aiProvider: zod_1.z.string().optional(),
        aiModel: zod_1.z.string().optional()
    }).optional(),
    metadata: zod_1.z.object({
        createdAt: zod_1.z.date(),
        updatedAt: zod_1.z.date(),
        version: zod_1.z.number(),
        tokensUsed: zod_1.z.number().optional(),
        totalCost: zod_1.z.number().optional()
    }).optional()
});
const AIConversationCanvas = ({ conversationId, initialConversation, onMessageSent, onConversationUpdated, className = '', style = {}, enableVoice = true, enableCollaboration = true, enableContextVisualization = true, aiProvider = 'auto', aiModel = 'auto', maxMessages = 100, autoClearAfter, customTools = [] }) => {
    // Hooks for AI conversation management
    const { conversation, sendMessage, editMessage, deleteMessage, clearConversation, isLoading, error } = (0, useAIConversation_1.useAIConversation)({
        conversationId,
        initialConversation,
        provider: aiProvider,
        model: aiModel,
        onConversationUpdated
    });
    // Voice input hook
    const { isListening, startListening, stopListening, transcript, confidence, isSupported: voiceSupported } = (0, useVoiceInput_1.useVoiceInput)({
        enabled: enableVoice,
        continuous: true,
        interimResults: true,
        language: 'en-US'
    });
    // Real-time collaboration hook
    const { collaborators, userCursors, shareConversation, broadcastMessage, onCollaboratorJoined, onCollaboratorLeft } = (0, useRealtimeCollaboration_1.useRealtimeCollaboration)({
        enabled: enableCollaboration,
        conversationId: conversation?.id
    });
    // Context visualization hook
    const { contextGraph, topicClusters, semanticMap, updateContext } = (0, useContextVisualization_1.useContextVisualization)({
        enabled: enableContextVisualization,
        messages: conversation?.messages || []
    });
    // Streaming response hook
    const { streamingMessage, isStreaming, streamResponse } = (0, useStreamingResponse_1.useStreamingResponse)();
    // Local state
    const [inputText, setInputText] = (0, react_1.useState)('');
    const [isVoiceMode, setIsVoiceMode] = (0, react_1.useState)(false);
    const [showContextPanel, setShowContextPanel] = (0, react_1.useState)(false);
    const [selectedMessage, setSelectedMessage] = (0, react_1.useState)(null);
    const [attachments, setAttachments] = (0, react_1.useState)([]);
    const [contextSuggestions, setContextSuggestions] = (0, react_1.useState)([]);
    // Refs
    const messagesEndRef = (0, react_1.useRef)(null);
    const inputRef = (0, react_1.useRef)(null);
    const canvasRef = (0, react_1.useRef)(null);
    const fileInputRef = (0, react_1.useRef)(null);
    // Scroll to bottom when new messages arrive
    (0, react_1.useEffect)(() => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [conversation?.messages, streamingMessage]);
    // Handle voice input
    (0, react_1.useEffect)(() => {
        if (transcript && confidence > 0.7) {
            setInputText(transcript);
        }
    }, [transcript, confidence]);
    // Auto-save conversation
    (0, react_1.useEffect)(() => {
        if (conversation?.settings?.autoSave && conversation.id) {
            const timeoutId = setTimeout(() => {
                // Auto-save logic would go here
                console.log('Auto-saving conversation...');
            }, 2000);
            return () => clearTimeout(timeoutId);
        }
    }, [conversation]);
    // Handle message sending
    const handleSendMessage = (0, react_1.useCallback)(async () => {
        if (!inputText.trim() && attachments.length === 0)
            return;
        const newMessage = {
            role: 'user',
            content: inputText.trim(),
            timestamp: new Date(),
            attachments: attachments.map(file => ({
                type: getFileType(file),
                url: URL.createObjectURL(file),
                name: file.name,
                size: file.size
            }))
        };
        try {
            const sentMessage = await sendMessage(newMessage);
            onMessageSent?.(sentMessage);
            setInputText('');
            setAttachments([]);
            // Stream AI response
            if (sentMessage) {
                await streamResponse({
                    messages: [...(conversation?.messages || []), sentMessage],
                    provider: aiProvider,
                    model: aiModel
                });
            }
        }
        catch (error) {
            console.error('Failed to send message:', error);
        }
    }, [inputText, attachments, sendMessage, onMessageSent, conversation, streamResponse, aiProvider, aiModel]);
    // Handle voice toggle
    const handleVoiceToggle = (0, react_1.useCallback)(() => {
        if (isListening) {
            stopListening();
            setIsVoiceMode(false);
            if (transcript) {
                handleSendMessage();
            }
        }
        else {
            startListening();
            setIsVoiceMode(true);
        }
    }, [isListening, startListening, stopListening, transcript, handleSendMessage]);
    // Handle file attachments
    const handleFileAttachment = (0, react_1.useCallback)((files) => {
        const newAttachments = Array.from(files).slice(0, 5 - attachments.length);
        setAttachments(prev => [...prev, ...newAttachments]);
    }, [attachments.length]);
    // Handle key events
    const handleKeyDown = (0, react_1.useCallback)((e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSendMessage();
        }
    }, [handleSendMessage]);
    // Generate context suggestions
    const generateContextSuggestions = (0, react_1.useCallback)(async () => {
        if (conversation?.messages && conversation.messages.length > 0) {
            // In a real implementation, this would call an AI service
            const suggestions = [
                'Continue this conversation',
                'Summarize key points',
                'Ask follow-up questions',
                'Switch to different topic',
                'Export conversation'
            ];
            setContextSuggestions(suggestions);
        }
    }, [conversation?.messages]);
    // Utility function to determine file type
    const getFileType = (file) => {
        if (file.type.startsWith('image/'))
            return 'image';
        if (file.type.startsWith('audio/'))
            return 'audio';
        if (file.name.endsWith('.js') || file.name.endsWith('.ts') || file.name.endsWith('.py'))
            return 'code';
        return 'document';
    };
    // Memoized message components
    const MessageComponent = (0, react_1.useMemo)(() => react_1.default.memo(({ message, isSelected, onSelect }) => ((0, jsx_runtime_1.jsxs)("div", { className: `message message--${message.role} ${isSelected ? 'message--selected' : ''}`, onClick: () => onSelect(message.id), children: [(0, jsx_runtime_1.jsxs)("div", { className: "message__header", children: [(0, jsx_runtime_1.jsx)("div", { className: "message__role", children: message.role }), (0, jsx_runtime_1.jsx)("div", { className: "message__timestamp", children: message.timestamp.toLocaleTimeString() }), message.metadata && ((0, jsx_runtime_1.jsxs)("div", { className: "message__metadata", children: [message.metadata.model && ((0, jsx_runtime_1.jsx)("span", { className: "message__model", children: message.metadata.model })), message.metadata.cost && ((0, jsx_runtime_1.jsxs)("span", { className: "message__cost", children: ["$", message.metadata.cost.toFixed(4)] })), message.metadata.latency && ((0, jsx_runtime_1.jsxs)("span", { className: "message__latency", children: [message.metadata.latency, "ms"] }))] }))] }), (0, jsx_runtime_1.jsxs)("div", { className: "message__content", children: [message.content, message.isStreaming && (0, jsx_runtime_1.jsx)("span", { className: "message__cursor", children: "|" })] }), message.attachments && message.attachments.length > 0 && ((0, jsx_runtime_1.jsx)("div", { className: "message__attachments", children: message.attachments.map((attachment, index) => ((0, jsx_runtime_1.jsxs)("div", { className: `attachment attachment--${attachment.type}`, children: [(0, jsx_runtime_1.jsx)("span", { className: "attachment__name", children: attachment.name }), attachment.size && ((0, jsx_runtime_1.jsxs)("span", { className: "attachment__size", children: [(attachment.size / 1024).toFixed(1), "KB"] }))] }, index))) })), message.reactions && Object.keys(message.reactions).length > 0 && ((0, jsx_runtime_1.jsx)("div", { className: "message__reactions", children: Object.entries(message.reactions).map(([emoji, count]) => ((0, jsx_runtime_1.jsxs)("button", { className: "reaction", children: [emoji, " ", count] }, emoji))) }))] }))), []);
    return ((0, jsx_runtime_1.jsxs)("div", { ref: canvasRef, className: `ai-conversation-canvas ${className}`, style: style, children: [(0, jsx_runtime_1.jsxs)("div", { className: "canvas__header", children: [(0, jsx_runtime_1.jsx)("div", { className: "canvas__title", children: conversation?.title || 'AI Conversation' }), enableCollaboration && collaborators.length > 0 && ((0, jsx_runtime_1.jsx)("div", { className: "canvas__collaborators", children: collaborators.map(collaborator => ((0, jsx_runtime_1.jsxs)("div", { className: `collaborator ${collaborator.isActive ? 'collaborator--active' : ''}`, children: [collaborator.avatar ? ((0, jsx_runtime_1.jsx)("img", { src: collaborator.avatar, alt: collaborator.name })) : ((0, jsx_runtime_1.jsx)("div", { className: "collaborator__avatar", children: collaborator.name[0] })), (0, jsx_runtime_1.jsx)("span", { className: "collaborator__name", children: collaborator.name })] }, collaborator.id))) })), (0, jsx_runtime_1.jsxs)("div", { className: "canvas__tools", children: [customTools.map(tool => ((0, jsx_runtime_1.jsx)("button", { className: "tool-button", onClick: () => conversation && tool.action(conversation), title: tool.name, children: tool.icon }, tool.id))), enableContextVisualization && ((0, jsx_runtime_1.jsx)("button", { className: `tool-button ${showContextPanel ? 'tool-button--active' : ''}`, onClick: () => setShowContextPanel(!showContextPanel), title: "Show Context Visualization", children: "\uD83E\uDDE0" })), (0, jsx_runtime_1.jsx)("button", { className: "tool-button", onClick: clearConversation, title: "Clear Conversation", children: "\uD83D\uDDD1\uFE0F" })] })] }), (0, jsx_runtime_1.jsxs)("div", { className: "canvas__content", children: [(0, jsx_runtime_1.jsxs)("div", { className: "canvas__messages", children: [(0, jsx_runtime_1.jsxs)("div", { className: "messages", children: [conversation?.messages.map(message => ((0, jsx_runtime_1.jsx)(MessageComponent, { message: message, isSelected: selectedMessage === message.id, onSelect: setSelectedMessage }, message.id))), streamingMessage && ((0, jsx_runtime_1.jsxs)("div", { className: "message message--assistant message--streaming", children: [(0, jsx_runtime_1.jsxs)("div", { className: "message__header", children: [(0, jsx_runtime_1.jsx)("div", { className: "message__role", children: "assistant" }), (0, jsx_runtime_1.jsxs)("div", { className: "message__status", children: [(0, jsx_runtime_1.jsx)("span", { className: "streaming-indicator", children: "\u25CF" }), "Streaming..."] })] }), (0, jsx_runtime_1.jsxs)("div", { className: "message__content", children: [streamingMessage, (0, jsx_runtime_1.jsx)("span", { className: "message__cursor", children: "|" })] })] })), enableCollaboration && userCursors.map(cursor => ((0, jsx_runtime_1.jsx)("div", { className: "user-cursor", style: {
                                            left: cursor.x,
                                            top: cursor.y,
                                            borderColor: cursor.color
                                        }, children: (0, jsx_runtime_1.jsx)("div", { className: "user-cursor__name", children: cursor.userName }) }, cursor.userId))), (0, jsx_runtime_1.jsx)("div", { ref: messagesEndRef })] }), contextSuggestions.length > 0 && ((0, jsx_runtime_1.jsx)("div", { className: "canvas__suggestions", children: contextSuggestions.map((suggestion, index) => ((0, jsx_runtime_1.jsx)("button", { className: "suggestion-button", onClick: () => setInputText(suggestion), children: suggestion }, index))) }))] }), enableContextVisualization && showContextPanel && ((0, jsx_runtime_1.jsxs)("div", { className: "canvas__context-panel", children: [(0, jsx_runtime_1.jsxs)("div", { className: "context-panel__header", children: [(0, jsx_runtime_1.jsx)("h3", { children: "Conversation Context" }), (0, jsx_runtime_1.jsx)("button", { onClick: () => setShowContextPanel(false), children: "\u00D7" })] }), (0, jsx_runtime_1.jsxs)("div", { className: "context-panel__content", children: [topicClusters.length > 0 && ((0, jsx_runtime_1.jsxs)("div", { className: "context-section", children: [(0, jsx_runtime_1.jsx)("h4", { children: "Topics Discussed" }), (0, jsx_runtime_1.jsx)("div", { className: "topic-clusters", children: topicClusters.map((cluster, index) => ((0, jsx_runtime_1.jsxs)("div", { className: "topic-cluster", children: [(0, jsx_runtime_1.jsx)("div", { className: "topic-cluster__name", children: cluster.name }), (0, jsx_runtime_1.jsx)("div", { className: "topic-cluster__weight", children: cluster.weight.toFixed(2) })] }, index))) })] })), semanticMap && ((0, jsx_runtime_1.jsxs)("div", { className: "context-section", children: [(0, jsx_runtime_1.jsx)("h4", { children: "Semantic Relationships" }), (0, jsx_runtime_1.jsx)("div", { className: "semantic-map", children: (0, jsx_runtime_1.jsx)("canvas", { width: "300", height: "200" }) })] })), contextGraph && ((0, jsx_runtime_1.jsxs)("div", { className: "context-section", children: [(0, jsx_runtime_1.jsx)("h4", { children: "Context Flow" }), (0, jsx_runtime_1.jsx)("div", { className: "context-graph", children: (0, jsx_runtime_1.jsx)("svg", { width: "300", height: "150" }) })] }))] })] }))] }), (0, jsx_runtime_1.jsxs)("div", { className: "canvas__input", children: [attachments.length > 0 && ((0, jsx_runtime_1.jsx)("div", { className: "canvas__attachments", children: attachments.map((file, index) => ((0, jsx_runtime_1.jsxs)("div", { className: "attachment-preview", children: [(0, jsx_runtime_1.jsx)("span", { className: "attachment-preview__name", children: file.name }), (0, jsx_runtime_1.jsx)("button", { className: "attachment-preview__remove", onClick: () => setAttachments(prev => prev.filter((_, i) => i !== index)), children: "\u00D7" })] }, index))) })), (0, jsx_runtime_1.jsxs)("div", { className: "input-container", children: [isVoiceMode && ((0, jsx_runtime_1.jsxs)("div", { className: "voice-indicator", children: [(0, jsx_runtime_1.jsxs)("div", { className: "voice-indicator__animation", children: [(0, jsx_runtime_1.jsx)("div", { className: "voice-wave" }), (0, jsx_runtime_1.jsx)("div", { className: "voice-wave" }), (0, jsx_runtime_1.jsx)("div", { className: "voice-wave" })] }), (0, jsx_runtime_1.jsxs)("span", { children: ["Listening... (", confidence.toFixed(0), "% confidence)"] })] })), (0, jsx_runtime_1.jsx)("textarea", { ref: inputRef, value: inputText, onChange: (e) => setInputText(e.target.value), onKeyDown: handleKeyDown, placeholder: isVoiceMode ? "Speak or type your message..." : "Type your message...", className: "message-input", rows: 1, disabled: isLoading || isStreaming }), (0, jsx_runtime_1.jsxs)("div", { className: "input-controls", children: [(0, jsx_runtime_1.jsx)("button", { className: "control-button", onClick: () => fileInputRef.current?.click(), title: "Attach file", children: "\uD83D\uDCCE" }), (0, jsx_runtime_1.jsx)("input", { ref: fileInputRef, type: "file", multiple: true, hidden: true, onChange: (e) => e.target.files && handleFileAttachment(e.target.files) }), enableVoice && voiceSupported && ((0, jsx_runtime_1.jsx)("button", { className: `control-button ${isVoiceMode ? 'control-button--active' : ''}`, onClick: handleVoiceToggle, title: isListening ? "Stop listening" : "Start voice input", children: isListening ? '🎤' : '🎙️' })), (0, jsx_runtime_1.jsx)("button", { className: "send-button", onClick: handleSendMessage, disabled: (!inputText.trim() && attachments.length === 0) || isLoading || isStreaming, title: "Send message", children: isLoading || isStreaming ? '⏳' : '📤' })] })] })] }), (0, jsx_runtime_1.jsxs)("div", { className: "canvas__status", children: [(0, jsx_runtime_1.jsxs)("div", { className: "status__info", children: [conversation?.metadata && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [conversation.metadata.tokensUsed && ((0, jsx_runtime_1.jsxs)("span", { className: "status__tokens", children: [conversation.metadata.tokensUsed.toLocaleString(), " tokens"] })), conversation.metadata.totalCost && ((0, jsx_runtime_1.jsxs)("span", { className: "status__cost", children: ["$", conversation.metadata.totalCost.toFixed(4)] }))] })), error && ((0, jsx_runtime_1.jsxs)("span", { className: "status__error", children: ["Error: ", error] }))] }), (0, jsx_runtime_1.jsxs)("div", { className: "status__actions", children: [(0, jsx_runtime_1.jsx)("button", { onClick: generateContextSuggestions, children: "\uD83D\uDCA1 Get Suggestions" }), enableCollaboration && ((0, jsx_runtime_1.jsx)("button", { onClick: () => shareConversation(conversation?.id || ''), children: "\uD83D\uDD17 Share" }))] })] })] }));
};
exports.AIConversationCanvas = AIConversationCanvas;
exports.default = exports.AIConversationCanvas;
//# sourceMappingURL=AIConversationCanvas.js.map