// Replace your current file with this (TypeScript React). No Tailwind required.
import React, { useState, useRef, useEffect } from "react";
import Head from "next/head";
import { useRouter } from "next/router";
import { useSession, signIn, signOut } from "next-auth/react";

type Message = { role: "user" | "assistant"; text: string; id: string };

interface ConversationSummary {
  id: string;
  title: string;
  updatedAt: number;
}

interface HomeProps {
  conversationId?: string;
}

export default function HomeNoTailwind({ conversationId }: HomeProps) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState("");
  const [listening, setListening] = useState(false);
  const [uploadName, setUploadName] = useState<string | null>(null);
  const [searchMode] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const [streamingMessage, setStreamingMessage] = useState("");
  const [conversations, setConversations] = useState<ConversationSummary[]>([]);
  const [currentConversationId, setCurrentConversationId] = useState<string | null>(conversationId || null);
  const [loadingConversationId, setLoadingConversationId] = useState<string | null>(null);
  const { data: session, status } = useSession();
  const isAuthed = status === 'authenticated' && !!session?.user;
  // Auth form state
  const [authMode, setAuthMode] = useState<'login'|'signup'>('login');
  const [loginUsername, setLoginUsername] = useState('');
  const [loginPassword, setLoginPassword] = useState('');
  const [signupUsername, setSignupUsername] = useState('');
  const [signupEmail, setSignupEmail] = useState('');
  const [signupPassword, setSignupPassword] = useState('');
  const [authProviders, setAuthProviders] = useState<any>(null);
  const messageEnd = useRef<HTMLDivElement | null>(null);
  const router = useRouter();
  const [uploadToast, setUploadToast] = useState<string | null>(null);
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [darkMode, setDarkMode] = useState(false);
  const [copiedId, setCopiedId] = useState<string | null>(null);
  const [hoveredMsgId, setHoveredMsgId] = useState<string | null>(null);
  const [subscriptionPlan, setSubscriptionPlan] = useState<string>('free');

  // Copy message text to clipboard
  async function copyToClipboard(text: string, msgId: string) {
    try {
      // Strip HTML tags for plain text copy
      const plainText = text.replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
      await navigator.clipboard.writeText(plainText);
      setCopiedId(msgId);
      setTimeout(() => setCopiedId(null), 2000);
    } catch (err) {
      console.error('Failed to copy:', err);
    }
  }

  // Load theme preference from localStorage
  useEffect(() => {
    try {
      const savedTheme = localStorage.getItem('theme');
      if (savedTheme === 'dark') setDarkMode(true);
    } catch {}
  }, []);

  // Save theme preference
  function toggleTheme() {
    const newMode = !darkMode;
    setDarkMode(newMode);
    try { localStorage.setItem('theme', newMode ? 'dark' : 'light'); } catch {}
  }

  // Restore last uploaded filename after refresh so we can keep using it for context
  useEffect(() => {
    try {
      const last = localStorage.getItem('lastUploadName');
      if (last) setUploadName(last);
    } catch {}
  }, []);

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

  // Close sidebar on Escape for accessibility
  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if (e.key === 'Escape') setSidebarOpen(false);
    }
    if (sidebarOpen) {
      window.addEventListener('keydown', onKey);
      return () => window.removeEventListener('keydown', onKey);
    }
  }, [sidebarOpen]);

  // Load conversations once authenticated
  useEffect(() => {
    if (isAuthed) {
      loadConversations();
      // Fetch subscription status
      fetchSubscriptionStatus();
    } else {
      setConversations([]);
      setSubscriptionPlan('free');
    }
  }, [isAuthed]);

  // Fetch subscription status from API
  async function fetchSubscriptionStatus() {
    try {
      const res = await fetch('/api/subscription/status');
      if (res.ok) {
        const data = await res.json();
        setSubscriptionPlan(data.plan || 'free');
      }
    } catch (err) {
      console.error('Failed to fetch subscription status:', err);
    }
  }

  // Fetch available auth providers so we only show Google button when configured
  useEffect(() => {
    async function loadProviders() {
      try {
        const r = await fetch('/api/auth/providers');
        if (r.ok) {
          const p = await r.json();
          setAuthProviders(p);
        }
      } catch {}
    }
    loadProviders();
  }, [status]);

  // Load specific conversation when conversationId changes (only when authed)
  useEffect(() => {
    if (isAuthed && conversationId && conversationId !== currentConversationId) {
      loadConversation(conversationId);
      setCurrentConversationId(conversationId);
    }
  }, [conversationId, isAuthed]);

  // Ensure conversation loads on initial mount when on /c/[id] and authed
  useEffect(() => {
    if (isAuthed && conversationId && messages.length === 0) {
      loadConversation(conversationId);
      setCurrentConversationId(conversationId);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Load user's conversations
  async function loadConversations() {
    try {
      console.log('🔄 Loading conversations...');
      const response = await fetch('/api/conversations', { cache: 'no-store', headers: { 'Cache-Control': 'no-cache' } });
      console.log('📊 Response status:', response.status);
      const data = await response.json();
      console.log('📊 Response data:', data);
      if (data.conversations) {
        console.log('✅ Setting conversations:', data.conversations.length, 'items');
        setConversations(data.conversations);
      } else {
        console.log('⚠️ No conversations in response');
      }
    } catch (error) {
      console.error('❌ Error loading conversations:', error);
    }
  }

  // Load specific conversation
  async function loadConversation(id: string) {
    try {
      setLoadingConversationId(id);
      const response = await fetch(`/api/conversation/${id}`);
      if (response.ok) {
        const data = await response.json();
        if (data.conversation) {
          const conversationMessages = data.conversation.messages.map((msg: any) => ({
            role: msg.role,
            text: msg.content,
            id: `${msg.role}-${msg.timestamp}`
          }));
          setMessages(conversationMessages);
        }
      }
    } catch (error) {
      console.error('Error loading conversation:', error);
    } finally {
      setLoadingConversationId(null);
    }
  }

  // Auth handlers
  async function handleCredentialsLogin(e?: React.FormEvent) {
    if (e) e.preventDefault();
    const result = await signIn('credentials', {
      redirect: false,
      username: loginUsername,
      password: loginPassword,
    });
    if (result?.error) {
      alert('Login failed: ' + result.error);
    } else {
      setLoginPassword('');
      loadConversations();
    }
  }

  async function handleSignup(e?: React.FormEvent) {
    if (e) e.preventDefault();
    try {
      const r = await fetch('/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username: signupUsername || null, email: signupEmail || null, password: signupPassword }),
      });
      const j = await r.json();
      if (!r.ok) throw new Error(j.error || 'Sign up failed');
      alert('Account created. You can now sign in.');
      setAuthMode('login');
      setLoginUsername(signupEmail || signupUsername);
      setSignupPassword('');
    } catch (err: any) {
      alert(err.message || 'Sign up failed');
    }
  }

  async function handleGoogleLogin() {
    await signIn('google');
  }

  async function handleSignOut() {
    await signOut({ redirect: false });
    setConversations([]);
    setMessages([]);
    router.push('/');
  }

  // Create new conversation
  async function createNewConversation() {
    try {
      if (!isAuthed) { alert('Please sign in to create a conversation.'); return; }
      const response = await fetch('/api/conversations', { method: 'POST' });
      const data = await response.json();
      if (data.conversation) {
        const newId = data.conversation.id;
        setCurrentConversationId(newId);
        setMessages([]);
        setInput("");
        setUploadName(null);
        try { localStorage.removeItem('lastUploadName'); } catch {}
        setIsLoading(false);
        // Optimistically show the new conversation in the sidebar immediately
        setConversations((prev) => [
          { id: newId, title: 'New Conversation', updatedAt: Date.now() },
          ...prev.filter((c) => c.id !== newId),
        ]);
        router.push(`/c/${newId}`);
        loadConversations(); // Refresh sidebar
      }
    } catch (error) {
      console.error('Error creating conversation:', error);
    }
  }

  // Delete conversation
  async function deleteConversation(id: string) {
    try {
      if (!isAuthed) { alert('Please sign in first.'); return; }
      const response = await fetch('/api/conversations', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ conversationId: id })
      });
      if (response.ok) {
        loadConversations(); // Refresh sidebar
        if (id === currentConversationId) {
          router.push('/'); // Go to home if current conversation was deleted
        }
      }
    } catch (error) {
      console.error('Error deleting conversation:', error);
    }
  }

  function formatMessage(text: string): string {
    return text
      // Bold text: **text** -> <strong>text</strong>
      .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      // Italic text: *text* -> <em>text</em>
      .replace(/\*(.*?)\*/g, '<em>$1</em>')
      // Headers: ## Header -> <h3>Header</h3>
      .replace(/^### (.*$)/gm, '<h4 style="font-size: 1.1em; font-weight: 600; margin: 12px 0 6px 0;">$1</h4>')
      .replace(/^## (.*$)/gm, '<h3 style="font-size: 1.2em; font-weight: 600; margin: 14px 0 8px 0;">$1</h3>')
      .replace(/^# (.*$)/gm, '<h2 style="font-size: 1.3em; font-weight: 700; margin: 16px 0 10px 0;">$1</h2>')
      // Line breaks: \n -> <br>
      .replace(/\n/g, '<br>')
      // Lists: - item -> <li>item</li>
      .replace(/^- (.*$)/gm, '<li style="margin: 4px 0; padding-left: 8px;">$1</li>')
      // Wrap consecutive <li> elements in <ul>
      .replace(/(<li[^>]*>.*?<\/li>)(?:\s*<li[^>]*>.*?<\/li>)*/g, (match) => 
        `<ul style="margin: 8px 0; padding-left: 20px; list-style-type: disc;">${match}</ul>`
      );
  }

  // Generate a preview title similar to the server logic (first 6 words, ellipsis at >50 chars)
  function generateTitlePreview(firstMessage: string): string {
    const words = firstMessage.trim().split(/\s+/).slice(0, 6);
    const base = words.join(' ');
    if (!base) return 'New Conversation';
    return firstMessage.length > 50 ? base + '...' : base;
  }

  function addUserMessage(text: string) {
    const m = { role: "user" as const, text, id: String(Date.now()) };
    setMessages((prev) => [...prev, m]);
    return m;
  }

  async function handleSend() {
    const trimmed = input.trim();
    console.log("handleSend called with:", trimmed);
    if (!trimmed || isLoading) {
      console.log("Skipping send: empty input or loading");
      return;
    }
    // Guests are allowed up to 5 queries (enforced server-side). No DB persistence for guests.

    setInput("");
    setIsLoading(true);
    const userMsg: Message = { role: "user", text: trimmed, id: "u-" + Date.now() };
    setMessages((prev) => [...prev, userMsg]);

    // Create new conversation if none exists (only when authed)
    let conversationId = currentConversationId;
    let createdThisSend = false;
    if (isAuthed && !conversationId) {
      try {
        const response = await fetch('/api/conversations', { method: 'POST' });
        const data = await response.json();
        if (data.conversation) {
          conversationId = data.conversation.id;
          setCurrentConversationId(conversationId);
          createdThisSend = true; // delay navigation until after streaming completes
          // Immediately reflect in sidebar as "New Conversation"
          setConversations((prev) => [
            { id: conversationId!, title: 'New Conversation', updatedAt: Date.now() },
            ...prev.filter((c) => c.id !== conversationId),
          ]);
          // Also prefetch latest from server in background
          loadConversations();
        }
      } catch (error) {
        console.error('Error creating conversation:', error);
      }
    }

    // Save user message to conversation
    if (isAuthed && conversationId) {
      try {
        await fetch(`/api/conversation/${conversationId}`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ role: 'user', content: trimmed })
        });
        // If this is the first user message, update sidebar title right away
        const preview = generateTitlePreview(trimmed);
        setConversations((prev) => {
          const next = prev.filter((c) => c.id !== conversationId);
          return [
            { id: conversationId!, title: preview, updatedAt: Date.now() },
            ...next,
          ];
        });
        // Reconcile with DB (will include accurate updated_at ordering if others changed)
        loadConversations();
      } catch (error) {
        console.error('Error saving user message:', error);
      }
    }
    console.log("Starting API request...");

    try {
      // Try streaming first
      console.log("Attempting streaming API call...");
      // Smart detection: include file context for document-related queries
      const q = trimmed.toLowerCase();
      
      // Keywords that indicate user wants to use the uploaded document
      const documentReferenceKeywords = [
        // Direct references
        'document', 'file', 'pdf', 'uploaded', 'attachment', 'the file', 'this file', 'my file',
        // Summary requests
        'summarize', 'summary', 'summarise', 'tldr', 'tl;dr', 'overview', 'key points', 'highlights', 'brief', 'gist', 'outline',
        // Content queries
        'in the', 'from the', 'according to', 'based on', 'what does it say', 'what is in',
        // Specific document terms (invoice, contract, etc.)
        'invoice', 'contract', 'agreement', 'report', 'receipt', 'statement'
      ];
      
      // Only include file if user has uploaded AND is asking about it
      const isFileRelatedQuery = !!uploadName && documentReferenceKeywords.some(k => q.includes(k));

      // Prepare conversation history for context
      const conversationHistory = messages.map(msg => ({
        role: msg.role,
        content: msg.text
      }));

      const requestBody = { 
        message: trimmed,
        conversationHistory: conversationHistory,
        search: searchMode,
        hasFile: isFileRelatedQuery,
        fileName: isFileRelatedQuery ? uploadName : null
      };
      console.log("Request body:", requestBody);
      
      const res = await fetch("/api/stream", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(requestBody),
      }).catch((error) => {
        console.error("Streaming API error:", error);
        return null;
      });

      if (!res) {
        console.log("Streaming failed, trying fallback API...");
      } else if (res.status === 403) {
        const msg = await res.text();
        setIsLoading(false);
        alert(msg || 'Free limit reached. Please sign up to continue.');
        router.push('/auth/signup');
        return;
      }

      if (!res || !res.body) {
        console.log("Streaming failed, trying fallback API...");
        const r = await fetch("/api/generate", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(requestBody),
        });
        
        if (r.status === 403) {
          const j = await r.json().catch(() => ({}));
          setIsLoading(false);
          alert(j.message || 'Free limit reached. Please sign up to continue.');
          router.push('/auth/signup');
          return;
        }

        if (!r.ok) {
          throw new Error(`API error: ${r.status} ${r.statusText}`);
        }
        
        const data = await r.json().catch(() => ({}));
        console.log("Fallback API response:", data);
        setIsLoading(false);
        setMessages((prev) => [
          ...prev,
          { role: "assistant", text: data.text || "(no response)", id: "a-" + Date.now() },
        ]);
        return;
      }

      console.log("Starting streaming response...");
      const reader = res.body.getReader();
      const decoder = new TextDecoder();
      let assistantText = "";
      const assistantId = "a-" + Date.now();
      setMessages((prev) => [...prev, { role: "assistant", text: "", id: assistantId }]);
      
      // Hide thinking indicator once streaming starts
      setIsLoading(false);
      
      while (true) {
        const { done, value } = await reader.read();
        if (done) {
          console.log("Streaming complete");
          setStreamingMessage("");
          
          // Save assistant message to conversation
          if (isAuthed && conversationId && assistantText) {
            try {
              await fetch(`/api/conversation/${conversationId}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ role: 'assistant', content: assistantText })
              });
              loadConversations(); // Refresh sidebar to show updated conversation
            } catch (error) {
              console.error('Error saving assistant message:', error);
            }
          }
          // If we created a new conversation during this send, navigate now
          // if (isAuthed && createdThisSend && conversationId) {
          //   router.push(`/c/${conversationId}`);
          // }
          
          break;
        }
        const chunk = decoder.decode(value);
        console.log("Received chunk:", chunk);
        
        // Stream in small batches for smooth effect, 3x speed (3 chars per tick)
        const STEP = 3;
        for (let i = 0; i < chunk.length; i += STEP) {
          const part = chunk.slice(i, i + STEP);
          assistantText += part;
          setMessages((prev) => prev.map((m) => (m.id === assistantId ? { ...m, text: assistantText } : m)));
          await new Promise(resolve => setTimeout(resolve, 8));
        }
      }
    } catch (err) {
      console.error(err);
      setMessages((prev) => [...prev, { role: "assistant", text: "Unable to respond to your question at this time.  Please try later.", id: "a-" + Date.now() }]);
    } finally {
      setIsLoading(false);
    }
  }

  function startVoice() {
    console.log("Starting voice recognition...");
    const SpeechRecognition = (window as any).webkitSpeechRecognition || (window as any).SpeechRecognition;
    if (!SpeechRecognition) {
      alert("Speech recognition not supported in this browser. Please use Chrome, Edge, or Safari.");
      return;
    }
    
    const rec = new SpeechRecognition();
    rec.lang = "en-US";
    rec.interimResults = true;
    rec.continuous = false;
    rec.maxAlternatives = 1;
    
    rec.onstart = () => {
      console.log("Voice recognition started");
      setListening(true);
    };
    
    rec.onend = () => {
      console.log("Voice recognition ended");
      setListening(false);
    };
    
    rec.onresult = (event: any) => {
      console.log("Voice recognition result:", event);
      let finalTranscript = "";
      let interimTranscript = "";
      
      for (let i = event.resultIndex; i < event.results.length; i++) {
        const transcript = event.results[i][0].transcript;
        if (event.results[i].isFinal) {
          finalTranscript += transcript;
        } else {
          interimTranscript += transcript;
        }
      }
      
      const fullTranscript = finalTranscript || interimTranscript;
      console.log("Setting input to:", fullTranscript);
      setInput(fullTranscript);
    };
    
    rec.onerror = (event: any) => {
      console.error("Speech recognition error:", event.error);
      setListening(false);
      if (event.error === 'not-allowed') {
        alert("Microphone access denied. Please allow microphone access and try again.");
      } else if (event.error === 'no-speech') {
        alert("No speech detected. Please try again.");
      } else {
        alert(`Speech recognition error: ${event.error}`);
      }
    };
    
    try {
      rec.start();
    } catch (error) {
      console.error("Failed to start speech recognition:", error);
      setListening(false);
      alert("Failed to start voice recognition. Please try again.");
    }
  }

  async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const files = e.target.files;
    if (!files || files.length === 0) return;
    const f = files[0];
    setUploadName(f.name);
    const fd = new FormData();
    fd.append("file", f);
    try {
      const r = await fetch("/api/upload", { method: "POST", body: fd });
      let j: any = null;
      try { j = await r.json(); } catch { j = null; }
      if (r.ok && j?.ok) {
        console.log("File uploaded successfully:", j);
        // Show a small toast that disappears automatically
        setUploadToast(`File "${f.name}" uploaded. You can now ask questions about this file.`);
        setTimeout(() => setUploadToast(null), 3500);
        try { localStorage.setItem('lastUploadName', f.name); } catch {}
      } else {
        const msg = j?.error || `${r.status} ${r.statusText}`;
        console.error("Upload failed:", j || msg);
        alert("❌ Upload failed: " + msg);
      }
    } catch (err) {
      console.error('Upload exception:', err);
      alert("❌ Upload failed: " + ((err as any)?.message || 'Network error'));
    }
  }

  // Theme colors
  const theme = darkMode ? {
    bg: '#1a1a2e',
    sidebarBg: '#16162a',
    cardBg: '#252542',
    border: '#3d3d5c',
    text: '#e5e5e5',
    textSecondary: '#9ca3af',
    textMuted: '#6b7280',
    inputBg: '#252542',
    bubbleBg: '#252542',
    logo: '/logo2.png'
  } : {
    bg: 'linear-gradient(180deg,#f8fafc,#f1f5f9)',
    sidebarBg: 'rgba(255,255,255,0.8)',
    cardBg: '#fff',
    border: '#e6e6e6',
    text: '#0f172a',
    textSecondary: '#374151',
    textMuted: '#6b7280',
    inputBg: 'rgba(255,255,255,0.98)',
    bubbleBg: '#fff',
    logo: '/logo.png'
  };

  // Inline styles so it works without Tailwind
  const S: Record<string, React.CSSProperties> = {
    page: { minHeight: "100vh", display: "flex", fontFamily: "Inter, Helvetica, Arial, sans-serif", background: theme.bg },
    sidebar: { width: 280, padding: 16, borderRight: `1px solid ${theme.border}`, boxSizing: "border-box", background: theme.sidebarBg, minHeight: "100vh" },
    logoRow: { display: "flex", alignItems: "center", gap: 12, marginBottom: 12 },
    bigG: { width: 44, height: 44, borderRadius: 12, display: "flex", alignItems: "center", justifyContent: "center", background: "linear-gradient(90deg,#2563eb,#7c3aed)", color: "#fff", fontWeight: 700 },
    circleBtn: { width: 40, height: 40, borderRadius: 999, display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer", border: "none" },
    micOn: { background: "#ef4444", color: "#fff" },
    micOff: { background: darkMode ? "#3d3d5c" : "#f3f4f6", color: darkMode ? "#e5e5e5" : "#111827" },
    main: { flex: 1, marginLeft: 0, padding: "24px 24px 140px", overflowY: "auto" as const },
    centerHero: { display: "flex", flexDirection: "column" as const, alignItems: "center", justifyContent: "center", minHeight: "60vh", textAlign: "center" as const },
    cardsGrid: { display: "grid", gridTemplateColumns: "repeat(2,160px)", gap: 12 },
    card: { padding: 16, borderRadius: 12, background: theme.cardBg, boxShadow: darkMode ? "0 4px 12px rgba(0,0,0,0.3)" : "0 6px 18px rgba(15,23,42,0.06)", cursor: "pointer", textAlign: "left" as const, color: theme.text, border: `1px solid ${theme.border}`, transition: "all 0.2s ease" },
    chatWindow: { maxWidth: 800, margin: "0 auto", paddingBottom: "10px", paddingTop: "20px" },
    msgRow: { display: "flex", gap: 12, alignItems: "flex-start", marginBottom: 32, paddingBottom: 8 },
    assistantBubble: { background: theme.bubbleBg, padding: "12px 16px", borderRadius: 14, boxShadow: darkMode ? "0 2px 8px rgba(0,0,0,0.2)" : "0 4px 12px rgba(2,6,23,0.06)", color: theme.text, maxWidth: "100%", border: darkMode ? `1px solid ${theme.border}` : 'none' },
    userBubble: { background: "linear-gradient(90deg,#2563eb,#7c3aed)", padding: "12px 16px", borderRadius: 14, color: "#fff", maxWidth: "100%" },
    inputBarWrap: { position: "fixed" as const, left: 280 + 24, right: 24, bottom: 68, display: "flex", justifyContent: "center", zIndex: 1000 },
    inputBar: { display: "flex", alignItems: "center", gap: 8, background: theme.inputBg, borderRadius: 999, padding: "8px 16px", boxShadow: darkMode ? "0 4px 20px rgba(0,0,0,0.3)" : "0 4px 20px rgba(0,0,0,0.08)", maxWidth: 700, width: "100%", border: `1px solid ${theme.border}` },
    textInput: { flex: 1, border: "none", outline: "none", fontSize: 15, background: "transparent", color: theme.text }
  };

  return (
    <>
      <Head>
        <title>Gregory AI</title>
        <meta name="description" content="Gregory AI - Your intelligent assistant for conversations, file analysis, and more." />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/logo.png" />
        <link rel="apple-touch-icon" href="/logo.png" />
      </Head>
      <style>{`
        body { 
          margin: 0; 
          padding: 0; 
          background: ${darkMode ? '#1a1a2e' : 'linear-gradient(180deg,#f8fafc,#f1f5f9)'}; 
          min-height: 100vh; 
        }
        html { 
          background: ${darkMode ? '#1a1a2e' : 'linear-gradient(180deg,#f8fafc,#f1f5f9)'}; 
          min-height: 100vh; 
        }
        
        /* Typing indicator animations */
        @keyframes bounce {
          0%, 80%, 100% { 
            transform: scale(0);
            opacity: 0.5;
          } 
          40% { 
            transform: scale(1);
            opacity: 1;
          }
        }

        /* Spinner for conversation loading */
        @keyframes spin {
          to { transform: rotate(360deg); }
        }
        .hamburger { display: none; }
        
        /* Mobile responsive styles */
        @media (max-width: 768px) {
          .sidebar {
            position: fixed !important;
            top: 0; left: 0; height: 100vh;
            width: 280px; max-width: 80vw;
            transform: translateX(-100%);
            transition: transform 0.3s ease;
            z-index: 1100;
          }
          .sidebar.open { transform: translateX(0); }
          .hamburger {
            position: fixed;
            top: 12px; left: 12px;
            width: 40px; height: 40px;
            border-radius: 10px;
            background: ${darkMode ? '#252542' : '#fff'};
            border: 1px solid ${darkMode ? '#3d3d5c' : '#e5e7eb'};
            box-shadow: ${darkMode ? '0 4px 12px rgba(0,0,0,0.3)' : '0 8px 20px rgba(0,0,0,0.08)'};
            display: inline-flex;
            align-items: center; justify-content: center;
            color: ${darkMode ? '#e5e5e5' : '#111827'}; font-size: 20px;
            z-index: 1200; cursor: pointer;
          }
          .main-content {
            margin-left: 0 !important;
          }
          .input-bar-wrap {
            left: 24px !important;
          }
          .disclaimer-mobile {
            left: 0 !important;
          }
        }
      `}</style>
      <div style={S.page}>
        <button
          type="button"
          className="hamburger"
          onClick={() => setSidebarOpen(true)}
          aria-label="Open menu"
          aria-controls="sidebar"
          aria-expanded={sidebarOpen}
        >
          ☰
        </button>
        <aside id="sidebar" role="complementary" className={`sidebar ${sidebarOpen ? 'open' : ''}`} style={S.sidebar}>
        <div style={S.logoRow}>
          <img src={theme.logo} alt="Gregory AI" style={{ width: 44, height: 44, borderRadius: 12 }} />
          <div style={{ fontWeight: 700, fontSize: 18, color: theme.text }}>Gregory AI</div>
        </div>
        {/* Theme Toggle */}
        <button
          onClick={toggleTheme}
          style={{
            width: '100%',
            padding: '10px 12px',
            marginBottom: 12,
            borderRadius: 10,
            border: `1px solid ${theme.border}`,
            background: theme.cardBg,
            color: theme.text,
            cursor: 'pointer',
            fontSize: 14,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            gap: 8
          }}
        >
          {darkMode ? '☀️ Light Mode' : '🌙 Dark Mode'}
        </button>
        {/* Auth Box: show links only when logged out; name and sign out when logged in */}
        {!isAuthed ? (
          <div style={{ padding: 12, background: theme.cardBg, border: `1px solid ${theme.border}`, borderRadius: 12, marginBottom: 12 }}>
            <div style={{ fontWeight: 600, fontSize: 14, color: theme.text, marginBottom: 8 }}>Welcome</div>
            <div style={{ display: 'flex', gap: 8 }}>
              <button 
                onClick={() => router.push('/auth/signin')}
                style={{ flex:1, padding:'10px 12px', borderRadius:10, border:'none', background:'linear-gradient(90deg,#2563eb,#7c3aed)', color:'#fff', cursor:'pointer' }}
              >Sign in</button>
              <button 
                onClick={() => router.push('/auth/signup')}
                style={{ flex:1, padding:'10px 12px', borderRadius:10, border:`1px solid ${theme.border}`, background: darkMode ? '#3d3d5c' : '#10b981', color: darkMode ? '#e5e5e5' : '#fff', cursor:'pointer' }}
              >Sign up</button>
            </div>
            <button 
              onClick={() => router.push('/pricing')}
              style={{ width:'100%', marginTop: 8, padding:'10px 12px', borderRadius:10, border:`1px solid ${darkMode ? '#4c1d95' : '#ddd6fe'}`, background: darkMode ? '#2d2d4a' : '#f5f3ff', color: darkMode ? '#c4b5fd' : '#7c3aed', cursor:'pointer', fontSize: 13, fontWeight: 500 }}
            >✨ View Pricing Plans</button>
          </div>
        ) : (
          <div
            style={{
              padding: 14,
              background: darkMode ? '#252542' : 'linear-gradient(180deg,#ffffff,#f9fafb)',
              border: `1px solid ${theme.border}`,
              borderRadius: 14,
              marginBottom: 12,
              boxShadow: darkMode ? '0 4px 12px rgba(0,0,0,0.3)' : '0 10px 24px rgba(15,23,42,0.08)'
            }}
          >
            <div style={{ display: 'grid', gridTemplateColumns: '40px 1fr', alignItems: 'center', columnGap: 10, marginBottom: 12 }}>
              {session?.user?.image ? (
                <img src={session.user.image as string} alt="Avatar" style={{ width: 36, height: 36, borderRadius: '50%', border: `1px solid ${theme.border}` }} />
              ) : (
                <div
                  style={{
                    width: 36,
                    height: 36,
                    borderRadius: '50%',
                    background: 'linear-gradient(90deg,#2563eb,#7c3aed)',
                    color: '#fff',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontWeight: 700,
                  }}
                >
                  {(session?.user?.name || session?.user?.email || 'U').slice(0, 1).toUpperCase()}
                </div>
              )}
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', justifyContent: 'center' }}>
                <div style={{ fontSize: 12, color: theme.textMuted, margin: 0, lineHeight: 1, whiteSpace: 'nowrap' }}>Signed in</div>
                <div style={{ fontSize: 14, fontWeight: 700, color: theme.text, marginTop: 2, lineHeight: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 180 }}>{session?.user?.name || session?.user?.email || 'User'}</div>
              </div>
            </div>

            {/* Subscription Plan Badge */}
            <div style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              padding: '8px 12px',
              marginBottom: 10,
              borderRadius: 8,
              background: darkMode ? '#2d2d4a' : '#f0fdf4',
              border: `1px solid ${darkMode ? '#3d3d5c' : '#bbf7d0'}`
            }}>
              <span style={{ fontSize: 12, color: theme.textMuted }}>Plan:</span>
              <span style={{ fontSize: 12, fontWeight: 600, color: darkMode ? '#4ade80' : '#16a34a' }}>
                {subscriptionPlan.charAt(0).toUpperCase() + subscriptionPlan.slice(1)}
              </span>
            </div>

            {/* Upgrade/Pricing Link */}
            <button
              onClick={() => router.push('/pricing')}
              style={{
                width: '100%',
                padding: '10px 12px',
                marginBottom: 8,
                borderRadius: 10,
                border: `1px solid ${darkMode ? '#4c1d95' : '#ddd6fe'}`,
                background: darkMode ? 'linear-gradient(90deg,#4c1d95,#7c3aed)' : 'linear-gradient(90deg,#ede9fe,#f5f3ff)',
                color: darkMode ? '#e9d5ff' : '#7c3aed',
                cursor: 'pointer',
                fontSize: 14,
                fontWeight: 600,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                gap: 8
              }}
            >
              ✨ {subscriptionPlan === 'free' ? 'Upgrade Plan' : 'Manage Plan'}
            </button>

            {/* Admin Link */}
            {(session?.user as any)?.isAdmin && (
              <button
                onClick={() => router.push('/admin')}
                style={{
                  width: '100%',
                  padding: '10px 12px',
                  marginBottom: 8,
                  borderRadius: 10,
                  border: `1px solid ${theme.border}`,
                  background: darkMode ? '#1f2d3d' : '#eff6ff',
                  color: '#3b82f6',
                  cursor: 'pointer',
                  fontSize: 14,
                  fontWeight: 600,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  gap: 8
                }}
              >
                ⚙️ Admin Dashboard
              </button>
            )}

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              <button
                onClick={createNewConversation}
                style={{
                  width: '100%',
                  height: 44,
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  padding: '0 12px',
                  boxSizing: 'border-box',
                  borderRadius: 10,
                  border: 'none',
                  background: 'linear-gradient(90deg,#2563eb,#7c3aed)',
                  color: '#fff',
                  cursor: 'pointer',
                  boxShadow: '0 4px 12px rgba(79,70,229,0.3)',
                  transition: 'transform 0.15s ease, box-shadow 0.15s ease',
                  whiteSpace: 'nowrap'
                }}
                onMouseEnter={(e) => {
                  (e.currentTarget as HTMLButtonElement).style.transform = 'translateY(-1px)';
                  (e.currentTarget as HTMLButtonElement).style.boxShadow = '0 10px 22px rgba(37,99,235,0.32)';
                }}
                onMouseLeave={(e) => {
                  (e.currentTarget as HTMLButtonElement).style.transform = 'translateY(0)';
                  (e.currentTarget as HTMLButtonElement).style.boxShadow = '0 8px 18px rgba(37,99,235,0.25)';
                }}
              >
                + New Chat
              </button>
              <button
                onClick={handleSignOut}
                style={{
                  width: '100%',
                  height: 44,
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  padding: '0 12px',
                  boxSizing: 'border-box',
                  borderRadius: 10,
                  border: `1px solid ${darkMode ? '#3d3d5c' : '#fee2e2'}`,
                  background: darkMode ? '#3d3d5c' : '#fff',
                  color: '#ef4444',
                  cursor: 'pointer',
                  transition: 'background 0.15s ease, border-color 0.15s ease',
                  whiteSpace: 'nowrap'
                }}
                onMouseEnter={(e) => {
                  (e.currentTarget as HTMLButtonElement).style.background = '#fff5f5';
                  (e.currentTarget as HTMLButtonElement).style.borderColor = '#fecaca';
                }}
                onMouseLeave={(e) => {
                  (e.currentTarget as HTMLButtonElement).style.background = darkMode ? '#3d3d5c' : '#fff';
                  (e.currentTarget as HTMLButtonElement).style.borderColor = darkMode ? '#3d3d5c' : '#fee2e2';
                }}
              >
                Sign out
              </button>
            </div>
          </div>
        )}
        
        {/* Debug info */}
        <div style={{ fontSize: 10, color: "#999", marginTop: 8, display: 'none' }}>
          Debug: {conversations.length} conversations loaded
        </div>
        
        {isAuthed && conversations.length > 0 && (
          <>
            <div style={{ marginTop: 18, fontSize: 12, color: theme.textMuted, fontWeight: 700 }}>RECENT</div>
            <div style={{ marginTop: 8, maxHeight: "400px", overflowY: "auto" }}>
              {conversations.map((conv) => (
                <div
                  key={conv.id}
                  onClick={() => { setLoadingConversationId(conv.id); router.push(`/c/${conv.id}`); setSidebarOpen(false); }}
                  style={{
                    padding: "8px 12px",
                    margin: "4px 0",
                    borderRadius: 8,
                    cursor: "pointer",
                    background: conv.id === currentConversationId ? (darkMode ? "#3d3d5c" : "#f3f4f6") : "transparent",
                    fontSize: 14,
                    color: theme.text,
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                    transition: "background 0.2s"
                  }}
                  onMouseEnter={(e) => {
                    if (conv.id !== currentConversationId) {
                      e.currentTarget.style.background = darkMode ? "#2d2d44" : "#f9fafb";
                    }
                  }}
                  onMouseLeave={(e) => {
                    if (conv.id !== currentConversationId) {
                      e.currentTarget.style.background = "transparent";
                    }
                  }}
                >
                  <span style={{ 
                    overflow: "hidden", 
                    textOverflow: "ellipsis", 
                    whiteSpace: "nowrap",
                    flex: 1
                  }}>
                    {conv.title}
                  </span>
                  {loadingConversationId === conv.id ? (
                    <div
                      aria-label="Loading conversation"
                      style={{
                        width: 14,
                        height: 14,
                        border: '2px solid #d1d5db',
                        borderTopColor: '#6b7280',
                        borderRadius: '50%',
                        animation: 'spin 0.8s linear infinite',
                        marginLeft: 8
                      }}
                    />
                  ) : (
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        deleteConversation(conv.id);
                      }}
                      style={{
                        background: "none",
                        border: "none",
                        color: "#9ca3af",
                        cursor: "pointer",
                        padding: "2px 4px",
                        borderRadius: 4,
                        fontSize: 12,
                        marginLeft: 8
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.color = "#ef4444";
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.color = "#9ca3af";
                      }}
                    >
                      ×
                    </button>
                  )}
                </div>
              ))}
            </div>
          </>
        )}
      </aside>
      {sidebarOpen && (
        <div
          className="sidebar-overlay"
          aria-hidden="true"
          onClick={() => setSidebarOpen(false)}
          style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.35)', zIndex: 1090 }}
        />
      )}

      <main className="main-content" style={S.main}>
        {messages.length === 0 ? (
          <div style={S.centerHero}>
            <h1 style={{ margin: 0, fontSize: 36, color: theme.text, fontWeight: 700, marginBottom: 8 }}>Gregory AI</h1>
            <h2 style={{ margin: 0, fontSize: 24, color: theme.textSecondary, fontWeight: 500 }}>Digital Intelligence</h2>
            <p style={{ color: theme.textMuted, marginTop: 6 }}>What would you like to explore today?</p>
            <div style={S.cardsGrid}>
              {[
                { label: "Sports ⚽", query: "Latest sports news and match results" },
                { label: "News 📰", query: "Top news headlines today" },
                { label: "Weather 🌤️", query: "Current weather forecast" },
                { label: "Stocks 📈", query: "Stock market updates" }
              ].map((item) => (
                <div 
                  key={item.label} 
                  style={{...S.card, transition: "all 0.2s ease"}} 
                  onClick={() => setInput(item.query)}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.transform = "translateY(-2px)";
                    e.currentTarget.style.boxShadow = darkMode ? "0 8px 20px rgba(0,0,0,0.4)" : "0 8px 25px rgba(15,23,42,0.12)";
                    e.currentTarget.style.borderColor = "#2563eb";
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.transform = "translateY(0px)";
                    e.currentTarget.style.boxShadow = darkMode ? "0 4px 12px rgba(0,0,0,0.3)" : "0 6px 18px rgba(15,23,42,0.06)";
                    e.currentTarget.style.borderColor = theme.border;
                  }}
                >
                  {item.label}
                </div>
              ))}
            </div>
          </div>
        ) : (
          <div style={S.chatWindow}>
            {messages.map((m) => (
              <div 
                key={m.id} 
                style={{ ...S.msgRow, justifyContent: m.role === "user" ? "flex-end" : "flex-start" }}
                onMouseEnter={() => setHoveredMsgId(m.id)}
                onMouseLeave={() => setHoveredMsgId(null)}
              >
                {m.role === "assistant" && <img src={theme.logo} alt="Gregory AI" style={{ width: 36, height: 36, borderRadius: 8 }} />}
                <div style={{ position: 'relative', maxWidth: '75%' }}>
                  <div 
                    style={m.role === "assistant" ? S.assistantBubble : S.userBubble}
                    dangerouslySetInnerHTML={{
                      __html: m.role === "assistant" ? formatMessage(m.text) : m.text
                    }}
                  />
                  {/* Floating action buttons */}
                  {(hoveredMsgId === m.id || copiedId === m.id) && (
                    <div style={{
                      position: 'absolute',
                      bottom: '-28px',
                      left: m.role === 'assistant' ? '0' : 'auto',
                      right: m.role === 'user' ? '0' : 'auto',
                      display: 'flex',
                      gap: '4px',
                      background: darkMode ? '#252542' : '#fff',
                      borderRadius: '8px',
                      padding: '4px',
                      boxShadow: darkMode ? '0 2px 8px rgba(0,0,0,0.3)' : '0 2px 8px rgba(0,0,0,0.1)',
                      border: `1px solid ${darkMode ? '#3d3d5c' : '#e5e7eb'}`,
                      zIndex: 10
                    }}>
                      <button
                        onClick={() => copyToClipboard(m.text, m.id)}
                        title="Copy to clipboard"
                        style={{
                          background: 'transparent',
                          border: 'none',
                          cursor: 'pointer',
                          padding: '4px 8px',
                          borderRadius: '4px',
                          display: 'flex',
                          alignItems: 'center',
                          gap: '4px',
                          fontSize: '12px',
                          color: copiedId === m.id ? '#16a34a' : (darkMode ? '#9ca3af' : '#6b7280'),
                          transition: 'all 0.2s'
                        }}
                        onMouseEnter={(e) => e.currentTarget.style.background = darkMode ? '#3d3d5c' : '#f3f4f6'}
                        onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
                      >
                        {copiedId === m.id ? (
                          <>
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                              <polyline points="20 6 9 17 4 12"></polyline>
                            </svg>
                            Copied!
                          </>
                        ) : (
                          <>
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                              <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
                              <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
                            </svg>
                            Copy
                          </>
                        )}
                      </button>
                    </div>
                  )}
                </div>
                {m.role === "user" && <img src={darkMode ? "/profile2.png" : "/profile.png"} alt="User" style={{ width: 36, height: 36, borderRadius: 8 }} />}
              </div>
            ))}
            {isLoading && (
              <div style={{ display: "flex", gap: 12, alignItems: "flex-start", marginBottom: 16 }}>
                <div style={{ 
                  background: theme.bubbleBg, 
                  padding: "12px 16px", 
                  borderRadius: 14, 
                  boxShadow: darkMode ? "0 2px 8px rgba(0,0,0,0.2)" : "0 4px 12px rgba(2,6,23,0.06)", 
                  color: theme.textMuted,
                  display: "flex",
                  alignItems: "center",
                  gap: "6px",
                  border: darkMode ? `1px solid ${theme.border}` : 'none'
                }}>
                  <span>Thinking</span>
                  <div style={{ 
                    display: "inline-flex", 
                    gap: "3px"
                  }}>
                    <div style={{ 
                      width: "5px", 
                      height: "5px", 
                      borderRadius: "50%", 
                      backgroundColor: "#2563eb",
                      animation: "bounce 1.4s ease-in-out infinite both",
                      animationDelay: "0s"
                    }}></div>
                    <div style={{ 
                      width: "5px", 
                      height: "5px", 
                      borderRadius: "50%", 
                      backgroundColor: "#2563eb",
                      animation: "bounce 1.4s ease-in-out infinite both",
                      animationDelay: "0.16s"
                    }}></div>
                    <div style={{ 
                      width: "5px", 
                      height: "5px", 
                      borderRadius: "50%", 
                      backgroundColor: "#2563eb",
                      animation: "bounce 1.4s ease-in-out infinite both",
                      animationDelay: "0.32s"
                    }}></div>
                  </div>
                </div>
              </div>
            )}
            <div ref={messageEnd} />
          </div>
        )}
      </main>

      {/* input */}
      <div className="input-bar-wrap" style={S.inputBarWrap}>
        <div style={S.inputBar}>
          <input
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                e.preventDefault();
                handleSend();
              }
            }}
            placeholder="Ask Gregory..."
            style={S.textInput}
            disabled={isLoading}
          />

          <button
            title="Upload file"
            style={{ ...S.circleBtn, background: darkMode ? "#3d3d5c" : "#f3f4f6", color: darkMode ? "#e5e5e5" : "#111827" }}
            onClick={() => document.getElementById("file-input")?.click()}
          >
            📎
            <input 
              id="file-input" 
              style={{ display: "none" }} 
              type="file" 
              onChange={handleUpload}
              accept=".pdf,.docx,.txt"
            />
          </button>

          <button
            title="Voice input"
            style={{ ...S.circleBtn, ...(listening ? S.micOn : S.micOff) }}
            onClick={startVoice}
          >
            {/* simple mic SVG */}
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ color: listening ? "#fff" : (darkMode ? "#e5e5e5" : "#111827") }}>
              <path d="M12 1v11"></path>
              <rect x="8" y="1" width="8" height="11" rx="4"></rect>
              <path d="M19 11v2a7 7 0 01-14 0v-2"></path>
              <line x1="12" y1="23" x2="12" y2="17"></line>
            </svg>
          </button>

          <button
            onClick={handleSend}
            disabled={!input.trim() || isLoading}
            style={{ ...S.circleBtn, background: "linear-gradient(90deg,#2563eb,#7c3aed)", color: "#fff" }}
          >
            ➤
          </button>
        </div>
        
        {/* File Upload Status - Small indicator */}
        {uploadName && (
          <div style={{ 
            position: 'fixed', 
            bottom: '60px', 
            right: '20px',
            background: 'rgba(16, 185, 129, 0.9)',
            color: 'white',
            padding: '8px 12px',
            borderRadius: '20px',
            fontSize: '12px',
            fontWeight: '500',
            boxShadow: '0 2px 8px rgba(16, 185, 129, 0.2)',
            zIndex: 1000,
            display: 'flex',
            alignItems: 'center',
            gap: '6px',
            maxWidth: '200px',
            overflow: 'hidden'
          }}>
            <span style={{ fontSize: '10px' }}>📎</span>
            <span style={{ 
              whiteSpace: 'nowrap', 
              overflow: 'hidden', 
              textOverflow: 'ellipsis' 
            }}>
              {uploadName}
            </span>
            <button 
              onClick={() => {
                setUploadName(null);
                try { localStorage.removeItem('lastUploadName'); } catch {}
              }}
              style={{
                background: 'rgba(255,255,255,0.3)',
                border: 'none',
                color: 'white',
                borderRadius: '50%',
                width: '16px',
                height: '16px',
                cursor: 'pointer',
                fontSize: '10px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center'
              }}
            >
              ×
            </button>
          </div>
        )}

        {uploadToast && (
          <div style={{
            position: 'fixed',
            right: '20px',
            bottom: '120px',
            background: '#111827',
            color: '#fff',
            padding: '10px 14px',
            borderRadius: 10,
            fontSize: 13,
            boxShadow: '0 10px 24px rgba(15,23,42,0.18)',
            zIndex: 1100,
            maxWidth: 320
          }}>
            ✅ {uploadToast}
          </div>
        )}
      </div>
      
      {/* Disclaimer at bottom */}
      <div className="disclaimer-mobile" style={{
        position: 'fixed',
        left: 0,
        right: 0,
        bottom: 0,
        background: darkMode ? '#16162a' : '#fff',
        padding: '12px 24px',
        fontSize: '12px',
        color: theme.textMuted,
        textAlign: 'center',
        borderTop: darkMode ? '1px solid #2d2d44' : 'none',
        zIndex: 1001
      }}>
        Gregory AI can make mistakes. Check important info.
      </div>
    </div>
    </>
  );
}
