import React, { useState, useEffect, useRef, useCallback } from 'react';
import { MessageSquare, Send, Bot, Sparkles, Minimize2, Loader2, RefreshCw, PhoneOff, AlertTriangle, Building2, Mail, Check } from 'lucide-react';
import { playNotificationSound } from '@/lib/sound';
import { FormattedChatMessage } from '@/Components/FormattedChatMessage';


interface ChatDepartment {
    id: number;
    name: string;
    slug: string;
    description?: string;
    icon?: string;
}

interface ChatMessage {
    id: number;
    sender_type: 'visitor' | 'admin';
    sender_name: string;
    message: string;
    created_at: string;
}

export function LiveChatWidget() {
    const [isOpen, setIsOpen] = useState(false);
    const [sessionToken, setSessionToken] = useState<string | null>(null);
    const [visitorName, setVisitorName] = useState('');
    const [visitorEmail, setVisitorEmail] = useState('');
    const [selectedDepartmentId, setSelectedDepartmentId] = useState<number | ''>('');
    const [departments, setDepartments] = useState<ChatDepartment[]>([]);
    const [activeDepartment, setActiveDepartment] = useState<ChatDepartment | null>(null);
    const [initialMessage, setInitialMessage] = useState('');
    const [messages, setMessages] = useState<ChatMessage[]>([]);
    const [newMessage, setNewMessage] = useState('');
    const [isStarted, setIsStarted] = useState(false);
    const [loading, setLoading] = useState(false);
    const [restoring, setRestoring] = useState(false);
    const [status, setStatus] = useState<string>('active');
    const [confirmClose, setConfirmClose] = useState(false);
    const [closing, setClosing] = useState(false);

    const [sendingTranscript, setSendingTranscript] = useState(false);
    const [transcriptSent, setTranscriptSent] = useState(false);
    const [adminTyping, setAdminTyping] = useState<{ is_typing: boolean; name: string } | null>(null);
    const [isAiThinking, setIsAiThinking] = useState(false);

    const messagesEndRef = useRef<HTMLDivElement>(null);
    const prevMessagesCount = useRef<number>(0);
    const lastTypingSent = useRef<number>(0);


    /**
     * Fetch active departments for visitor selection
     */
    useEffect(() => {
        const fetchDepts = async () => {
            try {
                const res = await fetch('/api/chat/departments', {
                    headers: { Accept: 'application/json' },
                });
                const data = await res.json();
                if (data.success && Array.isArray(data.departments)) {
                    setDepartments(data.departments);
                    if (data.departments.length > 0) {
                        setSelectedDepartmentId(data.departments[0].id);
                    }
                }
            } catch (e) {
                // Ignore
            }
        };
        fetchDepts();
    }, []);

    /**
     * On mount: try to restore an existing session from localStorage.
     */
    useEffect(() => {
        const savedToken = localStorage.getItem('techinsoul_chat_token');
        const savedName = localStorage.getItem('techinsoul_chat_name');
        const savedEmail = localStorage.getItem('techinsoul_chat_email');

        if (savedToken && savedName && savedEmail) {
            setVisitorName(savedName);
            setVisitorEmail(savedEmail);
            setRestoring(true);
            restoreSession(savedToken, savedName, savedEmail);
        }
    }, []);

    const restoreSession = async (token: string, name: string, email: string) => {
        try {
            const res = await fetch(`/api/chat/messages?session_token=${encodeURIComponent(token)}`, {
                headers: { Accept: 'application/json' },
            });
            const data = await res.json();

            if (data.success) {
                const msgs: ChatMessage[] = data.messages || [];
                prevMessagesCount.current = msgs.length;
                setMessages(msgs);
                setStatus(data.status || 'active');
                setActiveDepartment(data.department || null);
                setSessionToken(token);
                setVisitorName(name);
                setVisitorEmail(email);
                setIsStarted(true);
            } else {
                clearStoredSession();
            }
        } catch {
            clearStoredSession();
        } finally {
            setRestoring(false);
        }
    };

    // Polling every 3 seconds when chat is open and session is active
    useEffect(() => {
        if (!isOpen || !sessionToken || status === 'closed') return;

        const interval = setInterval(() => {
            fetchMessages(sessionToken);
        }, 3000);

        return () => clearInterval(interval);
    }, [isOpen, sessionToken, status]);

    useEffect(() => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [messages]);

    const fetchMessages = async (token: string) => {
        try {
            const res = await fetch(`/api/chat/messages?session_token=${encodeURIComponent(token)}`, {
                headers: { Accept: 'application/json' },
            });
            const data = await res.json();
            if (data.success) {
                const newMsgs: ChatMessage[] = data.messages || [];

                if (newMsgs.length > prevMessagesCount.current) {
                    const lastMsg = newMsgs[newMsgs.length - 1];
                    if (lastMsg && lastMsg.sender_type === 'admin' && prevMessagesCount.current > 0) {
                        playNotificationSound();
                    }
                }

                prevMessagesCount.current = newMsgs.length;
                setMessages(newMsgs);
                setStatus(data.status || 'active');
                if (data.department) {
                    setActiveDepartment(data.department);
                }

                // Update admin typing state
                if (data.admin_typing?.is_typing) {
                    setAdminTyping(data.admin_typing);
                } else {
                    setAdminTyping(null);
                }
            }
        } catch (err) {
            console.error('Failed to fetch chat messages', err);
        }
    };

    const handleVisitorTyping = (text: string) => {
        setNewMessage(text);
        if (!sessionToken || status === 'closed') return;

        const now = Date.now();
        if (now - lastTypingSent.current > 2000) {
            lastTypingSent.current = now;
            fetch('/api/chat/typing', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                },
                body: JSON.stringify({ session_token: sessionToken }),
            }).catch(() => {});
        }
    };


    const handleStartChat = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!visitorName.trim() || !visitorEmail.trim()) return;

        setLoading(true);
        try {
            const res = await fetch('/api/chat/start', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                },
                body: JSON.stringify({
                    visitor_name: visitorName,
                    visitor_email: visitorEmail,
                    department_id: selectedDepartmentId || undefined,
                    initial_message: initialMessage,
                }),
            });
            const data = await res.json();
            if (data.success) {
                const msgs: ChatMessage[] = data.messages || [];
                prevMessagesCount.current = msgs.length;
                setSessionToken(data.session_token);
                setIsStarted(true);
                setMessages(msgs);
                setStatus('active');
                setActiveDepartment(data.session?.department || null);
                localStorage.setItem('techinsoul_chat_token', data.session_token);
                localStorage.setItem('techinsoul_chat_name', visitorName);
                localStorage.setItem('techinsoul_chat_email', visitorEmail);
                setInitialMessage('');
            }
        } catch (err) {
            console.error('Error starting live chat', err);
        } finally {
            setLoading(false);
        }
    };

    const handleSendMessage = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!newMessage.trim() || !sessionToken) return;

        const text = newMessage.trim();
        setNewMessage('');

        const tempMsg: ChatMessage = {
            id: Date.now(),
            sender_type: 'visitor',
            sender_name: visitorName,
            message: text,
            created_at: new Date().toISOString(),
        };
        setMessages((prev) => [...prev, tempMsg]);
        setIsAiThinking(true);

        try {
            const res = await fetch('/api/chat/send', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                },
                body: JSON.stringify({ session_token: sessionToken, message: text }),
            });
            const data = await res.json();
            if (data.status === 'closed') {
                setStatus('closed');
            }
            if (data.ai_message) {
                setMessages((prev) => {
                    const withoutDuplicate = prev.filter((m) => m.id !== data.ai_message.id);
                    return [...withoutDuplicate, data.ai_message];
                });
            }
            fetchMessages(sessionToken);
        } catch (err) {
            console.error('Failed to send message', err);
        } finally {
            setIsAiThinking(false);
        }
    };


    const clearStoredSession = () => {
        localStorage.removeItem('techinsoul_chat_token');
        localStorage.removeItem('techinsoul_chat_name');
        localStorage.removeItem('techinsoul_chat_email');
        setSessionToken(null);
        setIsStarted(false);
        setMessages([]);
        setStatus('active');
        setActiveDepartment(null);
        setTranscriptSent(false);
        prevMessagesCount.current = 0;
    };

    const handleStartNewConversation = () => {
        clearStoredSession();
    };

    const handleCloseChat = async () => {
        if (!sessionToken || closing) return;
        setClosing(true);
        try {
            await fetch('/api/chat/close', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                },
                body: JSON.stringify({ session_token: sessionToken }),
            });
            setStatus('closed');
            setConfirmClose(false);
            localStorage.removeItem('techinsoul_chat_token');
            localStorage.removeItem('techinsoul_chat_name');
            localStorage.removeItem('techinsoul_chat_email');
        } catch (err) {
            console.error('Failed to close chat', err);
        } finally {
            setClosing(false);
        }
    };

    const handleRequestTranscript = async () => {
        if (!sessionToken || sendingTranscript) return;
        setSendingTranscript(true);
        try {
            const res = await fetch('/api/chat/send-transcript', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                },
                body: JSON.stringify({ session_token: sessionToken }),
            });
            const data = await res.json();
            if (data.success) {
                setTranscriptSent(true);
                setTimeout(() => setTranscriptSent(false), 5000);
            }
        } catch (e) {
            console.error('Failed to request transcript email', e);
        } finally {
            setSendingTranscript(false);
        }
    };

    return (
        <div className={isOpen ? "fixed inset-x-3 bottom-3 sm:inset-x-auto sm:bottom-6 sm:right-6 z-50 font-sans flex justify-center sm:block" : "fixed bottom-5 right-5 sm:bottom-6 sm:right-6 z-50 font-sans"}>
            {/* Chat Trigger Button */}
            {!isOpen && (
                <button
                    onClick={() => setIsOpen(true)}
                    className="group flex items-center gap-3 bg-gradient-to-r from-[#00F2FE] to-[#4FACFE] text-[#060B18] px-5 py-3.5 rounded-full font-bold shadow-xl shadow-[#00F2FE]/20 hover:scale-105 transition-all duration-300"
                >
                    <MessageSquare className="w-5 h-5 fill-current" />
                    <span className="text-sm font-extrabold tracking-wide">Live Support</span>
                    <span className="relative flex h-2.5 w-2.5">
                        <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                        <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-emerald-500"></span>
                    </span>
                </button>
            )}

            {/* Chat Window */}
            {isOpen && (
                <div className="w-full max-w-[420px] sm:w-[420px] h-[min(580px,calc(100dvh-24px))] sm:h-[550px] bg-[#0B132B] border border-slate-800 rounded-3xl shadow-2xl flex flex-col overflow-hidden animate-in fade-in slide-in-from-bottom-5 duration-300">
                    {/* Header */}
                    <div className="bg-gradient-to-r from-[#0B132B] to-[#1C2541] border-b border-slate-800 px-5 py-3.5 flex items-center justify-between shrink-0">

                        <div className="flex items-center gap-3 min-w-0">
                            <div className="w-10 h-10 rounded-full bg-[#00F2FE]/10 border border-[#00F2FE]/30 flex items-center justify-center text-[#00F2FE] font-bold text-sm shrink-0">
                                TS
                            </div>
                            <div className="min-w-0">
                                <h4 className="text-sm font-bold text-white flex items-center gap-1.5 truncate">
                                    Tech in Soul Support <Sparkles className="w-3.5 h-3.5 text-[#00F2FE] shrink-0" />
                                </h4>
                                <div className="flex items-center gap-2">
                                    <p className="text-[10px] text-emerald-400 flex items-center gap-1">
                                        <span className="w-1.5 h-1.5 rounded-full bg-emerald-400"></span>
                                        Online
                                    </p>
                                    {activeDepartment && (
                                        <span className="text-[10px] text-[#00F2FE] bg-[#00F2FE]/10 border border-[#00F2FE]/20 px-2 py-0.2 rounded-full truncate">
                                            {activeDepartment.name}
                                        </span>
                                    )}
                                </div>
                            </div>
                        </div>
                        <div className="flex items-center gap-1 shrink-0">
                            {isStarted && (
                                <button
                                    onClick={handleRequestTranscript}
                                    disabled={sendingTranscript || transcriptSent}
                                    title={`Send transcript to ${visitorEmail}`}
                                    className="p-1.5 text-[#00F2FE] hover:text-white rounded-lg hover:bg-[#00F2FE]/10 transition-all disabled:opacity-50"
                                >
                                    {sendingTranscript ? (
                                        <Loader2 className="w-4 h-4 animate-spin" />
                                    ) : transcriptSent ? (
                                        <Check className="w-4 h-4 text-emerald-400" />
                                    ) : (
                                        <Mail className="w-4 h-4" />
                                    )}
                                </button>
                            )}

                            {isStarted && status !== 'closed' && (
                                <button
                                    onClick={() => setConfirmClose((v) => !v)}
                                    title="End conversation"
                                    className="p-1.5 text-rose-400 hover:text-rose-300 rounded-lg hover:bg-rose-500/10 transition-all"
                                >
                                    <PhoneOff className="w-4 h-4" />
                                </button>
                            )}
                            <button
                                onClick={() => { setIsOpen(false); setConfirmClose(false); }}
                                className="p-1.5 text-slate-400 hover:text-white rounded-lg hover:bg-slate-800/60 transition-all"
                            >
                                <Minimize2 className="w-4 h-4" />
                            </button>
                        </div>

                        {/* Inline confirm bar */}
                        {confirmClose && (
                            <div className="absolute top-[68px] left-0 right-0 z-20 mx-3 bg-[#0B132B] border border-rose-500/40 rounded-xl px-4 py-3 shadow-xl flex items-center justify-between gap-3">
                                <div className="flex items-center gap-2 text-xs text-slate-300">
                                    <AlertTriangle className="w-4 h-4 text-rose-400 shrink-0" />
                                    End this conversation?
                                </div>
                                <div className="flex items-center gap-2 shrink-0">
                                    <button
                                        onClick={() => setConfirmClose(false)}
                                        className="text-[11px] font-bold text-slate-400 hover:text-white px-3 py-1 rounded-lg hover:bg-slate-800 transition-colors"
                                    >
                                        Cancel
                                    </button>
                                    <button
                                        onClick={handleCloseChat}
                                        disabled={closing}
                                        className="text-[11px] font-bold text-[#060B18] bg-rose-500 hover:bg-rose-400 disabled:opacity-50 px-3 py-1 rounded-lg transition-colors flex items-center gap-1"
                                    >
                                        {closing ? <Loader2 className="w-3 h-3 animate-spin" /> : null}
                                        End Chat
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>

                    {/* Body */}
                    {restoring ? (
                        <div className="flex-grow flex flex-col items-center justify-center gap-3 text-slate-400">
                            <Loader2 className="w-6 h-6 text-[#00F2FE] animate-spin" />
                            <p className="text-xs">Loading your conversation...</p>
                        </div>
                    ) : !isStarted ? (
                        /* Pre-Chat Registration Form */
                        <form onSubmit={handleStartChat} className="flex-grow p-6 flex flex-col justify-center space-y-3.5 overflow-y-auto">
                            <div className="text-center space-y-1 mb-1">
                                <h5 className="text-base font-bold text-white">Connect with Support</h5>
                                <p className="text-xs text-slate-400">Select a department and start a live chat session.</p>
                            </div>

                            <div>
                                <label className="text-[11px] font-bold text-slate-300 uppercase block mb-1">Department / Inquiry Type *</label>
                                <div className="relative">
                                    <select
                                        value={selectedDepartmentId}
                                        onChange={(e) => setSelectedDepartmentId(Number(e.target.value))}
                                        className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                    >
                                        {departments.length > 0 ? (
                                            departments.map((dept) => (
                                                <option key={dept.id} value={dept.id}>
                                                    {dept.name}
                                                </option>
                                            ))
                                        ) : (
                                            <option value="">General Inquiries</option>
                                        )}
                                    </select>
                                </div>
                            </div>

                            <div>
                                <label className="text-[11px] font-bold text-slate-300 uppercase block mb-1">Your Full Name *</label>
                                <input
                                    type="text"
                                    required
                                    value={visitorName}
                                    onChange={(e) => setVisitorName(e.target.value)}
                                    placeholder="e.g. Alex Vance"
                                    className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                />
                            </div>

                            <div>
                                <label className="text-[11px] font-bold text-slate-300 uppercase block mb-1">Work Email Address *</label>
                                <input
                                    type="email"
                                    required
                                    value={visitorEmail}
                                    onChange={(e) => setVisitorEmail(e.target.value)}
                                    placeholder="alex@company.com"
                                    className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                />
                            </div>

                            <div>
                                <label className="text-[11px] font-bold text-slate-300 uppercase block mb-1">Initial Message (Optional)</label>
                                <textarea
                                    rows={2}
                                    value={initialMessage}
                                    onChange={(e) => setInitialMessage(e.target.value)}
                                    placeholder="How can we assist you today?"
                                    className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#00F2FE] resize-none"
                                />
                            </div>

                            <button
                                type="submit"
                                disabled={loading}
                                className="w-full bg-gradient-to-r from-[#00F2FE] to-[#4FACFE] text-[#060B18] font-bold text-xs py-3 rounded-xl shadow-lg shadow-[#00F2FE]/20 hover:opacity-95 transition-all mt-1 flex items-center justify-center gap-2"
                            >
                                {loading ? (
                                    <>
                                        <Loader2 className="w-4 h-4 animate-spin" /> Connecting...
                                    </>
                                ) : (
                                    'Start Live Chat'
                                )}
                            </button>
                        </form>
                    ) : (
                        /* Active / Closed Chat Messages View */
                        <div className="flex-grow flex flex-col justify-between overflow-hidden">
                            <div className="flex-grow p-4 overflow-y-auto space-y-3 scrollbar-thin">
                                <div className="text-center my-1">
                                    <span className="text-[10px] text-slate-400 bg-[#060B18] px-3 py-1 rounded-full border border-slate-800">
                                        Session #{sessionToken?.substring(0, 8)} &bull; {activeDepartment?.name || 'General'}
                                    </span>
                                </div>

                                {messages.length === 0 ? (
                                    <div className="text-center text-slate-400 text-xs py-8 space-y-2">
                                        <Bot className="w-8 h-8 text-[#00F2FE] mx-auto opacity-70" />
                                        <p>Send a message below to start chatting live with our team!</p>
                                    </div>
                                ) : (
                                    messages.map((msg) => {
                                        const isVisitor = msg.sender_type === 'visitor';
                                        const isSystem = msg.sender_name === 'System' || msg.message.startsWith('⚑') || msg.message.startsWith('👋') || msg.message.startsWith('🚪');

                                        if (isSystem) {
                                            return (
                                                <div key={msg.id} className="text-center my-2">
                                                    <span className="text-[10px] text-slate-400 bg-[#060B18]/80 border border-slate-800/80 px-3 py-1 rounded-full inline-block">
                                                        {msg.message}
                                                    </span>
                                                </div>
                                            );
                                        }

                                        return (
                                            <div key={msg.id} className={`flex flex-col ${isVisitor ? 'items-end' : 'items-start'}`}>
                                                <span className="text-[10px] text-slate-400 mb-0.5 px-1">{msg.sender_name}</span>
                                                <div
                                                    className={`max-w-[85%] px-3.5 py-2.5 rounded-2xl text-xs leading-relaxed ${
                                                        isVisitor
                                                            ? 'bg-gradient-to-r from-[#00F2FE] to-[#4FACFE] text-[#060B18] font-medium rounded-br-none shadow-md shadow-cyan-500/10'
                                                            : 'bg-[#1C2541] text-slate-100 border border-slate-700/50 rounded-bl-none shadow-md shadow-black/20'
                                                    }`}
                                                >
                                                    <FormattedChatMessage content={msg.message} isVisitor={isVisitor} />
                                                </div>

                                                <span className="text-[9px] text-slate-500 mt-0.5 px-1">
                                                    {new Date(msg.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                                                </span>
                                            </div>
                                        );
                                    })
                                )}
                                {isAiThinking && !adminTyping && (
                                    <div className="flex items-center gap-2 px-3.5 py-2 bg-[#1C2541] border border-cyan-500/30 rounded-2xl rounded-bl-none text-xs text-cyan-300 animate-pulse w-fit shadow-md">
                                        <div className="flex gap-1 items-center">
                                            <span className="w-1.5 h-1.5 rounded-full bg-[#00F2FE] animate-bounce" style={{ animationDelay: '0ms' }} />
                                            <span className="w-1.5 h-1.5 rounded-full bg-[#00F2FE] animate-bounce" style={{ animationDelay: '150ms' }} />
                                            <span className="w-1.5 h-1.5 rounded-full bg-[#00F2FE] animate-bounce" style={{ animationDelay: '300ms' }} />
                                        </div>
                                        <span className="text-[11px] font-medium text-slate-200">Tech in Soul AI Assistant is typing...</span>
                                    </div>
                                )}
                                {adminTyping && (
                                    <div className="flex items-center gap-2 px-3.5 py-2 bg-[#1C2541] border border-cyan-500/30 rounded-2xl rounded-bl-none text-xs text-cyan-300 animate-pulse w-fit shadow-md">
                                        <div className="flex gap-1 items-center">
                                            <span className="w-1.5 h-1.5 rounded-full bg-[#00F2FE] animate-bounce" style={{ animationDelay: '0ms' }} />
                                            <span className="w-1.5 h-1.5 rounded-full bg-[#00F2FE] animate-bounce" style={{ animationDelay: '150ms' }} />
                                            <span className="w-1.5 h-1.5 rounded-full bg-[#00F2FE] animate-bounce" style={{ animationDelay: '300ms' }} />
                                        </div>
                                        <span className="text-[11px] font-medium text-slate-200">{adminTyping.name || 'Specialist'} is typing...</span>
                                    </div>
                                )}
                                <div ref={messagesEndRef} />

                            </div>

                            {/* Footer */}
                            {status === 'closed' ? (
                                <div className="p-4 bg-[#060B18] border-t border-slate-800 space-y-2 shrink-0">
                                    <p className="text-xs text-slate-400 text-center">
                                        This chat session has ended (inactivity or resolved).
                                    </p>

                                    <button
                                        onClick={handleRequestTranscript}
                                        disabled={sendingTranscript || transcriptSent}
                                        className="w-full bg-[#1C2541] hover:bg-[#253256] text-slate-200 border border-slate-700 font-semibold text-xs py-2 rounded-xl transition-all flex items-center justify-center gap-1.5 disabled:opacity-50"
                                    >
                                        {sendingTranscript ? (
                                            <>
                                                <Loader2 className="w-3.5 h-3.5 animate-spin" /> Sending to {visitorEmail}...
                                            </>
                                        ) : transcriptSent ? (
                                            <>
                                                <Check className="w-3.5 h-3.5 text-emerald-400" /> Transcript Emailed to {visitorEmail}!
                                            </>
                                        ) : (
                                            <>
                                                <Mail className="w-3.5 h-3.5 text-[#00F2FE]" /> Email Me Chat Transcript
                                            </>
                                        )}
                                    </button>

                                    <button
                                        onClick={handleStartNewConversation}
                                        className="w-full bg-gradient-to-r from-[#00F2FE] to-[#4FACFE] text-[#060B18] font-bold text-xs py-2.5 rounded-xl hover:opacity-90 transition-all flex items-center justify-center gap-2"
                                    >
                                        <RefreshCw className="w-3.5 h-3.5" />
                                        Start a New Conversation
                                    </button>
                                </div>
                            ) : (
                                <form
                                    onSubmit={handleSendMessage}
                                    className="p-3 bg-[#060B18] border-t border-slate-800 flex items-center gap-2 shrink-0"
                                >
                                    <input
                                        type="text"
                                        value={newMessage}
                                        onChange={(e) => handleVisitorTyping(e.target.value)}
                                        placeholder="Type your message..."
                                        className="flex-grow bg-[#0B132B] border border-slate-800 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                    />
                                    <button
                                        type="submit"
                                        disabled={!newMessage.trim()}
                                        className="p-2 bg-gradient-to-r from-[#00F2FE] to-[#4FACFE] text-[#060B18] rounded-xl hover:opacity-90 transition-all disabled:opacity-40 disabled:cursor-not-allowed shadow-md shadow-[#00F2FE]/10"
                                    >
                                        <Send className="w-4 h-4" />
                                    </button>
                                </form>
                            )}
                        </div>
                    )}
                </div>
            )}
        </div>
    );
}


