import AdminLayout from '@/Layouts/AdminLayout';
import { Head, usePage } from '@inertiajs/react';
import { useState, useEffect, useRef, Fragment } from 'react';
import axios from 'axios';

// --- Utility Components for Clarity ---

// Simplified Button Component
const IconButton = ({ children, onClick, className = '' }) => (
    <button
        type="button"
        onClick={onClick}
        className={`p-2 rounded-full text-gray-600 hover:bg-gray-100 transition-colors duration-150 ${className}`}
    >
        {children}
    </button>
);

// Emoji Picker Overlay
const EmojiPicker = ({ emojis, onSelect, onClose }) => (
    <div className="absolute bottom-full mb-2 left-0 right-0 md:left-4 md:right-auto md:w-80 bg-white rounded-xl shadow-2xl p-3 border border-gray-200 z-30 max-h-64 overflow-y-auto transform origin-bottom">
        <div className="grid grid-cols-8 gap-1">
            {emojis.map((emoji, index) => (
                <button
                    key={index}
                    className="text-2xl hover:bg-gray-100 rounded-lg p-1 transition-colors"
                    onClick={() => onSelect(emoji)}
                >
                    {emoji}
                </button>
            ))}
        </div>
        <button className="text-xs text-gray-500 hover:text-gray-700 mt-2 block w-full text-right" onClick={onClose}>Close</button>
    </div>
);

// --- Main Chat Component ---

