import React, { useState, useRef, useEffect, useCallback } from 'react'; import { SendIcon } from '../../assets/icons'; import { useSendMessage, useCurrentConversationId, useCurrentConversationState } from '../../contexts/ChatContext'; import useRenderTracker from '../../hooks/useRenderTracker'; interface InputSectionProps { scrollToBottom: (behavior: ScrollBehavior) => void; } const InputSection: React.FC = ({ scrollToBottom }) => { const sendMessage = useSendMessage(); const currentConversationId = useCurrentConversationId(); const currentConversationState = useCurrentConversationState(); const [inputValue, setInputValue] = useState(''); const textareaRef = useRef(null); const isEnabled = !currentConversationId || currentConversationState?.phase === 'IDLE'; // Only track if we're at mobile breakpoint (sm:) const [isMobile, setIsMobile] = useState(() => typeof window !== 'undefined' ? window.innerWidth < 640 : false ); useRenderTracker('InputSection', { currentConversationState, inputValue, isMobile, currentConversationId, sendMessage, scrollToBottom, }); useEffect(() => { const handleResize = () => { const mobile = window.innerWidth < 640; // Tailwind's sm: breakpoint setIsMobile(mobile); }; window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); useEffect(() => { if (textareaRef.current) { textareaRef.current.style.height = 'auto'; textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`; } }, [inputValue, isMobile]); const handleSubmit = useCallback( (e?: React.FormEvent) => { if (e) e.preventDefault(); const trimmedValue = inputValue.trim(); if (trimmedValue && isEnabled) { sendMessage(trimmedValue); setInputValue(''); setTimeout(() => { scrollToBottom('smooth'); }, 50); } }, [inputValue, isEnabled, sendMessage, scrollToBottom] ); const handleKeyDown = useCallback( (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSubmit(); } else if (e.key === 'Tab') { e.preventDefault(); const start = e.currentTarget.selectionStart; const end = e.currentTarget.selectionEnd; setInputValue((prevValue) => prevValue.substring(0, start) + '\t' + prevValue.substring(end) ); // Set cursor position after tab setTimeout(() => { if (textareaRef.current) { textareaRef.current.selectionStart = textareaRef.current.selectionEnd = start + 1; } }, 0); } }, [handleSubmit] ); return (