// 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);

  // 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();
    } else {
      setConversations([]);
    }
  }, [isAuthed]);

  // 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);
        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; color: #1f2937;">$1</h4>')
      .replace(/^## (.*$)/gm, '<h3 style="font-size: 1.2em; font-weight: 600; margin: 14px 0 8px 0; color: #1f2937;">$1</h3>')
      .replace(/^# (.*$)/gm, '<h2 style="font-size: 1.3em; font-weight: 700; margin: 16px 0 10px 0; color: #1f2937;">$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 or summarization queries
      const q = trimmed.toLowerCase();
      const summaryKeywords = ['summarize','summary','summarise','tldr','tl;dr','overview','key points','highlights','brief','gist','outline'];
      const docKeywords = ['document','file','pdf','fine','amount','total','invoice','price','cost','what','how much','show','find','content','text'];
      const isFileRelatedQuery = !!uploadName && (
        summaryKeywords.some(k => q.includes(k)) ||
        docKeywords.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'));
    }
  }

  // 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: "linear-gradient(180deg,#f8fafc,#f1f5f9)" },
    sidebar: { width: 280, padding: 16, borderRight: "1px solid #e6e6e6", boxSizing: "border-box", background: "rgba(255,255,255,0.8)", 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 },
    main: { flex: 1, padding: "28px 28px 160px 28px", boxSizing: "border-box", position: "relative", background: "linear-gradient(180deg,#f8fafc,#f1f5f9)", minHeight: "100vh" },
    centerHero: { height: "70vh", display: "flex", alignItems: "center", justifyContent: "center", flexDirection: "column", gap: 12, textAlign: "center" },
    cardsGrid: { display: "grid", gridTemplateColumns: "repeat(2,160px)", gap: 12 },
    card: { padding: 16, borderRadius: 12, background: "#fff", boxShadow: "0 6px 18px rgba(15,23,42,0.06)", cursor: "pointer", textAlign: "left" },
    chatWindow: { maxWidth: 800, margin: "0 auto", paddingBottom: "10px", paddingTop: "20px" },
    msgRow: { display: "flex", gap: 12, alignItems: "flex-start", marginBottom: 16 },
    assistantBubble: { background: "#fff", padding: "12px 16px", borderRadius: 14, boxShadow: "0 4px 12px rgba(2,6,23,0.06)", color: "#0f172a", maxWidth: "70%" },
    userBubble: { background: "linear-gradient(90deg,#2563eb,#7c3aed)", padding: "12px 16px", borderRadius: 14, color: "#fff", maxWidth: "70%" },
    inputBarWrap: { position: "fixed", left: 280 + 24, right: 24, bottom: 68, display: "flex", justifyContent: "center", zIndex: 1000 },
    inputBar: { maxWidth: 800, width: "100%", display: "flex", gap: 8, alignItems: "center", padding: "10px 12px", borderRadius: 999, background: "rgba(255,255,255,0.98)", boxShadow: "0 8px 30px rgba(2,6,23,0.12)", border: "1px solid rgba(0,0,0,0.05)" },
    textInput: { flex: 1, border: "none", outline: "none", fontSize: 16, background: "transparent" },
    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: "#f3f4f6", color: "#111827" }
  };

  return (
    <>
      <Head>
        <title>Gregory AI Agent</title>
        <meta name="description" content="Gregory AI Agent - 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: linear-gradient(180deg,#f8fafc,#f1f5f9); 
          min-height: 100vh; 
        }
        html { 
          background: 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: #fff;
            border: 1px solid #e5e7eb;
            box-shadow: 0 8px 20px rgba(0,0,0,0.08);
            display: inline-flex;
            align-items: center; justify-content: center;
            color: #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="/logo.png" alt="Gregory AI Agent" style={{ width: 44, height: 44, borderRadius: 12 }} />
          <div style={{ fontWeight: 700, fontSize: 18 }}>Gregory AI</div>
        </div>
        {/* Auth Box: show links only when logged out; name and sign out when logged in */}
        {!isAuthed ? (
          <div style={{ padding: 12, background: '#fff', border: '1px solid #e6e6e6', borderRadius: 12, marginBottom: 12 }}>
            <div style={{ fontWeight: 600, fontSize: 14, color: '#111827', 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:'1px solid #e6e6e6', background:'#2563eb', color:'#fff', cursor:'pointer' }}
              >Sign in</button>
              <button 
                onClick={() => router.push('/auth/signup')}
                style={{ flex:1, padding:'10px 12px', borderRadius:10, border:'1px solid #e6e6e6', background:'#10b981', color:'#fff', cursor:'pointer' }}
              >Sign up</button>
            </div>
          </div>
        ) : (
          <div
            style={{
              padding: 14,
              background: 'linear-gradient(180deg,#ffffff,#f9fafb)',
              border: '1px solid #e5e7eb',
              borderRadius: 14,
              marginBottom: 12,
              boxShadow: '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 #e5e7eb' }} />
              ) : (
                <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: '#6b7280', margin: 0, lineHeight: 1, whiteSpace: 'nowrap' }}>Signed in</div>
                <div style={{ fontSize: 14, fontWeight: 700, color: '#111827', marginTop: 2, lineHeight: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 180 }}>{session?.user?.name || session?.user?.email || 'User'}</div>
              </div>
            </div>

            <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: '1px solid transparent',
                  background: 'linear-gradient(90deg,#2563eb,#7c3aed)',
                  color: '#fff',
                  cursor: 'pointer',
                  boxShadow: '0 8px 18px rgba(37,99,235,0.25)',
                  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 #fee2e2',
                  background: '#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 = '#fff';
                  (e.currentTarget as HTMLButtonElement).style.borderColor = '#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: "#6b7280", 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 ? "#f3f4f6" : "transparent",
                    fontSize: 14,
                    color: "#374151",
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                    transition: "background 0.2s"
                  }}
                  onMouseEnter={(e) => {
                    if (conv.id !== currentConversationId) {
                      e.currentTarget.style.background = "#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: "#0f172a", fontWeight: 700, marginBottom: 8 }}>Gregory AI Agent</h1>
            <h2 style={{ margin: 0, fontSize: 24, color: "#374151", fontWeight: 500 }}>Hello</h2>
            <p style={{ color: "#6b7280", marginTop: 6 }}>What would you like to explore today?</p>
            <div style={S.cardsGrid}>
              {[
                { label: "Baseball 🏏", query: "Latest Baseball 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 = "0 8px 25px rgba(15,23,42,0.12)";
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.transform = "translateY(0px)";
                    e.currentTarget.style.boxShadow = "0 6px 18px rgba(15,23,42,0.06)";
                  }}
                >
                  {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" }}>
                {m.role === "assistant" && <img src="/logo.png" alt="Gregory AI" style={{ width: 36, height: 36, borderRadius: 8 }} />}
                <div 
                  style={m.role === "assistant" ? S.assistantBubble : S.userBubble}
                  dangerouslySetInnerHTML={{
                    __html: m.role === "assistant" ? formatMessage(m.text) : m.text
                  }}
                />
                {m.role === "user" && <img src="/profile.png" alt="User" style={{ width: 36, height: 36, borderRadius: 8 }} />}
              </div>
            ))}
            {isLoading && (
              <div style={{ display: "flex", gap: 12, alignItems: "flex-start", marginBottom: 16 }}>
                <img src="/logo.png" alt="Gregory AI" style={{ width: 36, height: 36, borderRadius: 8 }} />
                <div style={{ 
                  background: "#fff", 
                  padding: "12px 16px", 
                  borderRadius: 14, 
                  boxShadow: "0 4px 12px rgba(2,6,23,0.06)", 
                  color: "#6b7280",
                  display: "flex",
                  alignItems: "center",
                  gap: "4px"
                }}>
                  <span>Thinking</span>
                  <div style={{ 
                    display: "inline-flex", 
                    gap: "2px",
                    animation: "pulse 1.5s ease-in-out infinite"
                  }}>
                    <div style={{ 
                      width: "4px", 
                      height: "4px", 
                      borderRadius: "50%", 
                      backgroundColor: "#6b7280",
                      animation: "bounce 1.4s ease-in-out infinite both",
                      animationDelay: "0s"
                    }}></div>
                    <div style={{ 
                      width: "4px", 
                      height: "4px", 
                      borderRadius: "50%", 
                      backgroundColor: "#6b7280",
                      animation: "bounce 1.4s ease-in-out infinite both",
                      animationDelay: "0.16s"
                    }}></div>
                    <div style={{ 
                      width: "4px", 
                      height: "4px", 
                      borderRadius: "50%", 
                      backgroundColor: "#6b7280",
                      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: "#f3f4f6", color: "#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" : "#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)}
              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: '#fff',
        padding: '12px 24px',
        fontSize: '12px',
        color: '#6b7280',
        textAlign: 'center',
        // borderTop: '1px solid #e5e7eb',
        zIndex: 1001
      }}>
        Gregory AI Agent can make mistakes. Check important info.
      </div>
    </div>
    </>
  );
}
