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

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

export default function HomeNoTailwind() {
  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 messageEnd = useRef<HTMLDivElement | null>(null);

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

  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>`
      );
  }

  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:", { trimmed, isLoading });
      return;
    }
    
    addUserMessage(trimmed);
    setInput("");
    setIsLoading(true);
    console.log("Starting API request...");

    try {
      // Try streaming first
      console.log("Attempting streaming API call...");
      // Smart detection: only use file context if question seems related to the document
      const isFileRelatedQuery = uploadName && (
        trimmed.toLowerCase().includes('document') ||
        trimmed.toLowerCase().includes('file') ||
        trimmed.toLowerCase().includes('pdf') ||
        trimmed.toLowerCase().includes('fine') ||
        trimmed.toLowerCase().includes('amount') ||
        trimmed.toLowerCase().includes('total') ||
        trimmed.toLowerCase().includes('invoice') ||
        trimmed.toLowerCase().includes('price') ||
        trimmed.toLowerCase().includes('cost') ||
        trimmed.toLowerCase().includes('what') ||
        trimmed.toLowerCase().includes('how much') ||
        trimmed.toLowerCase().includes('show') ||
        trimmed.toLowerCase().includes('find') ||
        trimmed.toLowerCase().includes('content') ||
        trimmed.toLowerCase().includes('text')
      );

      // 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 || !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.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("");
          break;
        }
        const chunk = decoder.decode(value);
        console.log("Received chunk:", chunk);
        
        // Stream character by character for smooth effect
        for (let i = 0; i < chunk.length; i++) {
          assistantText += chunk[i];
          setMessages((prev) => prev.map((m) => (m.id === assistantId ? { ...m, text: assistantText } : m)));
          // Faster streaming - reduced delay from 20ms to 8ms
          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 });
      const j = await r.json();
      if (j.ok) {
        console.log("File uploaded successfully:", j);
        // Show a more user-friendly message
        const snippet = j.text_snippet ? j.text_snippet.substring(0, 100) + "..." : "File content processed";
        alert(`✅ File "${f.name}" uploaded successfully!\n\nPreview: ${snippet}\n\nYou can now ask questions about this file.`);
      } else {
        console.error("Upload failed:", j);
        alert("❌ Upload failed: " + (j.error || "Unknown error"));
      }
    } catch (err) {
      console.error(err);
      alert("Upload failed");
    }
  }

  // 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: 220, 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: 240 + 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;
          }
        }
        
        /* Mobile responsive styles */
        @media (max-width: 768px) {
          .sidebar {
            display: none !important;
          }
          .main-content {
            margin-left: 0 !important;
          }
          .input-bar-wrap {
            left: 24px !important;
          }
          .disclaimer-mobile {
            left: 0 !important;
          }
        }
      `}</style>
      <div style={S.page}>
        <aside className="sidebar" 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>
        <button 
          onClick={() => {
            setMessages([]);
            setInput("");
            setUploadName(null);
            setIsLoading(false);
          }}
          style={{ marginBottom: 12, padding: "10px 12px", borderRadius: 10, border: "1px solid #e6e6e6", background: "#fff", cursor: "pointer" }}
        >
          + New Chat
        </button>
        {/* <div style={{ marginTop: 18, fontSize: 12, color: "#6b7280", fontWeight: 700 }}>RECENT</div> */}
        {/* <ul style={{ marginTop: 8, paddingLeft: 12 }}>
          <li style={{ margin: "8px 0" }}>Building an AI Chatbot</li>
          <li style={{ margin: "8px 0" }}>Random String</li>
          <li style={{ margin: "8px 0" }}>Lola Model Firearms</li>
        </ul> */}
      </aside>

      <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)}
            onKeyPress={(e) => e.key === "Enter" && 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>
        )}
      </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>
    </>
  );
}
