"use client" import { useState, useRef, useEffect, Fragment, forwardRef, useImperativeHandle, useCallback } from "react" import { Bot, Terminal } from "lucide-react" import { GifPicker } from "./gif-picker" function linkifyText(text: string) { const urlRegex = /(https?:\/\/[^\s<]+[^\s<.,;:!?)\]}>])/ const parts = text.split(urlRegex) return parts.map((part, i) => { if (part.startsWith("http://") || part.startsWith("https://")) { return {part} } return {part} }) } function formatContent(text: string) { const lines = text.split("\n") return lines.map((line, i) => { const trimmed = line.trim() if (trimmed.startsWith("•") || trimmed.startsWith("-")) { const content = trimmed.replace(/^[•\-]\s*/, "") return (
{linkifyText(content)}
) } if (line === "") return
return

{linkifyText(line)}

}) } interface ChatMessage { role: "user" | "assistant" content: string gif?: { url: string previewUrl: string title: string } } interface AIChatProps { onMessageSent?: (msg: string) => void } export interface AIChatHandle { fillInput: (text: string) => void addAssistantMessage: (content: string) => void } export const AIChat = forwardRef(({ onMessageSent }, ref) => { const [messages, setMessages] = useState([]) const [input, setInput] = useState("") const [loading, setLoading] = useState(false) const [error, setError] = useState("") const [bootState, setBootState] = useState<"booting" | "ready" | "error">("booting") const [showGifPicker, setShowGifPicker] = useState(false) const messagesEndRef = useRef(null) const textareaRef = useRef(null) const containerRef = useRef(null) const hasUserMessage = messages.some(m => m.role === "user") const loadedFromStorage = useRef(false) useImperativeHandle(ref, () => ({ fillInput(text: string) { setInput(text) setTimeout(() => textareaRef.current?.focus(), 50) }, addAssistantMessage(content: string) { setMessages((prev) => { if (!prev.some((m) => m.role === "user")) { return [ { role: "user", content: "Search Facebook" }, { role: "assistant", content }, ] } return [...prev, { role: "assistant", content }] }) }, }), []) const handleGifSelect = useCallback((gif: { url: string; previewUrl: string; title: string }) => { setMessages((prev) => [...prev, { role: "user", content: gif.title || "Sent a GIF", gif }]) setShowGifPicker(false) }, []) useEffect(() => { if (showGifPicker) { const handler = (e: MouseEvent) => { if (containerRef.current && !containerRef.current.contains(e.target as Node)) { setShowGifPicker(false) } } document.addEventListener("mousedown", handler) return () => document.removeEventListener("mousedown", handler) } }, [showGifPicker]) useEffect(() => { const saved = localStorage.getItem("ai-chat-messages") if (saved) { try { const parsed = JSON.parse(saved) if (Array.isArray(parsed) && parsed.length > 0) { setMessages(parsed) loadedFromStorage.current = true } } catch {} } else { loadedFromStorage.current = false } }, []) useEffect(() => { if (messages.length > 0) { localStorage.setItem("ai-chat-messages", JSON.stringify(messages)) } }, [messages]) const checkServer = useCallback(async () => { try { const res = await fetch("/api/ai/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message: "ping" }), }) if (res.status !== 503) { setBootState("ready") } else { setTimeout(checkServer, 2000) } } catch { setTimeout(checkServer, 2000) } }, []) useEffect(() => { if (loadedFromStorage.current) return fetch("/api/ai/jobs") .then((r) => r.json()) .then((data) => { if (data.jobs?.length) { const names = data.jobs.map((j: { job_title: string }) => j.job_title) setMessages([ { role: "assistant", content: `Hi! I'm your Sales AI Assistant. I can help with tips for targeting:\n\n${names.map((n: string) => `• ${n}`).join("\n")}\n\nWhat would you like to know?`, }, ]) } else { setMessages([ { role: "assistant", content: "Hi! I'm your Sales AI Assistant. Ask me anything about sales strategies and prospect targeting.", }, ]) } }) .catch(() => { setMessages([ { role: "assistant", content: "Hi! I'm your Sales AI Assistant. Ask me anything about sales strategies and prospect targeting.", }, ]) }) checkServer() }, [checkServer]) useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }) }, [messages]) const sendMessage = useCallback(async (text?: string) => { const msg = (text || input).trim() if (!msg || loading) return setInput("") setError("") onMessageSent?.(msg) setMessages((prev) => [...prev, { role: "user", content: msg }]) setLoading(true) try { const res = await fetch("/api/ai/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message: msg }), }) if (!res.ok) { const data = await res.json().catch(() => ({})) throw new Error(data.error || `Error ${res.status}`) } const data = await res.json() setMessages((prev) => [...prev, { role: "assistant", content: data.response }]) } catch (err) { const errMsg = err instanceof Error ? err.message : "AI service unavailable" setError(errMsg) setMessages((prev) => [ ...prev, { role: "assistant", content: `⚠️ Error: ${errMsg}. Make sure Ollama is running with the model loaded.` }, ]) } finally { setLoading(false) } }, [input, loading, onMessageSent]) const handleKeyDown = useCallback((e: React.KeyboardEvent) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault() sendMessage() } }, [sendMessage]) const handleTextareaInput = useCallback((e: React.FormEvent) => { const t = e.target as HTMLTextAreaElement t.style.height = "auto" t.style.height = t.scrollHeight + "px" }, []) if (bootState === "booting") { return (

Servers booting...

) } if (bootState === "ready" && !hasUserMessage) { return (

What can I help you with?

Your AI sales assistant is ready. Choose a quick action or type your question below.

{showGifPicker && setShowGifPicker(false)} />}