import React, { useState, useRef, useEffect } from "react";
import ReactMarkdown from 'react-markdown';

function Message({ message }) {
  const isUser = message.role === "user";
  
  const renderers = {
    h1: ({ node, ...props }) => <h1 className="text-base font-semibold mb-2" {...props} />,
    h2: ({ node, ...props }) => <h2 className="text-base font-semibold mb-2" {...props} />,
    h3: ({ node, ...props }) => <h3 className="text-base font-semibold mb-2" {...props} />,
    h4: ({ node, ...props }) => <h4 className="text-base font-semibold mb-1" {...props} />,
    h5: ({ node, ...props }) => <h5 className="text-base font-semibold mb-1" {...props} />,
    h6: ({ node, ...props }) => <h6 className="text-base font-semibold mb-1" {...props} />,
    p: ({ node, ...props }) => <p className="text-base mb-2 last:mb-0" {...props} />,
    li: ({ node, ...props }) => <li className="text-base ml-4" {...props} />,
    ul: ({ node, ...props }) => <ul className="list-disc mb-2 ml-4" {...props} />,
    ol: ({ node, ...props }) => <ol className="list-decimal mb-2 ml-4" {...props} />,
    strong: ({ node, ...props }) => <strong className="font-semibold" {...props} />,
    em: ({ node, ...props }) => <em className="italic" {...props} />,
    code: ({ node, inline, ...props }) => 
      inline ? (
        <code className="bg-opacity-20 bg-black px-1 py-0.5 rounded text-sm" {...props} />
      ) : (
        <code className="block bg-opacity-20 bg-black px-3 py-2 rounded text-sm my-2 overflow-x-auto" {...props} />
      ),
  };

  return (
    <div className={`flex ${isUser ? "justify-end" : "justify-start"} mb-3`}>
      <div
        className={`rounded-2xl px-4 py-2 max-w-[70%] text-base shadow-sm font-inter ${
          isUser
            ? "bg-blue-600 text-white rounded-br-md"
            : "bg-gray-100 text-blue-900 border border-blue-100 rounded-bl-md"
        }`}
      >
        {/* Only apply ReactMarkdown if message is not streaming */}
        {message.isStreaming ? (
          <div className="whitespace-pre-wrap">{message.content}</div>
        ) : (
          <ReactMarkdown key={message.completedAt || message.timestamp} components={renderers}>
            {message.content}
          </ReactMarkdown>
        )}
      </div>
    </div>
  );
}

const STARTER_QUESTIONS = [
  "What are the key government services available to citizens?",
  "How do I apply for a national ID in Uganda?",
  "What is the process for reporting corruption?",
  "How can I access public health services?",
  "What are the requirements for starting a business in Uganda?",
  "How do I contact my local government office?",
  "What are the steps to file a complaint about a public service?",
  "How do I check the status of my application?",
  "Where can I find information about government tenders?"
];

