Getting the 10 syncs and adding my AI that works but has issues

This commit is contained in:
Ace
2026-07-01 12:16:22 +02:00
33 changed files with 838 additions and 481 deletions
+104 -96
View File
@@ -2,13 +2,14 @@
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 <a key={i} href={part} target="_blank" rel="noopener noreferrer" className="underline text-[#f97316] hover:text-[#f97316]/80">{part}</a>
return <a key={i} href={part} target="_blank" rel="noopener noreferrer" className="underline text-primary hover:text-primary/80">{part}</a>
}
return <Fragment key={i}>{part}</Fragment>
})
@@ -22,7 +23,7 @@ function formatContent(text: string) {
const content = trimmed.replace(/^[•\-]\s*/, "")
return (
<div key={i} className="flex items-start gap-2.5 my-1.5">
<span className="w-1.5 h-1.5 bg-[#f97316] rounded-sm inline-block mt-2 flex-shrink-0" />
<span className="w-1.5 h-1.5 bg-primary rounded-sm inline-block mt-2 flex-shrink-0" />
<span>{linkifyText(content)}</span>
</div>
)
@@ -35,27 +36,17 @@ function formatContent(text: string) {
interface ChatMessage {
role: "user" | "assistant"
content: string
gif?: {
url: string
previewUrl: string
title: 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
@@ -68,9 +59,12 @@ export const AIChat = forwardRef<AIChatHandle, AIChatProps>(({ onMessageSent },
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<HTMLDivElement>(null)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
const hasUserMessage = messages.some(m => m.role === "user")
const loadedFromStorage = useRef(false)
useImperativeHandle(ref, () => ({
fillInput(text: string) {
@@ -90,6 +84,44 @@ export const AIChat = forwardRef<AIChatHandle, AIChatProps>(({ onMessageSent },
},
}), [])
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", {
@@ -108,6 +140,7 @@ export const AIChat = forwardRef<AIChatHandle, AIChatProps>(({ onMessageSent },
}, [])
useEffect(() => {
if (loadedFromStorage.current) return
fetch("/api/ai/jobs")
.then((r) => r.json())
.then((data) => {
@@ -192,34 +225,24 @@ export const AIChat = forwardRef<AIChatHandle, AIChatProps>(({ onMessageSent },
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 (
<div className="flex items-center justify-center h-full">
<div className="flex flex-col items-center gap-5">
<p className="text-sm text-[#6b7280] animate-pulse">Servers booting...</p>
<div className="h-[56px] w-[110px] bg-[#1a1d2e] border border-[#ffffff0f] rounded-xl flex items-center justify-center overflow-hidden">
<p className="text-sm text-muted-foreground animate-pulse">Servers booting...</p>
<div className="h-[56px] w-[110px] bg-card border border-border rounded-xl flex items-center justify-center overflow-hidden">
<div className="robot-walk relative">
<svg width="40" height="36" viewBox="0 0 40 36" fill="none">
<rect x="10" y="2" width="20" height="16" rx="3" fill="#f97316" opacity="0.9"/>
<rect x="6" y="6" width="6" height="2" rx="1" className="robot-arm-l" fill="#f97316" opacity="0.7"/>
<rect x="28" y="6" width="6" height="2" rx="1" className="robot-arm-r" fill="#f97316" opacity="0.7"/>
<rect x="14" y="5" width="4" height="4" rx="1" fill="#0f1117"/>
<rect x="22" y="5" width="4" height="4" rx="1" fill="#0f1117"/>
<circle cx="16" cy="7" r="1.5" className="robot-eye" fill="#f97316"/>
<circle cx="24" cy="7" r="1.5" className="robot-eye" fill="#f97316"/>
<rect x="17" y="10" width="6" height="2" rx="1" fill="#0f1117"/>
<rect x="12" y="18" width="5" height="10" rx="2" className="robot-leg-l" fill="#f97316" opacity="0.8"/>
<rect x="23" y="18" width="5" height="10" rx="2" className="robot-leg-r" fill="#f97316" opacity="0.8"/>
<rect x="10" y="2" width="20" height="16" rx="3" fill="hsl(var(--primary))" opacity="0.9"/>
<rect x="6" y="6" width="6" height="2" rx="1" className="robot-arm-l" fill="hsl(var(--primary))" opacity="0.7"/>
<rect x="28" y="6" width="6" height="2" rx="1" className="robot-arm-r" fill="hsl(var(--primary))" opacity="0.7"/>
<rect x="14" y="5" width="4" height="4" rx="1" style={{fill: "hsl(var(--background))"}}/>
<rect x="22" y="5" width="4" height="4" rx="1" style={{fill: "hsl(var(--background))"}}/>
<circle cx="16" cy="7" r="1.5" className="robot-eye" fill="hsl(var(--primary))"/>
<circle cx="24" cy="7" r="1.5" className="robot-eye" fill="hsl(var(--primary))"/>
<rect x="17" y="10" width="6" height="2" rx="1" style={{fill: "hsl(var(--background))"}}/>
<rect x="12" y="18" width="5" height="10" rx="2" className="robot-leg-l" fill="hsl(var(--primary))" opacity="0.8"/>
<rect x="23" y="18" width="5" height="10" rx="2" className="robot-leg-r" fill="hsl(var(--primary))" opacity="0.8"/>
</svg>
</div>
</div>
@@ -230,48 +253,23 @@ export const AIChat = forwardRef<AIChatHandle, AIChatProps>(({ onMessageSent },
if (bootState === "ready" && !hasUserMessage) {
return (
<div className="flex-1 flex flex-col overflow-y-auto" style={{ backgroundImage: "radial-gradient(circle, #ffffff08 1px, transparent 1px)", backgroundSize: "24px 24px" }}>
<div className="flex-1 flex flex-col overflow-y-auto" style={{ backgroundImage: "radial-gradient(circle, hsl(var(--border)) 1px, transparent 1px)", backgroundSize: "24px 24px" }}>
<div className="flex-1 flex items-center justify-center">
<div className="max-w-lg mx-auto pt-12 pb-6 px-4">
<div className="max-w-lg mx-auto px-4">
<div className="float-in">
<div className="w-16 h-16 rounded-2xl mx-auto mb-6 bg-gradient-to-br from-[#f97316] to-[#ea580c] flex items-center justify-center shadow-[0_0_40px_rgba(249,115,22,0.3)]">
<div className="w-16 h-16 rounded-2xl mx-auto mb-6 bg-gradient-to-br from-primary to-primary flex items-center justify-center shadow-[0_0_40px_hsl(var(--primary)_/_0.3)]">
<Bot className="h-8 w-8 text-white" />
</div>
<h2 className="text-white font-bold text-2xl text-center mb-2">What can I help you with?</h2>
<p className="text-[#6b7280] text-sm text-center mb-8 leading-relaxed">Your AI sales assistant is ready. Choose a quick action or type your question below.</p>
</div>
<div className="grid grid-cols-2 gap-3">
{quickActions.map((action, i) => (
<div
key={i}
onClick={() => 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` }}
>
<div className={`w-9 h-9 rounded-lg ${action.iconBg} ${action.iconColor} flex items-center justify-center text-lg`}>{action.icon}</div>
<h3 className="text-white text-sm font-medium mt-3">{action.title}</h3>
<p className="text-[#6b7280] text-xs mt-1">{action.desc}</p>
</div>
))}
</div>
<div className="flex gap-2 justify-center mt-6 flex-wrap">
{commandPills.map((pill, i) => (
<div
key={i}
onClick={() => 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"
>
<span>{pill.icon}</span>
<span>{pill.label}</span>
</div>
))}
<h2 className="text-foreground font-bold text-2xl text-center mb-2">What can I help you with?</h2>
<p className="text-muted-foreground text-sm text-center leading-relaxed">Your AI sales assistant is ready. Choose a quick action or type your question below.</p>
</div>
</div>
</div>
<div className="sticky bottom-0 bg-[#0f1117]/95 backdrop-blur-md border-t border-[#ffffff08] px-4 py-4">
<div className="sticky bottom-0 bg-background/95 backdrop-blur-md px-4 py-4">
<div className="max-w-3xl mx-auto">
<div className="bg-[#1a1d2e] rounded-2xl border border-[#ffffff0a] focus-within:border-[#f97316]/40 focus-within:shadow-[0_0_20px_rgba(249,115,22,0.08)] transition-all duration-200 flex items-end gap-3 px-4 py-3">
<button type="button" className="w-8 h-8 rounded-lg text-[#4b5563] hover:text-[#f97316] hover:bg-[#ffffff08] flex items-center justify-center transition-colors duration-200 flex-shrink-0 text-lg">📎</button>
<div className="bg-card rounded-2xl border border-border focus-within:border-primary/40 focus-within:shadow-[0_0_20px_hsl(var(--primary)_/_0.08)] transition-all duration-200 flex items-end gap-3 px-4 py-3 relative" ref={containerRef}>
<button type="button" className="w-8 h-8 rounded-lg text-muted-foreground hover:text-primary hover:bg-muted/50 flex items-center justify-center transition-colors duration-200 flex-shrink-0 text-[11px] font-semibold tracking-wide" onClick={() => setShowGifPicker((v) => !v)}>GIF</button>
{showGifPicker && <GifPicker onSelect={handleGifSelect} onClose={() => setShowGifPicker(false)} />}
<textarea
ref={textareaRef}
value={input}
@@ -280,20 +278,20 @@ export const AIChat = forwardRef<AIChatHandle, AIChatProps>(({ onMessageSent },
onKeyDown={handleKeyDown}
placeholder="Ask for sales tips..."
rows={1}
className="bg-transparent flex-1 text-[#e5e7eb] text-sm placeholder-[#4b5563] resize-none outline-none min-h-[24px] max-h-[200px] overflow-y-auto leading-6"
className="bg-transparent flex-1 text-foreground text-sm placeholder-muted-foreground resize-none outline-none min-h-[24px] max-h-[200px] overflow-y-auto leading-6"
/>
<button
type="button"
onClick={() => sendMessage()}
disabled={!input.trim()}
className={`w-9 h-9 rounded-xl flex-shrink-0 bg-gradient-to-br from-[#f97316] to-[#ea580c] flex items-center justify-center text-white transition-all duration-200 ${input.trim() ? "hover:shadow-[0_0_20px_rgba(249,115,22,0.4)] hover:scale-105 active:scale-95" : "opacity-40 cursor-not-allowed"}`}
className={`w-9 h-9 rounded-xl flex-shrink-0 bg-gradient-to-br from-primary to-primary flex items-center justify-center text-white transition-all duration-200 ${input.trim() ? "hover:shadow-[0_0_20px_hsl(var(--primary)_/_0.4)] hover:scale-105 active:scale-95" : "opacity-40 cursor-not-allowed"}`}
>
</button>
</div>
<div className="flex justify-between items-center mt-2 px-1">
<span className="text-[#374151] text-[10px]">Shift + Enter for new line</span>
<span className="text-[#374151] text-[10px]">{input.length} / 2000</span>
<span className="text-muted-foreground text-[10px]">Shift + Enter for new line</span>
<span className="text-muted-foreground text-[10px]">{input.length} / 2000</span>
</div>
</div>
</div>
@@ -303,27 +301,36 @@ export const AIChat = forwardRef<AIChatHandle, AIChatProps>(({ onMessageSent },
return (
<div className="flex-1 flex flex-col min-h-0">
<div className="flex-1 overflow-y-auto px-4 py-6" style={{ backgroundImage: "radial-gradient(circle, #ffffff08 1px, transparent 1px)", backgroundSize: "24px 24px" }}>
<div className="flex-1 overflow-y-auto px-4 py-6" style={{ backgroundImage: "radial-gradient(circle, hsl(var(--border)) 1px, transparent 1px)", backgroundSize: "24px 24px" }}>
<div className="max-w-3xl mx-auto space-y-6">
{messages.map((msg, i) => (
<div key={i}>
{msg.role === "assistant" ? (
<div className="flex gap-3 items-start">
<div className="w-8 h-8 rounded-lg bg-gradient-to-br from-[#f97316] to-[#ea580c] flex items-center justify-center text-white text-sm flex-shrink-0">
<div className="w-8 h-8 rounded-lg bg-gradient-to-br from-primary to-primary flex items-center justify-center text-white text-sm flex-shrink-0">
<Bot className="h-4 w-4" />
</div>
<div className="flex-1 min-w-0">
<div className="bg-[#1a1d2e] rounded-2xl rounded-tl-sm border border-[#ffffff08] border-l-2 border-l-[#f97316] px-5 py-4 max-w-[85%]">
<div className="text-[#e5e7eb] text-sm leading-7 whitespace-pre-wrap">{formatContent(msg.content)}</div>
<div className="bg-card rounded-2xl rounded-tl-sm border border-border border-l-2 border-l-primary px-5 py-4 max-w-[85%]">
<div className="text-foreground text-sm leading-7 whitespace-pre-wrap">{formatContent(msg.content)}</div>
</div>
<div className="text-[#4b5563] text-[10px] mt-1">AI Assistant</div>
<div className="text-muted-foreground text-[10px] mt-1">AI Assistant</div>
</div>
</div>
) : (
<div className="flex gap-3 items-start flex-row-reverse">
<div className="flex-1 min-w-0 flex justify-end">
<div className="bg-gradient-to-br from-[#f97316] to-[#ea580c] rounded-2xl rounded-tr-sm px-5 py-4 max-w-[75%]">
<div className="text-white text-sm leading-7 whitespace-pre-wrap">{msg.content}</div>
<div className="bg-gradient-to-br from-primary to-primary rounded-2xl rounded-tr-sm px-5 py-4 max-w-[75%]">
{msg.gif ? (
<img
src={msg.gif.url}
alt={msg.gif.title || "GIF"}
className="w-full rounded-lg max-h-64 object-cover"
loading="lazy"
/>
) : (
<div className="text-white text-sm leading-7 whitespace-pre-wrap">{msg.content}</div>
)}
</div>
</div>
</div>
@@ -332,20 +339,20 @@ export const AIChat = forwardRef<AIChatHandle, AIChatProps>(({ onMessageSent },
))}
{loading && (
<div className="flex gap-3 items-start">
<div className="w-8 h-8 rounded-lg bg-gradient-to-br from-[#f97316] to-[#ea580c] flex items-center justify-center text-white text-sm flex-shrink-0">
<div className="w-8 h-8 rounded-lg bg-gradient-to-br from-primary to-primary flex items-center justify-center text-white text-sm flex-shrink-0">
<Bot className="h-4 w-4" />
</div>
<div className="bg-[#1a1d2e] rounded-2xl rounded-tl-sm border border-[#ffffff08] border-l-2 border-l-[#f97316] px-5 py-4 inline-flex items-center gap-1.5">
<span className="w-2 h-2 rounded-full bg-[#f97316] dot-1" />
<span className="w-2 h-2 rounded-full bg-[#f97316] dot-2" />
<span className="w-2 h-2 rounded-full bg-[#f97316] dot-3" />
<div className="bg-card rounded-2xl rounded-tl-sm border border-border border-l-2 border-l-primary px-5 py-4 inline-flex items-center gap-1.5">
<span className="w-2 h-2 rounded-full bg-primary dot-1" />
<span className="w-2 h-2 rounded-full bg-primary dot-2" />
<span className="w-2 h-2 rounded-full bg-primary dot-3" />
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
</div>
<div className="sticky bottom-0 bg-[#0f1117]/95 backdrop-blur-md border-t border-[#ffffff08] px-4 py-4">
<div className="sticky bottom-0 bg-background/95 backdrop-blur-md px-4 py-4">
<div className="max-w-3xl mx-auto">
{error && (
<div className="mb-2.5 text-xs text-red-400 flex items-center gap-1.5">
@@ -353,8 +360,9 @@ export const AIChat = forwardRef<AIChatHandle, AIChatProps>(({ onMessageSent },
{error}
</div>
)}
<div className="bg-[#1a1d2e] rounded-2xl border border-[#ffffff0a] focus-within:border-[#f97316]/40 focus-within:shadow-[0_0_20px_rgba(249,115,22,0.08)] transition-all duration-200 flex items-end gap-3 px-4 py-3">
<button type="button" className="w-8 h-8 rounded-lg text-[#4b5563] hover:text-[#f97316] hover:bg-[#ffffff08] flex items-center justify-center transition-colors duration-200 flex-shrink-0 text-lg">📎</button>
<div className="bg-card rounded-2xl border border-border focus-within:border-primary/40 focus-within:shadow-[0_0_20px_hsl(var(--primary)_/_0.08)] transition-all duration-200 flex items-end gap-3 px-4 py-3 relative" ref={containerRef}>
<button type="button" className="w-8 h-8 rounded-lg text-muted-foreground hover:text-primary hover:bg-muted/50 flex items-center justify-center transition-colors duration-200 flex-shrink-0 text-[11px] font-semibold tracking-wide" onClick={() => setShowGifPicker((v) => !v)}>GIF</button>
{showGifPicker && <GifPicker onSelect={handleGifSelect} onClose={() => setShowGifPicker(false)} />}
<textarea
ref={textareaRef}
value={input}
@@ -363,20 +371,20 @@ export const AIChat = forwardRef<AIChatHandle, AIChatProps>(({ onMessageSent },
onKeyDown={handleKeyDown}
placeholder="Ask for sales tips..."
rows={1}
className="bg-transparent flex-1 text-[#e5e7eb] text-sm placeholder-[#4b5563] resize-none outline-none min-h-[24px] max-h-[200px] overflow-y-auto leading-6"
className="bg-transparent flex-1 text-foreground text-sm placeholder-muted-foreground resize-none outline-none min-h-[24px] max-h-[200px] overflow-y-auto leading-6"
/>
<button
type="button"
onClick={() => sendMessage()}
disabled={!input.trim()}
className={`w-9 h-9 rounded-xl flex-shrink-0 bg-gradient-to-br from-[#f97316] to-[#ea580c] flex items-center justify-center text-white transition-all duration-200 ${input.trim() ? "hover:shadow-[0_0_20px_rgba(249,115,22,0.4)] hover:scale-105 active:scale-95" : "opacity-40 cursor-not-allowed"}`}
className={`w-9 h-9 rounded-xl flex-shrink-0 bg-gradient-to-br from-primary to-primary flex items-center justify-center text-white transition-all duration-200 ${input.trim() ? "hover:shadow-[0_0_20px_hsl(var(--primary)_/_0.4)] hover:scale-105 active:scale-95" : "opacity-40 cursor-not-allowed"}`}
>
</button>
</div>
<div className="flex justify-between items-center mt-2 px-1">
<span className="text-[#374151] text-[10px]">Shift + Enter for new line</span>
<span className="text-[#374151] text-[10px]">{input.length} / 2000</span>
<span className="text-muted-foreground text-[10px]">Shift + Enter for new line</span>
<span className="text-muted-foreground text-[10px]">{input.length} / 2000</span>
</div>
</div>
</div>
+193
View File
@@ -0,0 +1,193 @@
"use client"
import { useState, useRef, useEffect, useCallback } from "react"
import { Search, Loader2, ImageIcon } from "lucide-react"
interface GifResult {
id: string
title: string
url: string
previewUrl: string
previewHeight: number
width: number
height: number
}
interface GifPickerProps {
onSelect: (gif: { url: string; previewUrl: string; title: string }) => void
onClose: () => void
}
const SEARCH_CACHE = new Map<string, GifResult[]>()
export function GifPicker({ onSelect, onClose }: GifPickerProps) {
const [gifs, setGifs] = useState<GifResult[]>([])
const [loading, setLoading] = useState(true)
const [loadingMore, setLoadingMore] = useState(false)
const [search, setSearch] = useState("")
const [offset, setOffset] = useState(0)
const [hasMore, setHasMore] = useState(true)
const [error, setError] = useState("")
const sentinelRef = useRef<HTMLDivElement>(null)
const inputRef = useRef<HTMLInputElement>(null)
const searchTimeoutRef = useRef<ReturnType<typeof setTimeout>>()
const fetchGifs = useCallback(async (q: string, off: number, append: boolean) => {
if (off === 0) {
const cacheKey = q || "__trending__"
const cached = SEARCH_CACHE.get(cacheKey)
if (cached) {
setGifs(cached)
setLoading(false)
setHasMore(true)
setOffset(cached.length)
return
}
}
try {
if (!append) setLoading(true)
else setLoadingMore(true)
setError("")
const params = new URLSearchParams()
if (q) {
params.set("type", "search")
params.set("q", q)
}
params.set("offset", String(off))
params.set("limit", "20")
const res = await fetch(`/api/ai/giphy?${params}`)
if (!res.ok) {
const data = await res.json()
throw new Error(data.error || "Failed to fetch GIFs")
}
const data = await res.json()
const newGifs: GifResult[] = data.gifs || []
if (append) {
setGifs((prev) => [...prev, ...newGifs])
} else {
setGifs(newGifs)
if (off === 0 && !q) {
SEARCH_CACHE.set("__trending__", newGifs)
}
if (q) {
SEARCH_CACHE.set(q, newGifs)
}
}
setOffset(off + newGifs.length)
setHasMore(newGifs.length === 20)
} catch (err: any) {
setError(err.message || "Failed to load GIFs")
} finally {
setLoading(false)
setLoadingMore(false)
}
}, [])
useEffect(() => {
fetchGifs("", 0, false)
}, [fetchGifs])
useEffect(() => {
inputRef.current?.focus()
}, [])
useEffect(() => {
if (searchTimeoutRef.current) clearTimeout(searchTimeoutRef.current)
if (!search.trim()) {
fetchGifs("", 0, false)
return
}
searchTimeoutRef.current = setTimeout(() => {
fetchGifs(search.trim(), 0, false)
}, 400)
return () => {
if (searchTimeoutRef.current) clearTimeout(searchTimeoutRef.current)
}
}, [search, fetchGifs])
useEffect(() => {
const sentinel = sentinelRef.current
if (!sentinel) return
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting && hasMore && !loadingMore && !loading) {
fetchGifs(search.trim(), offset, true)
}
},
{ rootMargin: "200px" }
)
observer.observe(sentinel)
return () => observer.disconnect()
}, [hasMore, loadingMore, loading, offset, search, fetchGifs])
return (
<div className="absolute bottom-full left-0 right-0 mb-2 bg-card border border-border rounded-2xl shadow-xl shadow-black/20 overflow-hidden z-50">
<div className="p-3 border-b border-border">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<input
ref={inputRef}
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search GIFs..."
className="w-full bg-muted/50 text-foreground text-sm rounded-xl pl-9 pr-4 py-2.5 outline-none focus:ring-2 focus:ring-primary/30 placeholder:text-muted-foreground/60"
/>
</div>
</div>
<div className="overflow-y-auto" style={{ maxHeight: "360px" }}>
{loading ? (
<div className="flex items-center justify-center py-16">
<Loader2 className="h-6 w-6 animate-spin text-primary" />
</div>
) : error ? (
<div className="flex flex-col items-center justify-center py-16 px-4 text-center">
<ImageIcon className="h-8 w-8 text-muted-foreground mb-2" />
<p className="text-sm text-muted-foreground">{error}</p>
</div>
) : gifs.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 px-4 text-center">
<ImageIcon className="h-8 w-8 text-muted-foreground mb-2" />
<p className="text-sm text-muted-foreground">No GIFs found.</p>
</div>
) : (
<>
<div className="grid grid-cols-2 gap-2 p-3">
{gifs.map((gif) => (
<button
key={gif.id}
type="button"
onClick={() => onSelect({ url: gif.url, previewUrl: gif.previewUrl, title: gif.title })}
className="relative rounded-xl overflow-hidden bg-muted/30 hover:ring-2 hover:ring-primary/50 transition-all duration-200 aspect-video"
title={gif.title}
>
<img
src={gif.previewUrl}
alt={gif.title || "GIF"}
loading="lazy"
className="w-full h-full object-cover"
/>
</button>
))}
</div>
{loadingMore && (
<div className="flex items-center justify-center py-4">
<Loader2 className="h-5 w-5 animate-spin text-primary" />
</div>
)}
{hasMore && <div ref={sentinelRef} className="h-4" />}
</>
)}
</div>
</div>
)
}
+32 -46
View File
@@ -37,53 +37,39 @@ export function JobSelector({ onSelect, onSearch, searching }: JobSelectorProps)
}
return (
<div>
<div className="relative">
<button
type="button"
onClick={() => setOpen(!open)}
className="w-full flex items-center gap-2.5 bg-[#1a1d2e] border border-[#ffffff0f] hover:border-[#f97316]/30 rounded-xl px-4 py-3 text-sm text-[#9ca3af] hover:text-[#e5e7eb] transition-all duration-200"
>
<Briefcase className="h-4 w-4 text-[#f97316] flex-none" />
<span className="flex-1 text-left truncate">
{selected ? selected.job_title : loading ? "Loading jobs..." : "Select a job category to target"}
</span>
{loading ? <Loader2 className="h-3.5 w-3.5 animate-spin text-[#f97316]" /> : <ChevronDown className={`h-3.5 w-3.5 text-[#4b5563] transition-transform duration-200 ${open ? "rotate-180" : ""}`} />}
</button>
<div className="relative">
<button
type="button"
onClick={() => setOpen(!open)}
className="w-full flex items-center gap-2.5 bg-[#1a1d2e] border border-[#ffffff0f] hover:border-[#f97316]/30 rounded-xl px-4 py-3 text-sm text-[#9ca3af] hover:text-[#e5e7eb] transition-all duration-200"
>
<Briefcase className="h-4 w-4 text-[#f97316] flex-none" />
<span className="flex-1 text-left truncate">
{selected ? selected.job_title : loading ? "Loading jobs..." : "Select a job category"}
</span>
{loading ? <Loader2 className="h-3.5 w-3.5 animate-spin text-[#f97316]" /> : <ChevronDown className={`h-3.5 w-3.5 text-[#4b5563] transition-transform duration-200 ${open ? "rotate-180" : ""}`} />}
</button>
{open && (
<>
<div className="fixed inset-0 z-10" onClick={() => setOpen(false)} />
<div className="absolute top-full left-0 right-0 mt-1.5 z-20 bg-[#1a1d2e] border border-[#ffffff0f] rounded-xl shadow-xl shadow-black/40 max-h-60 overflow-y-auto">
{jobs.map((job, i) => (
<button
key={i}
type="button"
onClick={() => handleSelect(job)}
className="w-full text-left px-4 py-3 text-sm text-[#9ca3af] hover:bg-[#1f2437] hover:text-[#e5e7eb] transition-all duration-150 border-b border-[#ffffff08] last:border-0 border-l-2 border-l-transparent hover:border-l-[#f97316]/40"
>
<div className="font-medium">{job.job_title}</div>
<div className="text-xs text-[#4b5563] mt-0.5">{job.industry} &mdash; {job.description}</div>
</button>
))}
{jobs.length === 0 && !loading && (
<div className="px-4 py-4 text-xs text-[#4b5563] text-center">No job categories loaded</div>
)}
</div>
</>
)}
</div>
{selected && (
<button
type="button"
onClick={() => onSearch?.(selected)}
disabled={searching}
className="w-full mt-2 flex items-center justify-center gap-2 bg-gradient-to-br from-[#f97316] to-[#ea580c] hover:from-[#ea580c] hover:to-[#d97706] disabled:opacity-50 disabled:cursor-not-allowed rounded-xl px-4 py-2.5 text-sm font-semibold text-white transition-all duration-200 shadow-[0_0_20px_rgba(249,115,22,0.2)]"
>
{searching ? <Loader2 className="h-4 w-4 animate-spin" /> : <Search className="h-4 w-4" />}
{searching ? "Searching Facebook..." : "Search Facebook"}
</button>
{open && (
<>
<div className="fixed inset-0 z-10" onClick={() => setOpen(false)} />
<div className="absolute top-full left-0 right-0 mt-1.5 z-20 bg-[#1a1d2e] border border-[#ffffff0f] rounded-xl shadow-xl shadow-black/40 max-h-60 overflow-y-auto">
{jobs.map((job, i) => (
<button
key={i}
type="button"
onClick={() => handleSelect(job)}
className="w-full text-left px-4 py-3 text-sm text-[#9ca3af] hover:bg-[#1f2437] hover:text-[#e5e7eb] transition-all duration-150 border-b border-[#ffffff08] last:border-0 border-l-2 border-l-transparent hover:border-l-[#f97316]/40"
>
<div className="font-medium">{job.job_title}</div>
<div className="text-xs text-[#4b5563] mt-0.5">{job.industry} &mdash; {job.description}</div>
</button>
))}
{jobs.length === 0 && !loading && (
<div className="px-4 py-4 text-xs text-[#4b5563] text-center">No job categories loaded</div>
)}
</div>
</>
)}
</div>
)