"use client";

import { useEffect, useRef, useState } from 'react';
import dynamic from 'next/dynamic';
import { ArrowUp, BarChart3, ChevronDown, Database, Menu, MessageCircle, Zap } from 'lucide-react';
import { signOut, useSession } from 'next-auth/react';
import { CollapsedSidebar, HistoryPanel } from '@/components/chat/history-panel';
import { MessageBubbleContent } from '@/components/chat/message-bubble-content';
import { useAutoScroll } from '@/hooks/use-auto-scroll';
import {
  ChatSession,
  Message,
  STORAGE_KEY,
  buildSessionSignature,
  createSessionId,
  deriveTitle,
  sanitizeMessages,
} from '@/lib/chat-session';

const ReactMarkdown = dynamic(() => import('react-markdown'), { ssr: false });
export default function Home() {
  const [input, setInput] = useState('');
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const importInputRef = useRef<HTMLInputElement>(null);
  const [projectId, setProjectId] = useState<string>('');
  const [modelName, setModelName] = useState<string>('');
  const [sessions, setSessions] = useState<ChatSession[]>([]);
  const [activeSessionId, setActiveSessionId] = useState<string | null>(null);
  const [historyQuery, setHistoryQuery] = useState('');
  const [isHistoryOpen, setIsHistoryOpen] = useState(false);
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
  const isLoadingRef = useRef(true); // Track if we're loading from storage
  const messagesRef = useRef<Message[]>([]);
  const lastPersistedSignatureRef = useRef('');
  const { data: session } = useSession();

  useEffect(() => {
    messagesRef.current = messages;
  }, [messages]);
  useAutoScroll(messagesEndRef, messages);

  // Track whether initial load has completed
  const initialLoadDoneRef = useRef(false);

  useEffect(() => {
    isLoadingRef.current = true;
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored) {
        const parsed = JSON.parse(stored) as ChatSession[];
        if (parsed.length > 0) {
          const sorted = [...parsed].sort((a, b) => {
            const pinnedDiff = Number(Boolean(b.pinned)) - Number(Boolean(a.pinned));
            if (pinnedDiff !== 0) return pinnedDiff;
            return b.updatedAt - a.updatedAt;
          });
          setSessions(sorted);
          setActiveSessionId(sorted[0].id);
          const loadedMessages = sorted[0].messages || [];
          setMessages(loadedMessages);
          messagesRef.current = loadedMessages;
          lastPersistedSignatureRef.current = buildSessionSignature(sorted[0].id, loadedMessages);
          // Mark initial load as done after a microtask to ensure React has processed state updates
          queueMicrotask(() => {
            isLoadingRef.current = false;
            initialLoadDoneRef.current = true;
          });
          return;
        }
      }
    } catch (error) {
      console.warn('Failed to read chat history', error);
    }
    setActiveSessionId(createSessionId());
    lastPersistedSignatureRef.current = '';
    isLoadingRef.current = false;
    initialLoadDoneRef.current = true;
  }, []);

  useEffect(() => {
    // Don't save to localStorage during initial load - prevents overwriting history with empty array
    if (!initialLoadDoneRef.current) return;
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(sessions));
    } catch (error) {
      console.warn('Failed to save chat history', error);
    }
  }, [sessions]);

  useEffect(() => {
    // Don't save during initial load or session switching
    if (isLoadingRef.current) return;
    if (!activeSessionId || messages.length === 0) return;

    const nextSignature = buildSessionSignature(activeSessionId, messages);
    if (nextSignature === lastPersistedSignatureRef.current) return;
    lastPersistedSignatureRef.current = nextSignature;
    
    const now = Date.now();
    const title = deriveTitle(messages);
    const cleanMessages = sanitizeMessages(messages);
    setSessions((prev) => {
      const existingIndex = prev.findIndex((entry) => entry.id === activeSessionId);
      if (existingIndex === -1) {
        return [
          {
            id: activeSessionId,
            title,
            createdAt: now,
            updatedAt: now,
            messages: cleanMessages,
            pinned: false,
          },
          ...prev,
        ].sort((a, b) => {
          const pinnedDiff = Number(Boolean(b.pinned)) - Number(Boolean(a.pinned));
          if (pinnedDiff !== 0) return pinnedDiff;
          return b.updatedAt - a.updatedAt;
        });
      }
      const existing = prev[existingIndex];
      const updated = {
        ...existing,
        title,
        updatedAt: now,
        messages: cleanMessages,
      };
      const next = [...prev];
      next.splice(existingIndex, 1);
      return [updated, ...next].sort((a, b) => {
        const pinnedDiff = Number(Boolean(b.pinned)) - Number(Boolean(a.pinned));
        if (pinnedDiff !== 0) return pinnedDiff;
        return b.updatedAt - a.updatedAt;
      });
    });
  }, [messages, activeSessionId]);

  const runDryRunForMessage = async (index: number, sql: string, retryCount = 0) => {
    // Max 3 retries (0, 1, 2)
    if (retryCount > 2) {
      setMessages(prev => prev.map((msg, i) => 
        i === index ? { 
          ...msg, 
          isDryRunning: false, 
          dryRun: { valid: false, error: "Auto-fix failed after 3 attempts." } 
        } : msg
      ));
      return;
    }

    setMessages(prev => prev.map((msg, i) => 
      i === index ? { ...msg, isDryRunning: true } : msg
    ));

    try {
      const res = await fetch('/api/bigquery', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sql, mode: 'dry_run' }),
      });
      const data = await res.json();
      
      if (data.projectId) {
        setProjectId(data.projectId);
      }

      if (data.valid) {
        // Success
        setMessages(prev => prev.map((msg, i) => 
          i === index ? { 
            ...msg, 
            isDryRunning: false, 
            dryRun: data 
          } : msg
        ));
      } else {
        // Failed -> Try Auto-Fix
        console.log(`Dry run failed (Attempt ${retryCount + 1}). Trying auto-fix...`, data.error);
        
        // Construct fix prompt
        const fixPrompt = `The previous SQL failed validation with this error: "${data.error}". 
        
        Original SQL:
        \`\`\`sql
        ${sql}
        \`\`\`
        
        Please correct the SQL query to resolve this error. Return ONLY the full corrected SQL query wrapped in markdown code blocks.`;
        
        // Call Chat API again for fix
        // We need to pass the conversation history context + this fix request
        // To avoid messing up the visible chat history, we'll just send this as a specialized request
        // In a real app you might want to append this exchange to history, but for UI cleanliness we'll do it invisibly
        
        // We need the messages context up to this point
        const currentMessages = messagesRef.current.map(({ role, content }) => ({ role, content }));
        
        const fixResponse = await fetch('/api/chat', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ 
             messages: [
               ...currentMessages, 
               { role: 'user', content: fixPrompt }
             ] 
          }),
        });
        
        const fixData = await fixResponse.json();
        
        if (fixData.sql) {
           // Update the message with new SQL and explanation
           const cleanContent = fixData.content.replace(/```sql[\s\S]*?```/g, "").replace(/```[\s\S]*?```/g, "").trim();
           
           setMessages(prev => prev.map((msg, i) => 
             i === index ? { 
               ...msg, 
               content: msg.content + `\n\n*(Auto-fix Attempt ${retryCount + 1}: SQL updated)*\n\n` + cleanContent,
               sql: fixData.sql 
             } : msg
           ));
           
           // Recursive call for next dry run check
           setTimeout(() => runDryRunForMessage(index, fixData.sql, retryCount + 1), 0);
        } else {
           // No SQL returned in fix attempt
           setMessages(prev => prev.map((msg, i) => 
            i === index ? { 
              ...msg, 
              isDryRunning: false, 
              dryRun: { valid: false, error: data.error + " (Auto-fix failed to generate SQL)" } 
            } : msg
          ));
        }
      }
      
    } catch (e: unknown) {
      const errorMessage = e instanceof Error ? e.message : 'Unknown error';
      setMessages(prev => prev.map((msg, i) => 
        i === index ? { 
          ...msg, 
          isDryRunning: false, 
          dryRun: { valid: false, error: errorMessage } 
        } : msg
      ));
    }
  };

  const handleSuggestionClick = (suggestion: string) => {
    setInput(suggestion);
  };

  const sendQuery = async (queryText: string) => {
    if (!queryText.trim() || loading) return;
    if (!activeSessionId) {
      setActiveSessionId(createSessionId());
    }

    const userMsg: Message = { role: 'user', content: queryText };
    setMessages(prev => [...prev, userMsg]);
    setInput('');
    setLoading(true);

    try {
      const response = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          messages: [...messagesRef.current, userMsg].map(({ role, content }) => ({ role, content })),
        }),
      });

      const data = await response.json();
      if (data.error) throw new Error(data.error);

      if (data.model) {
        setModelName(data.model);
      }

      const cleanContent = data.content.replace(/```sql[\s\S]*?```/g, "").replace(/```[\s\S]*?```/g, "").trim();

      const assistantMsg: Message = {
        role: 'assistant',
        content: cleanContent,
        sql: data.sql,
      };

      setMessages(prev => {
        const newMessages = [...prev, assistantMsg];
        if (data.sql) {
          setTimeout(() => runDryRunForMessage(newMessages.length - 1, data.sql), 0);
        }
        return newMessages;
      });

    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      setMessages(prev => [...prev, { role: 'assistant', content: `Error: ${errorMessage}` }]);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    sendQuery(input);
  };

  const handleExecute = async (index: number, sql: string) => {
    // Set executing state for the specific message
    setMessages(prev => prev.map((msg, i) => 
      i === index ? { ...msg, isExecuting: true, queryResult: undefined } : msg
    ));

    try {
      const res = await fetch('/api/bigquery', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sql, mode: 'execute' }),
      });
      const data = await res.json();
      if (data.error) throw new Error(data.error);
      
      if (data.projectId) {
        setProjectId(data.projectId);
      }
      if (data.model) {
        setModelName(data.model);
      }
      
      setMessages(prev => prev.map((msg, i) => 
        i === index ? { 
          ...msg, 
          isExecuting: false, 
          queryResult: { rows: data.rows }
        } : msg
      ));
      
    } catch (e: unknown) {
      const errorMessage = e instanceof Error ? e.message : 'Unknown error';
      setMessages(prev => prev.map((msg, i) => 
        i === index ? { 
          ...msg, 
          isExecuting: false, 
          queryResult: { error: errorMessage }
        } : msg
      ));
    }
  };

  const resetChat = () => {
    lastPersistedSignatureRef.current = '';
    setMessages([]);
    setInput('');
    setLoading(false);
    setActiveSessionId(createSessionId());
  };

  const handleSelectSession = (selected: ChatSession) => {
    const selectedMessages = selected.messages || [];
    messagesRef.current = selectedMessages;
    lastPersistedSignatureRef.current = buildSessionSignature(selected.id, selectedMessages);
    setActiveSessionId(selected.id);
    setMessages(selectedMessages);
    setIsHistoryOpen(false);
    setLoading(false);
    setInput('');
  };

  const handleNewSession = () => {
    lastPersistedSignatureRef.current = '';
    setActiveSessionId(createSessionId());
    setMessages([]);
    setInput('');
    setLoading(false);
    setIsHistoryOpen(false);
  };

  const handleDeleteSession = (sessionId: string) => {
    setSessions((prev) => prev.filter((entry) => entry.id !== sessionId));
    if (sessionId === activeSessionId) {
      const remaining = sessions.filter((entry) => entry.id !== sessionId);
      if (remaining[0]) {
        const nextMessages = remaining[0].messages || [];
        messagesRef.current = nextMessages;
        lastPersistedSignatureRef.current = buildSessionSignature(remaining[0].id, nextMessages);
        setActiveSessionId(remaining[0].id);
        setMessages(nextMessages);
      } else {
        lastPersistedSignatureRef.current = '';
        setActiveSessionId(createSessionId());
        setMessages([]);
      }
      setInput('');
      setLoading(false);
    }
  };

  const handleTogglePin = (sessionId: string) => {
    setSessions((prev) =>
      [...prev]
        .map((entry) =>
          entry.id === sessionId ? { ...entry, pinned: !entry.pinned } : entry
        )
        .sort((a, b) => {
          const pinnedDiff = Number(Boolean(b.pinned)) - Number(Boolean(a.pinned));
          if (pinnedDiff !== 0) return pinnedDiff;
          return b.updatedAt - a.updatedAt;
        })
    );
  };

  const handleExportHistory = () => {
    const payload = JSON.stringify(sessions, null, 2);
    const blob = new Blob([payload], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `finops-history-${new Date().toISOString().slice(0, 10)}.json`;
    link.click();
    URL.revokeObjectURL(url);
  };

  const mergeImportedSessions = (incoming: ChatSession[]) => {
    setSessions((prev) => {
      const map = new Map<string, ChatSession>();
      prev.forEach((entry) => map.set(entry.id, entry));
      incoming.forEach((entry) => {
        if (!entry?.id || !entry?.messages) return;
        const existing = map.get(entry.id);
        if (existing) {
          const newer = existing.updatedAt >= entry.updatedAt ? existing : entry;
          map.set(entry.id, newer);
        } else {
          map.set(entry.id, entry);
        }
      });
      const merged: ChatSession[] = [];
      map.forEach((value) => merged.push(value));
      return merged.sort((a, b) => {
        const pinnedDiff = Number(Boolean(b.pinned)) - Number(Boolean(a.pinned));
        if (pinnedDiff !== 0) return pinnedDiff;
        return b.updatedAt - a.updatedAt;
      });
    });
  };

  const handleImportHistory = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      try {
        const parsed = JSON.parse(reader.result as string) as ChatSession[];
        if (Array.isArray(parsed)) {
          mergeImportedSessions(parsed);
        }
      } catch (error) {
        console.warn('Failed to import history', error);
      } finally {
        event.target.value = '';
      }
    };
    reader.readAsText(file);
  };

  const normalizedHistoryQuery = historyQuery.trim().toLowerCase();
  const filteredSessions = normalizedHistoryQuery
    ? sessions.filter((entry) => {
        const titleMatch = entry.title.toLowerCase().includes(normalizedHistoryQuery);
        const messageMatch = entry.messages.some((msg) => {
          const contentMatch = msg.content.toLowerCase().includes(normalizedHistoryQuery);
          const sqlMatch = msg.sql ? msg.sql.toLowerCase().includes(normalizedHistoryQuery) : false;
          return contentMatch || sqlMatch;
        });
        return titleMatch || messageMatch;
      })
    : sessions;

  // Quick action suggestions
  const quickActions = [
    { icon: MessageCircle, label: "Get Started", query: "What can you help me with?" },
    { icon: BarChart3, label: "Top Spenders", query: "Top 10 AWS accounts by cost, Dec 2025" },
    { icon: Zap, label: "Tenant Costs", query: "AWS 703227779288: cost by tenant tag, last 3 weeks" },
    { icon: Database, label: "EC2 Breakdown", query: "AWS 385595570414: EC2 instance types and costs, last month" },
  ];

  return (
    <main className="flex h-screen bg-cream-200 dark:bg-warm-900 text-warm-800 dark:text-cream-100 font-sans selection:bg-accent/20 overflow-hidden">
      {/* History Sidebar - Collapsible */}
      {isSidebarCollapsed ? (
        <aside className="hidden lg:flex flex-shrink-0">
          <CollapsedSidebar
            sessions={filteredSessions}
            onExpand={() => setIsSidebarCollapsed(false)}
            onNewSession={handleNewSession}
            onSelectSession={handleSelectSession}
          />
        </aside>
      ) : (
        <aside className="hidden lg:flex lg:flex-col w-80 flex-shrink-0 border-r border-cream-300 dark:border-warm-700 bg-white dark:bg-warm-900 transition-all duration-300">
          <HistoryPanel
            sessions={filteredSessions}
            hasAnySessions={sessions.length > 0}
            activeSessionId={activeSessionId}
            historyQuery={historyQuery}
            onHistoryQueryChange={setHistoryQuery}
            onSelectSession={handleSelectSession}
            onNewSession={handleNewSession}
            onDeleteSession={handleDeleteSession}
            onTogglePin={handleTogglePin}
            onExport={handleExportHistory}
            onImportClick={() => importInputRef.current?.click()}
            onCollapse={() => setIsSidebarCollapsed(true)}
          />
        </aside>
      )}

      <div className="flex-1 flex flex-col min-w-0 overflow-hidden">
        {/* Header - minimal like Manus */}
        <header className="h-14 px-4 border-b border-cream-300/60 dark:border-warm-700/60 bg-cream-200 dark:bg-warm-900 flex items-center justify-between flex-shrink-0 z-20">
          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={() => setIsHistoryOpen(true)}
              className="lg:hidden w-8 h-8 rounded-lg text-warm-500 hover:text-warm-700 hover:bg-cream-300/50 dark:text-warm-400 dark:hover:text-cream-100 dark:hover:bg-warm-700/50 transition-colors flex items-center justify-center"
              aria-label="Open menu"
            >
              <Menu className="w-5 h-5" />
            </button>
            <button 
              onClick={resetChat}
              className="flex items-center gap-1.5 hover:opacity-70 transition-opacity cursor-pointer focus:outline-none px-2 py-1 -ml-2"
              title="Start New Chat"
            >
              <span className="text-sm font-medium text-warm-700 dark:text-warm-200">FinOps Agent</span>
              <ChevronDown className="w-4 h-4 text-warm-400" />
            </button>
          </div>
          <div className="flex items-center gap-2">
            {projectId && (
              <div className="hidden sm:flex items-center px-2.5 py-1 rounded-lg bg-warm-800 dark:bg-cream-100 text-cream-100 dark:text-warm-800 text-xs font-medium">
                {projectId}
              </div>
            )}
            {modelName && (
              <div className="hidden sm:flex items-center px-2.5 py-1 rounded-lg bg-accent/10 text-accent text-xs font-medium">
                {modelName}
              </div>
            )}
            {session?.user?.email && (
              <button
                type="button"
                onClick={() => signOut({ callbackUrl: '/auth/signin' })}
                className="text-xs font-medium text-warm-500 hover:text-warm-700 dark:text-warm-400 dark:hover:text-cream-100 transition-colors px-2 py-1"
              >
                Sign Out
              </button>
            )}
          </div>
        </header>

        {/* Messages Area */}
        <div className="flex-1 overflow-y-auto scrollbar-thin bg-cream-200 dark:bg-warm-900">
          {/* Empty State - Manus style */}
          {messages.length === 0 && (
            <div className="flex flex-col items-center justify-center min-h-[calc(100vh-180px)] px-6 animate-fade-in">
              <div className="max-w-2xl w-full text-center">
                {/* Main Heading - Serif font like Manus */}
                <h1 className="heading-serif text-4xl md:text-5xl text-warm-800 dark:text-cream-100 mb-12">
                  What can I do for you?
                </h1>
                
                {/* Input Box */}
                <div className="relative mb-8">
                  <form onSubmit={handleSubmit}>
                    <div className="relative bg-white dark:bg-warm-800 rounded-2xl shadow-warm-lg border border-cream-300 dark:border-warm-600 overflow-hidden">
                      <input
                        type="text"
                        value={input}
                        onChange={(e) => setInput(e.target.value)}
                        placeholder="Ask about cloud costs, e.g. 'Top 10 AWS accounts by spend last month'"
                        className="w-full px-6 py-5 pr-14 bg-transparent text-warm-800 dark:text-cream-100 placeholder:text-warm-400 dark:placeholder:text-warm-500 outline-none text-base"
                      />
                      <div className="absolute right-4 top-1/2 -translate-y-1/2 flex items-center gap-2">
                        <button
                          type="submit"
                          disabled={loading || !input.trim()}
                          className={`w-9 h-9 rounded-full flex items-center justify-center transition-all duration-200 ${
                            input.trim() 
                              ? 'bg-warm-800 dark:bg-cream-100 text-cream-100 dark:text-warm-800 shadow-warm-md hover:shadow-warm-lg'
                              : 'bg-cream-200 dark:bg-warm-700 text-warm-400'
                          }`}
                        >
                          <ArrowUp className="w-4 h-4" />
                        </button>
                </div>
                    </div>
                  </form>
                </div>

                {/* Quick Actions - Pill buttons like Manus */}
                <div className="flex flex-wrap items-center justify-center gap-3">
                  {quickActions.map((action) => (
                    <button 
                      key={action.label}
                      onClick={() => handleSuggestionClick(action.query)}
                      className="btn-pill"
                    >
                      <action.icon className="w-4 h-4 text-warm-500" />
                      <span>{action.label}</span>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* Message List - Separated cards for each message */}
          {messages.length > 0 && (
            <div className="flex flex-col min-h-full">
              {/* Conversation Container */}
              <div className="flex-1 flex justify-center px-4 md:px-8 py-6">
                <div className="w-full max-w-3xl space-y-4">
                  {/* Messages as separate cards */}
                  {messages.map((msg, idx) => (
                    <div key={idx} className="animate-slide-up">
                      {msg.role === 'user' ? (
                        /* User message - Right aligned bubble with chat-style corner */
                        <div className="flex justify-end">
                          <div className="max-w-[80%] px-5 py-3 bg-warm-800 dark:bg-cream-100 text-cream-100 dark:text-warm-800 rounded-2xl rounded-br-sm shadow-warm-md">
                            <div className="prose prose-sm max-w-none prose-p:leading-relaxed prose-p:my-0 prose-p:text-cream-100 dark:prose-p:text-warm-800 font-medium">
                              <ReactMarkdown>{msg.content}</ReactMarkdown>
                            </div>
                          </div>
                        </div>
                      ) : (
                        /* Assistant message - Left aligned card */
                        <div className="bg-white dark:bg-warm-800 rounded-2xl shadow-warm-md border border-cream-200 dark:border-warm-700 overflow-hidden">
                          {/* Header with branding */}
                          <div className="px-5 pt-4 pb-3 flex items-center gap-2.5 border-b border-cream-200 dark:border-warm-700">
                            <div className="w-7 h-7 rounded-lg flex items-center justify-center bg-gradient-to-br from-accent to-accent-600 shadow-sm">
                              <Database className="w-4 h-4 text-white" />
                            </div>
                            <span className="text-sm font-semibold text-warm-800 dark:text-cream-100">FinOps</span>
                            <span className="text-[10px] font-medium text-accent bg-accent/10 px-2 py-0.5 rounded-full">Agent</span>
                          </div>

                          {/* Message content */}
                          <MessageBubbleContent 
                            msg={msg} 
                            index={idx}
                            onExecute={handleExecute} 
                          />
                        </div>
                      )}
                    </div>
                  ))}

                  {/* Loading Indicator - Separate card */}
                  {loading && (
                    <div className="animate-fade-in bg-white dark:bg-warm-800 rounded-2xl shadow-warm-md border border-cream-200 dark:border-warm-700 overflow-hidden">
                      <div className="px-5 pt-4 pb-3 flex items-center gap-2.5 border-b border-cream-200 dark:border-warm-700">
                        <div className="w-7 h-7 rounded-lg flex items-center justify-center bg-gradient-to-br from-accent to-accent-600 shadow-sm">
                          <Database className="w-4 h-4 text-white" />
                        </div>
                        <span className="text-sm font-semibold text-warm-800 dark:text-cream-100">FinOps</span>
                        <span className="text-[10px] font-medium text-accent bg-accent/10 px-2 py-0.5 rounded-full">Agent</span>
                      </div>
                      <div className="px-5 py-4">
                        <div className="inline-flex items-center gap-2.5 px-4 py-2.5 rounded-full bg-cream-100 dark:bg-warm-700/50 border border-cream-300 dark:border-warm-600">
                          <div className="w-4 h-4 rounded bg-accent animate-thinking" />
                          <span className="text-sm font-medium text-warm-600 dark:text-warm-300">Thinking</span>
                        </div>
                      </div>
                    </div>
                  )}
                  
                  {/* Bottom spacer to prevent content from being hidden under fixed input */}
                  <div ref={messagesEndRef} className="h-32" />
                </div>
              </div>
              
              {/* Fixed Input Area at Bottom */}
              <div className="sticky bottom-0 bg-gradient-to-t from-cream-200 via-cream-200/95 to-transparent dark:from-warm-900 dark:via-warm-900/95 dark:to-transparent pt-6 pb-4 px-4 md:px-8">
                <div className="max-w-3xl mx-auto">
                  {/* Subtle top separator line */}
                  <div className="absolute left-1/2 -translate-x-1/2 top-0 w-24 h-px bg-gradient-to-r from-transparent via-cream-400/50 dark:via-warm-600/50 to-transparent" />
                  <form onSubmit={handleSubmit}>
                    <div className="flex items-center gap-3 px-5 py-3.5 bg-white dark:bg-warm-800 rounded-2xl border border-cream-300 dark:border-warm-600 shadow-warm-lg backdrop-blur-sm">
                      {/* Input field */}
                      <input
                        type="text"
                        value={input}
                        onChange={(e) => setInput(e.target.value)}
                        placeholder="Ask a follow-up or new cost analysis question..."
                        className="flex-1 bg-transparent text-warm-800 dark:text-cream-100 placeholder:text-warm-400 dark:placeholder:text-warm-500 outline-none text-sm"
                      />
                      
                      {/* Submit button */}
                      <button
                        type="submit"
                        disabled={loading || !input.trim()}
                        className={`w-9 h-9 rounded-full flex items-center justify-center transition-all duration-200 flex-shrink-0 ${
                          input.trim() 
                            ? 'bg-warm-800 dark:bg-cream-100 text-cream-100 dark:text-warm-800 shadow-warm-md hover:shadow-warm-lg hover:scale-105'
                            : 'bg-cream-200 dark:bg-warm-700 text-warm-400'
                        }`}
                      >
                        <ArrowUp className="w-4 h-4" />
                      </button>
                    </div>
                  </form>
                  {/* Disclaimer */}
                  <div className="text-center mt-2">
                    <span className="text-[11px] text-warm-400 dark:text-warm-500">
                      AI can make mistakes. Verify important information.
                    </span>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Mobile History Panel Overlay */}
      {isHistoryOpen && (
        <div
          className="fixed inset-0 z-30 bg-warm-900/40 backdrop-blur-sm lg:hidden"
          onClick={() => setIsHistoryOpen(false)}
        >
          <div
            className="absolute left-0 top-0 h-full w-72 max-w-[85%] shadow-warm-xl animate-slide-up"
            onClick={(event) => event.stopPropagation()}
          >
            <HistoryPanel
              sessions={filteredSessions}
              hasAnySessions={sessions.length > 0}
              activeSessionId={activeSessionId}
              historyQuery={historyQuery}
              onHistoryQueryChange={setHistoryQuery}
              onSelectSession={handleSelectSession}
              onNewSession={handleNewSession}
              onDeleteSession={handleDeleteSession}
              onTogglePin={handleTogglePin}
              onExport={handleExportHistory}
              onImportClick={() => importInputRef.current?.click()}
              onClose={() => setIsHistoryOpen(false)}
            />
          </div>
        </div>
      )}
      <input
        ref={importInputRef}
        type="file"
        accept="application/json"
        onChange={handleImportHistory}
        className="hidden"
      />
    </main>
  );
}
