"use client"
import { useState, useRef, useEffect, Fragment, forwardRef, useImperativeHandle, useCallback } from "react"
import { Send, Bot, User, AlertCircle, Sparkles, Lightbulb, Target, MessageSquare, 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 blocks: { type: "code" | "text"; content: string }[] = []
const regex = /```(\w*)\n?([\s\S]*?)```/g
let last = 0
let match: RegExpExecArray | null
while ((match = regex.exec(text)) !== null) {
if (match.index > last) {
blocks.push({ type: "text", content: text.slice(last, match.index) })
}
blocks.push({ type: "code", content: match[2].trim() })
last = match.index + match[0].length
}
if (last < text.length) {
blocks.push({ type: "text", content: text.slice(last) })
}
if (blocks.length) return blocks
return [{ type: "text" as const, content: text }]
}
function formatBullets(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
}
}
function TypingDots() {
return (
)
}
const suggestions = [
{ icon: Terminal, label: "Lists", query: "Show me available job lists and categories" },
{ icon: Target, label: "Leads", query: "Pull recent leads" },
{ icon: Lightbulb, label: "Tips", query: "Give me general sales tips" },
{ icon: MessageSquare, label: "Objections", query: "How do I handle common objections?" },
]
interface AIChatProps {
onMessageSent?: (msg: string) => void
}
export const AIChat = forwardRef<{ fillInput: (text: string) => void }, AIChatProps>(({ 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)
},
}), [])
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/health")
if (res.ok) {
setBootState("ready")
return
}
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])
useEffect(() => {
if (textareaRef.current) {
textareaRef.current.style.height = "auto"
textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, 120)}px`
}
}, [input])
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 (
)
}
const hasMessages = messages.length > 0
return (
{messages.map((msg, i) => (
{msg.role === "assistant" ? (
{formatContent(msg.content).map((block, bi) =>
block.type === "code" ? (
{block.content}
) : (
{formatBullets(block.content)}
)
)}
AI Assistant
) : (
{msg.gif ? (

) : (
{msg.content}
)}
)}
))}
{loading && (
)}
{!hasMessages && (
{suggestions.map((s, i) => (
))}
)}
{error && (
)}
{showGifPicker && setShowGifPicker(false)} />}
Shift + Enter for new line
{input.length} / 2000
)
})
AIChat.displayName = "AIChat"