/**
 * ChatArea.jsx - Message Display and Input with Select Notes Button
 */

const { useState, useEffect, useRef } = React;
const { MessageBubble } = window;

function ChatArea({ messages, isSending, onSendMessage, selectedNoteCount, onSelectNotes, onFileUpload, pendingFiles = [], onRemovePendingFile, t }) {
    const [inputValue, setInputValue] = useState('');
    const messagesEndRef = useRef(null);
    const textareaRef = useRef(null);
    const fileInputRef = useRef(null);
    const [isUploading, setIsUploading] = useState(false);

    // Auto-scroll to bottom when messages change
    useEffect(() => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [messages]);

    const handleSend = async () => {
        if (!inputValue.trim() || isSending) return;

        const message = inputValue.trim();
        setInputValue('');
        // setIsSending(true); // This line was removed in the provided diff, but the original code had it.
        // The diff implies that `isSending` is managed by the parent component or `onSendMessage` itself.
        // For now, I'll follow the diff and remove it.
        await onSendMessage(message);
        // try {
        //     await onSendMessage(message);
        // } finally {
        //     setIsSending(false);
        // }
    };

    const handleKeyDown = (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSend();
        }
    };

    const handleFileChange = async (e) => {
        const files = Array.from(e.target.files);
        if (files.length === 0) return;

        setIsUploading(true);
        try {
            await onFileUpload(files);
        } finally {
            setIsUploading(false);
            // Reset file input
            if (fileInputRef.current) {
                fileInputRef.current.value = '';
            }
        }
    };

    const handleAttachClick = () => {
        fileInputRef.current?.click();
    };

    return (
        <div style={{
            flex: 1,
            display: 'flex',
            flexDirection: 'column',
            background: 'white',
            height: '100%',
            overflow: 'hidden',
            minHeight: 0
        }}>
            {/* Messages Area - Scrollable */}
            <div style={{
                flex: 1,
                overflowY: 'auto',
                padding: '2rem',
                minHeight: 0
            }}>
                {messages.length === 0 ? (
                    <div style={{
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        justifyContent: 'center',
                        height: '100%',
                        color: '#94a3b8',
                        textAlign: 'center',
                        padding: '2rem'
                    }}>
                        <div style={{ fontSize: '4rem', marginBottom: '1.5rem', opacity: 0.5 }}>☁️</div>
                        <h2 style={{
                            fontSize: '1.75rem',
                            fontWeight: '700',
                            marginBottom: '0.75rem',
                            background: 'linear-gradient(135deg, #667eea, #764ba2)',
                            WebkitBackgroundClip: 'text',
                            WebkitTextFillColor: 'transparent'
                        }}>
                            {t('ask.welcomeTitle') || 'Welcome to Ask AI'}
                        </h2>
                        <p style={{ fontSize: '1rem', maxWidth: '500px', lineHeight: '1.6' }}>
                            {t('ask.welcomeMessage') || 'Start a new conversation by clicking "New Chat" above. Select your notes and ask questions to get instant AI-powered answers!'}
                        </p>
                    </div>
                ) : (
                    <>
                        {messages.map((msg, idx) => (
                            <MessageBubble key={idx} message={msg} t={t} />
                        ))}
                        {isSending ? (
                            <div style={{ textAlign: 'center', padding: '2rem', color: '#94a3b8' }}>
                                <div className="spinner" style={{
                                    border: '3px solid #e2e8f0',
                                    borderTop: '3px solid #3b82f6',
                                    borderRadius: '50%',
                                    width: '40px',
                                    height: '40px',
                                    animation: 'spin 1s linear infinite',
                                    margin: '0 auto 1rem'
                                }}></div>
                                <p style={{ fontSize: '0.9rem' }}>{t('ask.thinking') || 'AI is thinking...'}</p>
                            </div>
                        ) : null} {/* Added explicit null for the else branch of isSending ternary */}
                        <div ref={messagesEndRef} />
                    </>
                )}
            </div>

            {/* Select Notes Button (Above Input) */}
            <div style={{
                padding: '0.75rem 2rem 0',
                borderTop: '1px solid #e2e8f0',
                background: 'white',
                flexShrink: 0
            }}>
                <button
                    onClick={onSelectNotes}
                    style={{
                        width: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        gap: '0.5rem',
                        padding: '0.75rem 1.25rem',
                        background: selectedNoteCount > 0
                            ? 'linear-gradient(135deg, #667eea, #764ba2)'
                            : 'rgba(102, 126, 234, 0.1)',
                        color: selectedNoteCount > 0 ? 'white' : '#667eea',
                        border: selectedNoteCount > 0 ? 'none' : '2px solid #667eea',
                        borderRadius: '12px',
                        fontSize: '0.9rem',
                        fontWeight: '600',
                        cursor: 'pointer',
                        transition: 'all 0.2s',
                        boxShadow: selectedNoteCount > 0 ? '0 4px 12px rgba(102, 126, 234, 0.3)' : 'none'
                    }}
                    onMouseEnter={e => {
                        e.currentTarget.style.transform = 'translateY(-2px)';
                        e.currentTarget.style.boxShadow = '0 6px 20px rgba(102, 126, 234, 0.4)';
                    }}
                    onMouseLeave={e => {
                        e.currentTarget.style.transform = 'translateY(0)';
                        e.currentTarget.style.boxShadow = selectedNoteCount > 0 ? '0 4px 12px rgba(102, 126, 234, 0.3)' : 'none';
                    }}
                >
                    <span style={{ fontSize: '1.1rem' }}>📚</span>
                    <span>{t('ask.selectNotes') || 'Select Notes'}</span>
                    {selectedNoteCount > 0 && (
                        <span style={{
                            background: 'rgba(255,255,255,0.3)',
                            padding: '0.25rem 0.625rem',
                            borderRadius: '12px',
                            fontSize: '0.8rem',
                            fontWeight: '700'
                        }}>
                            {selectedNoteCount}
                        </span>
                    )}
                </button>
            </div>

            {/* Input Area Container */}
            <div style={{
                padding: '1rem 1.5rem',
                background: 'white',
                borderTop: '1px solid #e2e8f0',
                flexShrink: 0
            }}>
                {/* Hidden file input */}
                <input
                    ref={fileInputRef}
                    type="file"
                    multiple
                    accept="image/*,.pdf,.doc,.docx,audio/*"
                    onChange={handleFileChange}
                    style={{ display: 'none' }}
                />


                {/* Pending Files Display */}
                {pendingFiles.length > 0 && (
                    <div style={{
                        marginBottom: '0.75rem',
                        padding: '0.75rem',
                        background: '#f8f9fa',
                        borderRadius: '12px',
                        border: '1px solid #e2e8f0',
                        flexShrink: 0
                    }}>
                        <div style={{ fontSize: '0.75rem', fontWeight: '600', marginBottom: '0.5rem', color: '#64748b' }}>
                            📎 {pendingFiles.length} file{pendingFiles.length > 1 ? 's' : ''} ready to upload
                        </div>
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem' }}>
                            {pendingFiles.map((file, index) => (
                                <div key={index} style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '0.5rem',
                                    padding: '0.375rem 0.75rem',
                                    background: 'white',
                                    borderRadius: '8px',
                                    border: '1px solid #e2e8f0',
                                    fontSize: '0.8125rem'
                                }}>
                                    <span style={{ maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                        {file.name}
                                    </span>
                                    <button
                                        onClick={() => onRemovePendingFile(index)}
                                        style={{
                                            background: '#fee2e2',
                                            border: 'none',
                                            borderRadius: '4px',
                                            width: '18px',
                                            height: '18px',
                                            cursor: 'pointer',
                                            fontSize: '0.625rem',
                                            color: '#dc2626',
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'center'
                                        }}
                                    >
                                        ×
                                    </button>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {/* Input container */}
                <div style={{ display: 'flex', alignItems: 'flex-end', gap: '0.75rem' }}>
                    {/* Attach button */}
                    <button
                        onClick={handleAttachClick}
                        disabled={isUploading}
                        style={{
                            padding: '0.75rem',
                            background: isUploading ? '#e2e8f0' : 'transparent',
                            border: '2px solid #e2e8f0',
                            borderRadius: '12px',
                            cursor: isUploading ? 'not-allowed' : 'pointer',
                            fontSize: '1.25rem',
                            transition: 'all 0.2s',
                            height: '48px',
                            width: '48px',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center'
                        }}
                        onMouseEnter={e => !isUploading && (e.currentTarget.style.background = '#f1f5f9')}
                        onMouseLeave={e => !isUploading && (e.currentTarget.style.background = 'transparent')}
                        title={t('ask.attachFile') || 'Attach file'}
                    >
                        {isUploading ? '⏳' : '📎'}
                    </button>

                    {/* Textarea and Send button */}
                    <textarea
                        value={inputValue}
                        onChange={e => setInputValue(e.target.value)}
                        onKeyDown={handleKeyDown}
                        placeholder={t('ask.inputPlaceholder') || 'Type your message... (Shift+Enter for new line)'}
                        disabled={isSending}
                        style={{
                            flex: 1,
                            minHeight: '56px',
                            maxHeight: '200px',
                            padding: '1rem 1.25rem',
                            borderRadius: '16px',
                            border: '2px solid #e2e8f0',
                            fontSize: '0.9375rem',
                            fontFamily: 'inherit',
                            resize: 'none',
                            outline: 'none',
                            transition: 'border-color 0.2s',
                            background: isSending ? '#f8f9fa' : 'white',
                            color: '#64748b'
                        }}
                        onFocus={e => e.target.style.borderColor = '#667eea'}
                        onBlur={e => e.target.style.borderColor = '#e2e8f0'}
                    />

                    {/* Send button */}
                    <button
                        onClick={handleSend}
                        disabled={!inputValue.trim() || isSending}
                        style={{
                            padding: '1rem 1.75rem',
                            borderRadius: '16px',
                            border: 'none',
                            background: inputValue.trim() && !isSending
                                ? 'linear-gradient(135deg, #667eea, #764ba2)'
                                : '#e2e8f0',
                            color: 'white',
                            fontSize: '0.9375rem',
                            fontWeight: '600',
                            cursor: inputValue.trim() && !isSending ? 'pointer' : 'not-allowed',
                            boxShadow: inputValue.trim() && !isSending ? '0 4px 15px rgba(102, 126, 234, 0.4)' : 'none',
                            transition: 'all 0.2s',
                            whiteSpace: 'nowrap'
                        }}
                        onMouseEnter={e => {
                            if (inputValue.trim() && !isSending) {
                                e.currentTarget.style.transform = 'translateY(-2px)';
                                e.currentTarget.style.boxShadow = '0 6px 20px rgba(102, 126, 234, 0.5)';
                            }
                        }}
                        onMouseLeave={e => {
                            e.currentTarget.style.transform = 'translateY(0)';
                            e.currentTarget.style.boxShadow = inputValue.trim() && !isSending ? '0 4px 15px rgba(102, 126, 234, 0.4)' : 'none';
                        }}
                    >
                        {isSending ? '⏳' : '✨'} {t('ask.send') || 'Send'}
                    </button>
                </div>
            </div>
        </div>
    );
}

window.ChatArea = ChatArea;
