"use client" import { useState, useRef, useEffect, Fragment, forwardRef, useImperativeHandle, useCallback } from "react" import { Bot, Terminal } from "lucide-react" 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 } interface AIChatProps { onMessageSent?: (msg: string) => void } const quickActions = [ { icon: "✉️", iconBg: "bg-[#f97316]/10", iconColor: "text-[#f97316]", title: "Cold Email Template", desc: "Generate targeted outreach emails", prompt: "Write a cold email template for a Software Developer" }, { icon: "🛡️", iconBg: "bg-[#3b82f6]/10", iconColor: "text-[#3b82f6]", title: "Handle Objections", desc: "Get scripts for common objections", prompt: "Give me objection handling scripts for sales" }, { icon: "🎯", iconBg: "bg-[#8b5cf6]/10", iconColor: "text-[#8b5cf6]", title: "Target Industry", desc: "Find leads in specific industries", prompt: "How do I target leads in the tech industry" }, { icon: "📋", iconBg: "bg-[#22c55e]/10", iconColor: "text-[#22c55e]", title: "Build Lead List", desc: "Strategies to grow your pipeline", prompt: "Help me build a lead list strategy" }, { icon: "📞", iconBg: "bg-[#f97316]/10", iconColor: "text-[#f97316]", title: "Call Scripts", desc: "Proven phone sales scripts", prompt: "Give me a cold call script for outreach" }, { icon: "📊", iconBg: "bg-[#ec4899]/10", iconColor: "text-[#ec4899]", title: "Sales Strategy", desc: "Industry specific sales tactics", prompt: "What sales strategies work best per industry" }, ] const commandPills = [ { icon: "📋", label: "Lists", prompt: "lists" }, { icon: "👥", label: "Leads", prompt: "leads" }, { icon: "💡", label: "Tips", prompt: "Give me some sales tips" }, { icon: "✉️", label: "Templates", prompt: "Show me email templates" }, ] 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 messagesEndRef = useRef(null) const textareaRef = useRef(null) const hasUserMessage = messages.some(m => m.role === "user") 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 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(() => { 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" }, []) const handleQuickAction = useCallback((prompt: string) => { setInput(prompt) setTimeout(() => sendMessage(prompt), 50) }, [sendMessage]) const handleCommandPill = useCallback((prompt: string) => { setInput(prompt) setTimeout(() => sendMessage(prompt), 50) }, [sendMessage]) 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.

{quickActions.map((action, i) => (
handleQuickAction(action.prompt)} className="float-in bg-[#1a1d2e] hover:bg-[#1f2437] rounded-xl p-4 border border-[#ffffff0a] hover:border-[#f97316]/30 cursor-pointer transition-all duration-200 hover:shadow-[0_4px_20px_rgba(249,115,22,0.1)] hover:-translate-y-0.5" style={{ animationDelay: `${0.1 + i * 0.05}s` }} >
{action.icon}

{action.title}

{action.desc}

))}
{commandPills.map((pill, i) => (
handleCommandPill(pill.prompt)} className="bg-[#1a1d2e] border border-[#ffffff0f] hover:border-[#f97316]/40 hover:bg-[#1f2437] rounded-full px-4 py-2 text-xs text-[#9ca3af] hover:text-[#f97316] transition-all duration-200 cursor-pointer flex items-center gap-1.5" > {pill.icon} {pill.label}
))}