export default function Chatbot({ showNavbar, setShowNavbar }) {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const [sessions, setSessions] = useState([]);
  const [activeSession, setActiveSession] = useState(null);
  const [query, setQuery] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [language, setLanguage] = useState('English');
  const [showConfirmDelete, setShowConfirmDelete] = useState(false);
  const [sessionToDelete, setSessionToDelete] = useState(null);
  const messagesEndRef = useRef(null);
  const storedUser = JSON.parse(localStorage.getItem("user"));
  const usernameOrEmail = storedUser?.username || storedUser?.email || "Guest";
  
  const languageMap = {
    'English': 'eng', 
    'Luganda': 'lug',
    'Iteso': 'teo',
    'Runyankole': 'nyn',
    'Acholi': 'ach',
  };
  
  const API_URL = `${import.meta.env.VITE_APP_API_BASE_URL}/feedback`;
  const getAuthToken = () => localStorage.getItem('accessToken');

  // Derived state - messages come from activeSession only
  const messages = activeSession?.messages || [];

  // Fetch all chat sessions on mount
  useEffect(() => {
    const fetchSessions = async () => {
      const token = getAuthToken();
      if (!token) return;
      
      try {
        const response = await fetch(`${API_URL}/sessions/`, {
          headers: { 'Authorization': `Bearer ${token}` },
        });
        
        if (!response.ok) throw new Error('Failed to fetch sessions');
        
        const data = await response.json();
        // Ensure all sessions have messages array
        const safeSessions = data.map(s => ({ ...s, messages: s.messages || [] }));
        // Sort with pinned at top
        const sortedSessions = safeSessions.sort((a, b) => (b.is_pinned ? 1 : 0) - (a.is_pinned ? 1 : 0));
        setSessions(sortedSessions);
      } catch (error) {
        console.error('Error fetching sessions:', error);
      }
    };
    
    fetchSessions();
  }, []);

  // Handle screen size changes
  useEffect(() => {
    const checkScreenSize = () => {
      const mobile = window.innerWidth < 768;
      setIsMobile(mobile);
      if (mobile) {
        setSidebarOpen(false);
      }
    };

    checkScreenSize();
    window.addEventListener('resize', checkScreenSize);
    return () => window.removeEventListener('resize', checkScreenSize);
  }, []);

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

  // Create new chat session
  const handleNewChat = async () => {
    setIsLoading(true);
    
    try {
      const token = getAuthToken();
      const response = await fetch(`${API_URL}/sessions/`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({}),
      });
  
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.error || 'Failed to create new session');
      }
  
      const newSession = await response.json();
      const safeSession = { 
        ...newSession, 
        messages: newSession.messages || [],
        display_title: 'New Chat'
      };
  
      // Add to sessions list at the top
      setSessions(prev => [safeSession, ...prev]);
      // Set as active session
      setActiveSession(safeSession);
      // Clear input
      setQuery("");
      // Close sidebar on mobile
      if (isMobile) {
        setSidebarOpen(false);
      }
      
      return safeSession;
    } catch (error) {
      console.error('Error creating new chat:', error);
      alert('Failed to create new chat. Please try again.');
      return null;
    } finally {
      setIsLoading(false);
    }
  };

  // Load a specific chat session
  const handleChatSelect = async (session) => {
    try {
      const token = getAuthToken();
      const response = await fetch(`${API_URL}/sessions/${session.id}/`, {
        headers: { 'Authorization': `Bearer ${token}` },
      });
  
      if (!response.ok) throw new Error("Failed to fetch chat history");
  
      const fullSession = await response.json();
      const safeSession = { 
        ...fullSession, 
        messages: (fullSession.messages || []).map(msg => ({
          ...msg,
          isStreaming: false  // Ensure loaded messages are marked as not streaming
        }))
      };
  
      setActiveSession(safeSession);
      
      // Close sidebar on mobile
      if (isMobile) {
        setSidebarOpen(false);
      }
    } catch (err) {
      console.error("Error loading chat:", err);
      alert('Failed to load chat history. Please try again.');
    }
  };

  // Delete a chat session
  const handleDeleteChat = async (sessionId, e) => {
    e.stopPropagation();
    
    // Show custom confirmation modal
    setSessionToDelete(sessionId);
    setShowConfirmDelete(true);
  };

  // Confirm delete action
  const confirmDelete = async () => {
    if (!sessionToDelete) return;

    try {
      const token = getAuthToken();
      const response = await fetch(`${API_URL}/sessions/${sessionToDelete}/`, {
        method: 'DELETE',
        headers: { 'Authorization': `Bearer ${token}` },
      });
      
      if (!response.ok) throw new Error('Failed to delete chat');
  
      // Remove from sessions list
      setSessions(prev => prev.filter(s => s.id !== sessionToDelete));
  
      // If deleted chat was active, clear it
      if (activeSession?.id === sessionToDelete) {
        setActiveSession(null);
      }
    } catch (error) {
      console.error('Error deleting chat:', error);
      alert('Failed to delete chat. Please try again.');
    } finally {
      setShowConfirmDelete(false);
      setSessionToDelete(null);
    }
  };

  // Cancel delete
  const cancelDelete = () => {
    setShowConfirmDelete(false);
    setSessionToDelete(null);
  };

  // Send a message
  const handleSendMessage = async (e, text) => {
    if (e) e.preventDefault();
    const content = text || query;
  
    if (!content.trim() || isLoading) return;
  
    // Ensure we have an active session
    let currentSession = activeSession;
    if (!currentSession) {
      currentSession = await handleNewChat();
      if (!currentSession) {
        alert("Failed to start a new chat. Please try again.");
        return;
      }
    }
  
    // Clear input immediately
    setQuery('');
    setIsLoading(true);
  
    const userMessage = { 
      role: 'user', 
      content, 
      timestamp: new Date().toISOString(),
      isStreaming: false
    };
    
    // Optimistically add user message
    const updatedMessages = [...currentSession.messages, userMessage];
    setActiveSession(prev => ({ ...prev, messages: updatedMessages }));
  
    // Add placeholder for bot message with unique ID
    const botMessageId = `bot-${Date.now()}`;
    const isNonEnglish = language !== 'English';
    
    const botPlaceholder = { 
      id: botMessageId, 
      role: 'bot', 
      content: isNonEnglish ? '.....' : '', 
      timestamp: new Date().toISOString(),
      isStreaming: !isNonEnglish  // Only stream for English
    };
    setActiveSession(prev => ({ 
      ...prev, 
      messages: [...prev.messages, botPlaceholder] 
    }));
  
    try {
      const token = getAuthToken();
      const payload = {
        session_id: currentSession.id,
        query: content,
        language: languageMap[language],
      };
  
      const response = await fetch(`${API_URL}/chat/`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload),
      });
  
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to get response from bot');
      }
  
      let accumulatedContent = '';
  
      // For non-English, wait for complete response (no streaming)
      if (isNonEnglish) {
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
  
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
  
          const chunk = decoder.decode(value);
          const lines = chunk.split('\n');
          
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const data = line.slice(6); 
              
              if (data === '[END]') {
                break;
              } else if (data.startsWith('[ERROR]')) {
                accumulatedContent = data;
                break;
              } else if (data.trim()) {
                accumulatedContent += data;
              }
            }
          }
        }
  
        // Only display the final translated content
        const finalBotMessage = { 
          id: botMessageId,
          role: 'bot', 
          content: accumulatedContent, 
          timestamp: new Date().toISOString(),
          isStreaming: false , // Not streaming, apply markdown
          completedAt: Date.now()  
        };
        
        setActiveSession(prev => ({
          ...prev,
          messages: prev.messages.map(msg => 
            msg.id === botMessageId ? finalBotMessage : msg
          )
        }));
  
      } else {
        // For English, stream the response
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
  
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
  
          const chunk = decoder.decode(value);
          const lines = chunk.split('\n');
          
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const data = line.slice(6); 
              
              if (data === '[END]') {
                // Mark streaming as complete
                setActiveSession(prev => ({
                  ...prev,
                  messages: prev.messages.map(msg => 
                    msg.id === botMessageId 
                      ? { ...msg, isStreaming: false,completedAt: Date.now() }
                      : msg
                  )
                }));
                break;
              } else if (data.startsWith('[ERROR]')) {
                accumulatedContent = data;
                setActiveSession(prev => ({
                  ...prev,
                  messages: prev.messages.map(msg => 
                    msg.id === botMessageId 
                      ? { ...msg, content: data, isError: true, isStreaming: false }
                      : msg
                  )
                }));
                return;
              } else if (data.trim()) {
                accumulatedContent += data;
                setActiveSession(prev => ({
                  ...prev,
                  messages: prev.messages.map(msg => 
                    msg.id === botMessageId 
                      ? { ...msg, content: accumulatedContent, isStreaming: true }
                      : msg
                  )
                }));
              }
            }
          }
        }
      }
  
      // Update the session in the sessions list
      const finalMessages = [
        ...currentSession.messages, 
        userMessage, 
        { 
          id: botMessageId,
          role: 'bot', 
          content: accumulatedContent, 
          timestamp: new Date().toISOString(),
          isStreaming: false,
          completedAt: Date.now()
        }
      ];
      
      const updatedSession = {
        ...currentSession,
        messages: finalMessages,
        display_title: currentSession.messages.length === 0
          ? content.substring(0, 30) + (content.length > 30 ? "..." : "")
          : currentSession.display_title
      };
      
      setSessions(prevSessions => 
        prevSessions.map(s => 
          s.id === currentSession.id ? updatedSession : s
        )
      );
  
    } catch (error) {
      console.error('Error sending message:', error);
      setActiveSession(prev => ({
        ...prev,
        messages: prev.messages.map(msg => 
          msg.id === botMessageId 
            ? { ...msg, content: `Error: ${error.message}`, isError: true, isStreaming: false }
            : msg
        )
      }));
    } finally {
      setIsLoading(false);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    handleSendMessage(e);
  };

  const showStarter = messages.length === 0 && !isLoading;

  return (
    // CHANGE 1: Added overflow-hidden to root to lock body scroll
    <div className="flex h-screen w-full bg-gray-50 relative overflow-hidden">
      {/* Sidebar - unchanged, already scrollable internally */}
      <div className={`
        bg-white h-full shadow-lg border-r border-blue-100 flex flex-col transition-all duration-300 z-30
        ${isMobile 
          ? `fixed left-0 top-0 w-80 ${sidebarOpen ? 'translate-x-0' : '-translate-x-full'}`
          : `${sidebarOpen ? 'w-64' : 'w-0'} overflow-hidden`
        }
      `}>
        {/* Sidebar Header */}
        <div className="flex items-center justify-between px-4 py-4 border-b border-blue-100 min-w-64">
          <div className="flex items-center gap-2">
            <svg className="w-5 h-5 text-blue-700" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" 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>
            <span className="font-bold text-blue-700 text-lg font-poppins">Chats</span>
          </div>
          <button
            className="p-1.5 rounded hover:bg-blue-50 border border-blue-100"
            style={{ width: 32, height: 32 }}
            onClick={() => setSidebarOpen(false)}
            aria-label="Close sidebar"
          >
            <svg className="w-5 h-5 text-blue-700" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        {/* New Chat Button */}
        <div className="p-4 border-b border-blue-50 min-w-64">
          <button 
            onClick={handleNewChat}
            disabled={isLoading}
            className="w-full flex items-center gap-2 px-4 py-3 rounded-lg bg-blue-600 text-white font-semibold hover:bg-blue-700 transition duration-200 shadow-sm disabled:opacity-50"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" />
            </svg>
            <span>New Chat</span>
          </button>
        </div>

        {/* Chat History */}
        <div className="flex-1 overflow-y-auto min-w-64">
          <div className="px-2 py-2">
            <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wide px-3 py-2">Recent Chats</h3>
            <div className="space-y-1">
              {sessions.length > 0 ? (
                sessions.map((session) => (
                  <div
                    key={session.id}
                    onClick={() => handleChatSelect(session)}
                    className={`group relative p-3 rounded-lg cursor-pointer transition duration-200 mx-1 ${
                      activeSession?.id === session.id
                        ? 'bg-blue-50 border border-blue-200' 
                        : 'hover:bg-gray-50 border border-transparent'
                    }`}
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1 min-w-0">
                        <h4 className="font-medium text-gray-900 text-sm truncate">
                          {session.display_title || 'New Chat'}
                        </h4>
                      </div>
                      <button
                        onClick={(e) => handleDeleteChat(session.id, e)}
                        className="opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-red-50 text-gray-400 hover:text-red-500 transition duration-200"
                        aria-label="Delete chat"
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                        </svg>
                      </button>
                    </div>
                  </div>
                ))
              ) : (
                <div className="font-medium text-gray-900 text-sm px-3">No Chats found</div>
              )}
            </div>
          </div>
        </div>

        {/* User Profile Section */}
        <div className="p-4 border-t border-blue-100 min-w-64">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center">
              <svg className="w-5 h-5 text-blue-700" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
              </svg>
            </div>
            <div className="flex-1">
              <p className="text-sm font-medium text-blue-900">{usernameOrEmail ||"Guest User"}</p>
              {/* <p className="text-xs text-gray-500">Free Plan</p> */}
            </div>
            <button className="p-1 rounded hover:bg-blue-50 text-gray-400 hover:text-blue-600 transition duration-200">
              <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
              </svg>
            </button>
          </div>
        </div>
      </div>

      {/* Main content area - CHANGE 2: Added overflow-hidden to enforce internal scrolling */}
      <div className="flex-1 flex flex-col h-full min-w-0 overflow-hidden">
        {/* Top bar */}
        <div className="flex items-center px-3 md:px-4 py-3 bg-white border-b border-gray-200 z-10 shadow-sm">
          <button
            className="mr-2 md:mr-3 p-1.5 rounded-full hover:bg-blue-50 transition border border-blue-100 flex-shrink-0"
            style={{ width: 34, height: 34 }}
            onClick={() => setSidebarOpen(!sidebarOpen)}
            aria-label="Toggle sidebar"
          >
            <svg className="w-5 h-5 text-blue-700" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M4 6h16M4 12h16M4 18h16" />
            </svg>
          </button>
          <span className="font-bold text-blue-900 text-base md:text-lg lg:text-xl font-poppins truncate">RPS Virtual Assistant</span>
          <div className="ml-auto flex items-center gap-1 md:gap-2">
            <select 
              value={language}
              onChange={(e) => setLanguage(e.target.value)}
              className="rounded-lg border border-blue-200 px-2 md:px-3 py-1 text-xs md:text-sm focus:outline-none focus:ring-2 focus:ring-blue-200 bg-blue-50 text-blue-700"
            >
              <option>English</option>
              <option>Luganda</option>
              <option>Iteso</option>
              <option>Acholi</option>
              <option>Runyankole</option>
            </select>
            <button
              className="hidden sm:block ml-1 md:ml-2 px-2 md:px-3 py-1.5 rounded-lg hover:bg-blue-100 transition border border-blue-100 text-xs md:text-sm font-medium text-blue-700"
              onClick={() => setShowNavbar(!showNavbar)}
              aria-label={showNavbar ? "Close menu" : "Open menu"}
            >
              {showNavbar ? "Close" : "Menu"}
            </button>
          </div>
        </div>

        {/* Chat area - CHANGE 3: Added overflow-hidden to wrapper, and min-h-0 to inner scrollable div */}
        <div className="flex-1 flex flex-col h-full relative overflow-hidden">
          <div className="flex-1 flex flex-col items-center min-h-0 overflow-y-auto px-2 md:px-4 py-4 md:py-8 bg-gray-50 w-full">
            {showStarter ? (
              <div className="flex flex-col items-center justify-center h-full gap-3 md:gap-4 w-full max-w-4xl mx-auto">
                <div className="text-center mb-2 md:mb-4 px-2">
                  <h2 className="text-lg md:text-xl lg:text-2xl font-bold text-blue-900 mb-2 font-poppins">Welcome to the RPS Virtual Assistant</h2>
                  <p className="text-blue-700 text-sm md:text-base">What do you want to know?</p>
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2 w-full mb-4 md:mb-8">
                  {STARTER_QUESTIONS.map((q, i) => (
                    <button
                      key={i}
                      className="bg-white border border-blue-100 rounded-lg px-3 py-2 md:py-3 text-left shadow hover:shadow-md hover:bg-blue-50 transition text-blue-900 text-xs md:text-sm font-inter"
                      onClick={() => handleSendMessage(null, q)}
                      disabled={isLoading}
                    >
                      {q}
                    </button>
                  ))}
                </div>
                <div className="w-full max-w-2xl flex items-center gap-2 bg-white border border-gray-200 rounded-full px-3 md:px-4 py-2 md:py-3 shadow-sm">
                  <input
                    className="flex-1 bg-transparent text-sm md:text-base focus:outline-none placeholder-gray-500"
                    type="text"
                    placeholder="Type your message..."
                    value={query}
                    onChange={(e) => setQuery(e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && handleSendMessage(e)}
                    disabled={isLoading}
                  />
                  <button
                    onClick={(e) => handleSendMessage(e)}
                    className="bg-blue-600 hover:bg-blue-700 text-white rounded-full p-2 transition disabled:opacity-50 flex-shrink-0"
                    disabled={isLoading || !query.trim()}
                    aria-label="Send message"
                  >
                    <svg className="w-4 md:w-5 h-4 md:h-5 transform rotate-90" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
                    </svg>
                  </button>
                </div>
              </div>
            ) : (
              <>
                <div className="w-full max-w-xs sm:max-w-sm md:max-w-2xl lg:max-w-4xl xl:max-w-6xl mx-auto px-1 md:px-2">
                  {messages.map((msg, idx) => <Message key={`${msg.id || idx}-${msg.isStreaming ? 'stream' : 'done'}`} message={msg} />)}
                  {isLoading && (
                    <div className="flex justify-start mb-3">
                      <div className="rounded-2xl px-3 md:px-4 py-2 bg-gray-100 text-blue-400 border border-blue-100 max-w-[70%] animate-pulse text-sm md:text-base">Typing...</div>
                    </div>
                  )}
                  <div ref={messagesEndRef} />
                </div>
              </>
            )}
          </div>

          {!showStarter && (
            <div
              className="sticky bottom-0 w-full max-w-6xl mx-auto flex items-center gap-2 bg-white border-t border-gray-200 px-3 md:px-4 py-2 md:py-3 z-20"
              style={{ boxShadow: "0 -2px 12px 0 rgba(30, 64, 175, 0.04)" }}
            >
              <input
                className="flex-1 rounded-full border border-blue-200 px-3 md:px-4 py-2 text-sm md:text-base focus:outline-none focus:ring-2 focus:ring-blue-200 transition"
                type="text"
                placeholder="Type your message..."
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                onKeyPress={(e) => e.key === 'Enter' && handleSendMessage(e)}
                disabled={isLoading}
              />
              <button
                onClick={(e) => handleSendMessage(e)}
                className="bg-blue-600 hover:bg-blue-700 text-white rounded-full p-2 transition disabled:opacity-50"
                disabled={isLoading || !query.trim()}
                aria-label="Send message"
              >
                <svg className="w-5 h-5 transform rotate-90" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
                </svg>
              </button>
            </div>
          )}
        </div>
      </div>

      {/* Custom Delete Confirmation Modal */}
      {showConfirmDelete && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 backdrop-blur-sm p-4">
          <div className="bg-white rounded-xl shadow-2xl max-w-sm w-full max-h-[90vh] overflow-y-auto border border-gray-200">
            <div className="p-6">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center flex-shrink-0">
                  <svg className="w-5 h-5 text-red-600" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                  </svg>
                </div>
                <h3 className="text-lg font-semibold text-gray-900">Delete Chat?</h3>
              </div>
              <p className="text-sm text-gray-600 mb-6">
                Are you sure you want to delete this chat? This action cannot be undone.
              </p>
              <div className="flex gap-3 justify-end">
                <button
                  onClick={cancelDelete}
                  className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition duration-200"
                >
                  Cancel
                </button>
                <button
                  onClick={confirmDelete}
                  className="px-4 py-2 text-sm font-medium text-white bg-red-600 hover:bg-red-700 rounded-lg transition duration-200 flex items-center gap-2"
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                  </svg>
                  Delete
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}