export default function Index({ conversations: initialConversations }) {
    const { auth } = usePage().props;
    const [conversations, setConversations] = useState(initialConversations);
    const [selectedConversation, setSelectedConversation] = useState(initialConversations[0] || null);
    const [messages, setMessages] = useState([]);
    const [messageInput, setMessageInput] = useState('');
    const [searchTerm, setSearchTerm] = useState('');
    
    // UI State for mobile/overlays
    const [showMobileConversation, setShowMobileConversation] = useState(false);
    const [showEmojiPicker, setShowEmojiPicker] = useState(false);
    const [showAttachments, setShowAttachments] = useState(false);

    // Messaging/Loading State
    const [loadingMessages, setLoadingMessages] = useState(false);
    const [isTyping, setIsTyping] = useState(false); // Placeholder for real-time feature
    const [onlineUsers, setOnlineUsers] = useState(['John Doe', 'Jane Smith', 'Alice Brown', 'Bob Green']);
    
    const messagesEndRef = useRef(null);
    const inputRef = useRef(null);
    
    const emojis = ['😀', '😃', '😄', '😁', '😅', '😂', '🤣', '😊', '😇', '🙂', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛', '😜', '🤪', '😝', '🤗', '🤭', '🤫', '🤔', '🤐', '🤨', '😐', '😑', '😶', '😏', '😒', '🙄', '😬', '🤥', '😌', '😔', '😪', '🤤', '😴', '😷', '🤒', '🤕', '🤢', '🤮', '🤧', '🥵', '🥶', '🥴', '😵', '🤯', '🤠', '🥳', '😎', '🤓', '🧐', '😕', '😟', '🙁', '☹️', '😮', '😯', '😲', '😳', '🥺', '😦', '😧', '😨', '😰', '😥', '😢', '😭', '😱', '😖', '😣', '😞', '😓', '😩', '😫', '🥱', '😤', '😡', '😠', '🤬', '😈', '👿', '💀', '☠️', '💩', '🤡', '👹', '👺', '👻', '👽', '👾', '🤖', '❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍', '🤎', '💔', '❣️', '💕', '💞', '💓', '💗', '💖', '💘', '💝', '👍', '👎', '👌', '✌️', '🤞', '🤟', '🤘', '🤙', '👈', '👉', '👆', '👇', '☝️', '✋', '🤚', '🖐️', '🖖', '👋', '🤙', '💪', '🙏'];


    // --- Effects & Handlers ---

    useEffect(() => {
        if (selectedConversation) {
            setLoadingMessages(true);
            axios.get(route('user.messages.show', selectedConversation.id)).then((response) => {
                setMessages(response.data.messages);
                setLoadingMessages(false);
            }).catch(() => {
                setLoadingMessages(false);
            });
        }
    }, [selectedConversation]);

    useEffect(() => {
        // Scroll to bottom after new messages or when messages are loaded
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [messages, loadingMessages]);

    const sendMessage = () => {
        if (messageInput.trim() === '') return;

        axios.post(route('user.messages.store', selectedConversation.id), {
            body: messageInput,
        }).then((response) => {
            setMessages([...messages, response.data]);
            setMessageInput('');
        }).catch(error => {
            console.error('Message send failed:', error);
        });
    };

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

    const handleConversationSelect = (convo) => {
        setSelectedConversation(convo);
        setShowMobileConversation(true); // Switch to chat view on mobile
        setShowEmojiPicker(false); // Close any overlays
        setShowAttachments(false);
    };

    const handleBackToList = () => {
        setShowMobileConversation(false); // Switch to list view on mobile
    };
    
    const handleEmojiSelect = (emoji) => {
        setMessageInput(prev => prev + emoji);
        setShowEmojiPicker(false);
        inputRef.current?.focus();
    };
    
    const handleToggleAttachments = () => {
        setShowAttachments(prev => !prev);
        setShowEmojiPicker(false); // Close other overlay
    };

    const handleToggleEmojiPicker = () => {
        setShowEmojiPicker(prev => !prev);
        setShowAttachments(false); // Close other overlay
    };


    const filteredConversations = conversations.filter(convo => 
        convo.with.toLowerCase().includes(searchTerm.toLowerCase())
    );

    // --- Components for Visual Clarity ---

    const ConversationAvatar = ({ user, size = '10', isOnline, showBadge = true }) => {
        const initials = user.split(' ').map(n => n[0]).join('');
        return (
            <div className="relative flex-shrink-0">
                <div className={`h-${size} w-${size} rounded-full bg-gradient-to-br from-emerald-400 to-teal-500 flex items-center justify-center text-white font-semibold text-sm ring-2 ring-white shadow-sm`}>
                    {initials}
                </div>
                {isOnline && showBadge && (
                    <span className="absolute bottom-0 right-0 h-3 w-3 bg-green-500 rounded-full border-2 border-white"></span>
                )}
            </div>
        );
    };

    const OnlineUsersStrip = () => (
        <div className="p-4 border-b border-gray-100 bg-white">
            <div className="flex items-center justify-between mb-2">
                <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wider">Online Now</h3>
                <span className="text-xs text-emerald-600 font-medium">{onlineUsers.length} active</span>
            </div>
            <div className="flex space-x-3 overflow-x-auto pb-1 -mx-4 px-4 scrollbar-hide">
                {onlineUsers.map((user, index) => (
                    <div key={index} className="flex flex-col items-center flex-shrink-0">
                        <ConversationAvatar user={user} size="10" isOnline={true} showBadge={false} />
                        <span className="text-xs text-gray-600 mt-1 truncate max-w-[3rem]">{user.split(' ')[0]}</span>
                    </div>
                ))}
            </div>
        </div>
    );

    // --- Render Logic ---

    return (
        <AdminLayout>
            <Head title="My Messages" />

            {/* Main Chat Container - Responsive Height */}
            <div className="flex h-[calc(100vh-65px)] bg-gray-100 rounded-xl overflow-hidden shadow-2xl">
                
                {/* 1. Conversations List Panel */}
                <div className={`${showMobileConversation ? 'hidden' : 'flex'} w-full md:flex md:w-1/3 lg:w-1/4 border-r border-gray-200 flex-col bg-white`}>
                    
                    {/* Header with Search (Attractive Gradient) */}
                    <div className="p-4 border-b border-gray-200 bg-gradient-to-r from-emerald-600 to-teal-700 shadow-md">
                        <h2 className="text-2xl font-extrabold text-white mb-3">Chats</h2>
                        <div className="relative">
                            <input
                                type="text"
                                placeholder="Search conversations..."
                                className="block w-full pl-10 pr-3 py-2 border border-transparent rounded-full bg-white/20 backdrop-blur text-white placeholder-white/70 focus:outline-none focus:ring-2 focus:ring-white/80 focus:bg-white/30 transition duration-150 text-sm"
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                            />
                            <svg className="absolute inset-y-0 left-0 ml-3 h-5 w-5 text-white/70 my-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                            </svg>
                        </div>
                    </div>
                    
                    <OnlineUsersStrip />
                    
                    {/* Conversations List */}
                    {conversations.length > 0 ? (
                        <div className="overflow-y-auto flex-1">
                            {filteredConversations.length > 0 ? (
                                <ul>
                                    {filteredConversations.map((convo) => (
                                        <li
                                            key={convo.id}
                                            className={`cursor-pointer transition-all duration-200 ${selectedConversation?.id === convo.id ? 'bg-emerald-50 border-l-4 border-emerald-500 font-semibold' : 'hover:bg-gray-50 border-l-4 border-transparent'}`}
                                            onClick={() => handleConversationSelect(convo)}
                                        >
                                            <div className="flex items-center p-4">
                                                <ConversationAvatar user={convo.with} size="12" isOnline={convo.isOnline} />
                                                <div className="flex-1 min-w-0 ml-3">
                                                    <div className="flex justify-between items-baseline">
                                                        <h3 className="text-gray-900 truncate">{convo.with}</h3>
                                                        <p className="text-xs text-gray-500 ml-2 flex-shrink-0">{convo.timestamp}</p>
                                                    </div>
                                                    <div className="flex justify-between items-center mt-0.5">
                                                        <p className="text-sm text-gray-600 truncate">
                                                            {convo.lastMessage}
                                                        </p>
                                                        {convo.unread > 0 && (
                                                            <span className="bg-emerald-500 text-white text-xs rounded-full px-2 py-0.5 ml-2 flex-shrink-0 shadow-sm">
                                                                {convo.unread}
                                                            </span>
                                                        )}
                                                    </div>
                                                </div>
                                            </div>
                                        </li>
                                    ))}
                                </ul>
                            ) : (
                                // No Search Results State
                                <div className="flex flex-col items-center justify-center h-full p-6 text-center">
                                    <p className="text-sm text-gray-500">No results for "{searchTerm}"</p>
                                    <button 
                                        className="mt-3 px-3 py-1 text-sm bg-emerald-600 text-white rounded-full hover:bg-emerald-700 transition-colors shadow-md"
                                        onClick={() => setSearchTerm('')}
                                    >
                                        Clear Search
                                    </button>
                                </div>
                            )}
                        </div>
                    ) : (
                        // No Conversations State
                        <div className="flex-1 flex flex-col items-center justify-center p-6 text-center">
                            <svg className="h-12 w-12 text-emerald-600 mb-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                            </svg>
                            <h3 className="text-lg font-semibold text-gray-900 mb-2">No conversations yet</h3>
                            <button className="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors shadow-md mt-3">
                                Start New Chat
                            </button>
                        </div>
                    )}
                </div>
                
                {/* 2. Messages Area Panel */}
                {selectedConversation ? (
                    <div className={`${showMobileConversation ? 'flex' : 'hidden'} w-full md:flex md:w-2/3 lg:w-3/4 flex-col bg-white`}>
                        
                        {/* Chat Header */}
                        <div className="p-4 border-b border-gray-200 bg-white shadow-sm">
                            <div className="flex items-center justify-between">
                                <div className="flex items-center">
                                    {/* Mobile back button */}
                                    <IconButton onClick={handleBackToList} className="mr-2 md:hidden">
                                        <svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" /></svg>
                                    </IconButton>
                                    <ConversationAvatar user={selectedConversation.with} size="10" isOnline={selectedConversation.isOnline} />
                                    <div className="ml-3">
                                        <h2 className="text-lg font-semibold text-gray-900">{selectedConversation.with}</h2>
                                        <p className="text-xs text-gray-500">{selectedConversation.isOnline ? 'Active now' : 'Last seen ' + selectedConversation.lastSeen}</p>
                                    </div>
                                </div>
                                <div className="flex space-x-1">
                                    <IconButton><svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" /></svg></IconButton>
                                    <IconButton><svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" /></svg></IconButton>
                                    <IconButton><svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z" /></svg></IconButton>
                                </div>
                            </div>
                        </div>
                        
                        {/* Messages Body */}
                        <div className="flex-1 p-4 overflow-y-auto bg-gray-50">
                            {loadingMessages ? (
                                // Loading State (Spinner)
                                <div className="flex items-center justify-center h-full">
                                    <div className="text-center">
                                        <svg className="animate-spin h-8 w-8 text-emerald-600 mb-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                        </svg>
                                        <p className="text-sm text-gray-500">Fetching messages...</p>
                                    </div>
                                </div>
                            ) : messages.length > 0 ? (
                                // Message Bubbles
                                <div className="space-y-4">
                                    {messages.map((msg, index) => (
                                        <Fragment key={msg.id}>
                                            {/* Time/Date Separator (Optional: Add logic here for grouping by date) */}
                                            
                                            <div className={`flex ${msg.from === 'You' ? 'justify-end' : 'justify-start'}`}>
                                                <div className={`max-w-xs sm:max-w-md lg:max-w-lg ${msg.from !== 'You' ? 'flex items-end' : ''}`}>
                                                    {msg.from !== 'You' && (
                                                        <div className="flex-shrink-0 mr-2">
                                                            <ConversationAvatar user={msg.from} size="8" isOnline={true} showBadge={false} />
                                                        </div>
                                                    )}
                                                    
                                                    <div>
                                                        {index === 0 || messages[index - 1].from !== msg.from ? (
                                                            <p className={`text-xs text-gray-500 mb-1 ${msg.from === 'You' ? 'text-right' : 'text-left'}`}>
                                                                {msg.from}
                                                            </p>
                                                        ) : null}
                                                        
                                                        <div
                                                            className={`px-4 py-2 rounded-xl shadow-md transition-all duration-300 ${
                                                                msg.from === 'You' 
                                                                    ? 'bg-gradient-to-br from-emerald-500 to-teal-600 text-white rounded-br-none' 
                                                                    : 'bg-white text-gray-800 rounded-tl-none border border-gray-200'
                                                            }`}
                                                        >
                                                            <p className="text-sm break-words whitespace-pre-wrap">{msg.text}</p>
                                                        </div>
                                                        
                                                        <div className={`flex items-center mt-1 ${msg.from === 'You' ? 'justify-end' : 'justify-start'}`}>
                                                            <p className="text-xs text-gray-500 mr-1">{msg.timestamp}</p>
                                                            {msg.from === 'You' && (
                                                                <svg className="h-3 w-3 text-emerald-500" fill="currentColor" viewBox="0 0 20 20">
                                                                    <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                                                                </svg>
                                                            )}
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </Fragment>
                                    ))}
                                    {/* Typing Indicator */}
                                    {isTyping && (
                                        <div className="flex justify-start items-center">
                                            <div className="flex-shrink-0 mr-2">
                                                <ConversationAvatar user={selectedConversation.with} size="8" isOnline={true} showBadge={false} />
                                            </div>
                                            <div className="bg-white text-gray-800 rounded-xl rounded-tl-none border border-gray-200 px-4 py-2 shadow-sm">
                                                <div className="flex space-x-1 items-center">
                                                    <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{animationDelay: '0ms'}}></div>
                                                    <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{animationDelay: '150ms'}}></div>
                                                    <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{animationDelay: '300ms'}}></div>
                                                </div>
                                            </div>
                                        </div>
                                    )}
                                    <div ref={messagesEndRef} />
                                </div>
                            ) : (
                                // Empty Chat State
                                <div className="flex flex-col items-center justify-center h-full text-center p-6">
                                    <div className="w-20 h-20 bg-gradient-to-br from-emerald-100 to-teal-100 rounded-full flex items-center justify-center mb-4">
                                        <svg className="h-10 w-10 text-emerald-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
                                        </svg>
                                    </div>
                                    <h3 className="text-lg font-semibold text-gray-900 mb-2">Say Hello to {selectedConversation.with}!</h3>
                                    <p className="text-gray-500 max-w-sm">Start the conversation with a friendly greeting or question.</p>
                                </div>
                            )}
                        </div>
                        
                        {/* Message Input Area */}
                        <div className="p-4 bg-white border-t border-gray-200 relative">
                            
                            {/* Attachments Overlay */}
                            {showAttachments && (
                                <div className="absolute bottom-full mb-2 left-0 right-0 md:left-4 md:right-auto md:w-80 bg-white rounded-xl shadow-2xl p-4 border border-gray-200 z-30 transform origin-bottom">
                                    <div className="grid grid-cols-3 gap-4">
                                        {[
                                            { name: 'Photo', icon: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" /> },
                                            { name: 'Audio', icon: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19V6l12-3v13M9 19c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zm12-3c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zM9 10l12-3" /> },
                                            { name: 'Document', icon: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /> },
                                        ].map((item, index) => (
                                            <button key={index} className="flex flex-col items-center p-3 hover:bg-gray-50 rounded-lg transition-colors border border-transparent hover:border-emerald-300">
                                                <div className="w-10 h-10 bg-emerald-100 rounded-full flex items-center justify-center mb-1">
                                                    <svg className="h-5 w-5 text-emerald-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">{item.icon}</svg>
                                                </div>
                                                <span className="text-xs text-gray-600">{item.name}</span>
                                            </button>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {/* Emoji Picker Overlay */}
                            {showEmojiPicker && (
                                <EmojiPicker 
                                    emojis={emojis} 
                                    onSelect={handleEmojiSelect}
                                    onClose={() => setShowEmojiPicker(false)} 
                                />
                            )}
                            
                            {/* Input Bar */}
                            <div className="flex items-end space-x-2">
                                <IconButton onClick={handleToggleAttachments}>
                                    <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" /></svg>
                                </IconButton>
                                <IconButton onClick={handleToggleEmojiPicker}>
                                    <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                                </IconButton>
                                <div className="flex-1">
                                    <textarea
                                        ref={inputRef}
                                        rows={1}
                                        placeholder="Type a message..."
                                        className="block w-full border border-gray-300 rounded-full py-2.5 px-4 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-transparent resize-none transition duration-150 shadow-sm"
                                        value={messageInput}
                                        onChange={(e) => {
                                            setMessageInput(e.target.value);
                                            // Auto-resize textarea logic (simple implementation)
                                            if (inputRef.current) {
                                                inputRef.current.style.height = 'auto';
                                                inputRef.current.style.height = inputRef.current.scrollHeight + 'px';
                                            }
                                        }}
                                        onKeyPress={handleKeyPress}
                                        // Reset height when cleared
                                        onBlur={() => {
                                            if (inputRef.current && messageInput === '') {
                                                inputRef.current.style.height = 'auto';
                                            }
                                        }}
                                        style={{ minHeight: '44px', maxHeight: '100px' }} // Set min/max height for textarea
                                    />
                                </div>
                                <button
                                    className="p-3 rounded-full bg-gradient-to-r from-emerald-500 to-teal-600 text-white hover:from-emerald-600 hover:to-teal-700 focus:outline-none focus:ring-4 focus:ring-emerald-300 transition-all duration-200 transform hover:scale-105 shadow-lg"
                                    onClick={sendMessage}
                                >
                                    <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
                                    </svg>
                                </button>
                            </div>
                        </div>
                    </div>
                ) : (
                    /* Desktop/Initial Empty State */
                    <div className={`${!showMobileConversation ? 'flex md:flex' : 'hidden'} w-full md:w-2/3 lg:w-3/4 flex-col bg-gray-50 items-center justify-center`}>
                         <div className="text-center p-6">
                            <div className="w-24 h-24 bg-gradient-to-br from-emerald-100 to-teal-100 rounded-full flex items-center justify-center mb-4 mx-auto shadow-inner">
                                <svg className="h-12 w-12 text-emerald-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                                </svg>
                            </div>
                            <h3 className="text-xl font-semibold text-gray-900 mb-2">Welcome to Your Inbox</h3>
                            <p className="text-gray-500 mb-6 max-w-sm">Select a conversation from the list to view messages and start chatting.</p>
                            {conversations.length === 0 && (
                                <button className="px-5 py-2.5 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors shadow-lg">
                                    Start a New Conversation
                                </button>
                            )}
                        </div>
                    </div>
                )}
            </div>
        </AdminLayout>
    );
}