"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 = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = __importStar(require("react"));
const framer_motion_1 = require("framer-motion");
const react_query_1 = require("@tanstack/react-query");
const zustand_1 = require("zustand");
// Performance monitoring hook
const usePerformanceMonitor = () => {
    const [metrics, setMetrics] = (0, react_1.useState)({
        renderTime: 0,
        memoryUsage: 0,
        frameRate: 60
    });
    (0, react_1.useEffect)(() => {
        const startTime = performance.now();
        return () => {
            const endTime = performance.now();
            setMetrics(prev => ({
                ...prev,
                renderTime: endTime - startTime
            }));
        };
    }, []);
    return metrics;
};
// Zustand store for conversation state
const useConversationStore = (0, zustand_1.create)((set) => ({
    messages: [],
    activeUsers: [],
    context: {},
    isTyping: false,
    addMessage: (message) => set((state) => ({
        messages: [...state.messages, message]
    })),
    setTyping: (isTyping) => set({ isTyping }),
    updateContext: (context) => set((state) => ({
        context: { ...state.context, ...context }
    }))
}));
exports.AIConversationCanvas = react_1.default.memo(({ provider, enableRealtime = true, enableCollaboration = false, accessibilityLevel = 'aa', onMessage, maxMessages = 1000, enableVirtualization = true, performanceMode = 'standard' }) => {
    const messagesEndRef = (0, react_1.useRef)(null);
    const { messages, addMessage, isTyping } = useConversationStore();
    const [input, setInput] = (0, react_1.useState)('');
    const metrics = usePerformanceMonitor();
    // Optimize messages for performance
    const optimizedMessages = (0, react_1.useMemo)(() => {
        const messagesToShow = enableVirtualization
            ? messages.slice(-maxMessages)
            : messages;
        return performanceMode === 'high-performance'
            ? messagesToShow.slice(-50) // Limit to 50 most recent for high performance
            : messagesToShow;
    }, [messages, maxMessages, enableVirtualization, performanceMode]);
    // Throttled auto-scroll for performance
    const throttledScrollToBottom = (0, react_1.useCallback)(() => {
        if (performanceMode === 'high-performance') {
            // Use requestAnimationFrame for smooth scrolling
            requestAnimationFrame(() => {
                messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
            });
        }
        else {
            messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
        }
    }, [performanceMode]);
    // Auto-scroll to bottom with performance optimization
    (0, react_1.useEffect)(() => {
        throttledScrollToBottom();
    }, [optimizedMessages, throttledScrollToBottom]);
    // Send message mutation
    const sendMessage = (0, react_query_1.useMutation)({
        mutationFn: async (content) => {
            const message = {
                id: crypto.randomUUID(),
                content,
                role: 'user',
                timestamp: new Date()
            };
            addMessage(message);
            // Call AI provider
            const response = await provider.sendMessage(content);
            addMessage(response);
            onMessage?.(response);
            return response;
        }
    });
    const handleSubmit = (0, react_1.useCallback)((e) => {
        e.preventDefault();
        if (input.trim() && !sendMessage.isPending) {
            sendMessage.mutate(input);
            setInput('');
        }
    }, [input, sendMessage]);
    // Handle keyboard shortcuts
    const handleKeyDown = (0, react_1.useCallback)((e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSubmit(e);
        }
        else if (e.key === 'Escape') {
            setInput('');
        }
    }, [handleSubmit]);
    return ((0, jsx_runtime_1.jsxs)("div", { className: "ai-conversation-canvas flex flex-col h-full bg-white dark:bg-gray-900 rounded-lg shadow-lg", role: "region", "aria-label": "AI Conversation", children: [(0, jsx_runtime_1.jsxs)("div", { className: "flex-1 overflow-y-auto p-4 space-y-4", role: "log", "aria-live": "polite", "aria-label": "Conversation messages", children: [(0, jsx_runtime_1.jsx)(framer_motion_1.AnimatePresence, { children: optimizedMessages.map((message) => ((0, jsx_runtime_1.jsx)(framer_motion_1.motion.div, { initial: performanceMode === 'high-performance' ? false : { opacity: 0, y: 20 }, animate: performanceMode === 'high-performance' ? false : { opacity: 1, y: 0 }, exit: performanceMode === 'high-performance' ? false : { opacity: 0, y: -20 }, className: `message ${message.role === 'user' ? 'ml-auto' : 'mr-auto'} max-w-[80%]`, children: (0, jsx_runtime_1.jsxs)("div", { className: `p-3 rounded-lg ${message.role === 'user'
                                    ? 'bg-blue-500 text-white'
                                    : 'bg-gray-200 dark:bg-gray-700 text-gray-900 dark:text-white'}`, role: "article", "aria-label": `Message from ${message.role}`, tabIndex: 0, children: [(0, jsx_runtime_1.jsx)("span", { className: "sr-only", children: message.role === 'user' ? 'You said:' : 'AI responded:' }), message.content, (0, jsx_runtime_1.jsxs)("span", { className: "sr-only", children: ["at ", message.timestamp.toLocaleTimeString()] })] }) }, message.id))) }), isTyping && ((0, jsx_runtime_1.jsxs)(framer_motion_1.motion.div, { initial: { opacity: 0 }, animate: { opacity: 1 }, className: "typing-indicator", "aria-live": "polite", "aria-label": "AI is typing", children: [(0, jsx_runtime_1.jsx)("span", { className: "dot", children: "\u2022" }), (0, jsx_runtime_1.jsx)("span", { className: "dot", children: "\u2022" }), (0, jsx_runtime_1.jsx)("span", { className: "dot", children: "\u2022" })] })), (0, jsx_runtime_1.jsx)("div", { ref: messagesEndRef })] }), (0, jsx_runtime_1.jsx)("form", { onSubmit: handleSubmit, className: "p-4 border-t dark:border-gray-700", children: (0, jsx_runtime_1.jsxs)("div", { className: "flex gap-2", children: [(0, jsx_runtime_1.jsx)("label", { htmlFor: "message-input", className: "sr-only", children: "Type your message to send to the AI assistant" }), (0, jsx_runtime_1.jsx)("input", { id: "message-input", type: "text", value: input, onChange: (e) => setInput(e.target.value), onKeyDown: handleKeyDown, placeholder: "Type your message...", className: "flex-1 px-4 py-2 rounded-lg border dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2", "aria-label": "Message input", "aria-describedby": "message-help", disabled: sendMessage.isPending, autoComplete: "off", maxLength: 4000 }), (0, jsx_runtime_1.jsx)("div", { id: "message-help", className: "sr-only", children: "Press Enter to send message, Escape to clear input" }), (0, jsx_runtime_1.jsx)("button", { type: "submit", disabled: sendMessage.isPending || !input.trim(), className: "px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors duration-200", "aria-label": sendMessage.isPending ? "Sending message..." : "Send message", "aria-describedby": "send-button-help", children: sendMessage.isPending ? ((0, jsx_runtime_1.jsx)("span", { "aria-hidden": "true", children: "..." })) : ('Send') }), (0, jsx_runtime_1.jsx)("div", { id: "send-button-help", className: "sr-only", children: sendMessage.isPending ? "Message is being sent" : "Click to send your message" })] }) })] }));
});
exports.AIConversationCanvas.displayName = 'AIConversationCanvas';
//# sourceMappingURL=AIConversationCanvas.js.map