'use client'; import { FormEvent, useEffect, useRef, useState } from 'react'; import { usePathname } from 'next/navigation'; type PersistedMessage = { role: 'user' | 'assistant'; content: string }; const unavailable = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.'; const token = () => { try { return localStorage.getItem('accessToken') || ''; } catch { return ''; } }; export default function SupportChat() { const [config, setConfig] = useState<{ enabled: boolean; label: string; icon: string } | null>(null); const [configError, setConfigError] = useState(false); const [open, setOpen] = useState(false); const [message, setMessage] = useState(''); const [busy, setBusy] = useState(false); const [rows, setRows] = useState<{ question: string; answer: string }[]>([]); const [conversationId, setConversationId] = useState(''); const [contextLimited, setContextLimited] = useState(false); const identity = useRef(''); const pending = useRef(null); useEffect(() => { let active = true; const refresh = async () => { try { const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL || '/api'}/support-chat/config`, { cache: 'no-store' }); if (!response.ok) throw new Error('config'); const raw = await response.json(); const value = raw.data ?? raw; if (typeof value.enabled !== 'boolean' || typeof value.label !== 'string' || !['chat', 'paw', 'bot'].includes(value.icon)) throw new Error('config'); if (active) { setConfig(value); setConfigError(false); if (!value.enabled) { setOpen(false); pending.current?.abort(); setRows([]); } } } catch { if (active) { setConfig(null); setConfigError(true); setOpen(false); pending.current?.abort(); setRows([]); } } }; void refresh(); const timer = window.setInterval(refresh, 10000); window.addEventListener('focus', refresh); return () => { active = false; clearInterval(timer); window.removeEventListener('focus', refresh); }; }, []); const chatScrollRef = useRef(null); useEffect(() => { const handleOpenSupport = () => setOpen(true); window.addEventListener('canina:open-support-chat', handleOpenSupport); return () => window.removeEventListener('canina:open-support-chat', handleOpenSupport); }, []); const historyKey = useRef(''); const pathname = usePathname(); const isPdpPage = pathname?.startsWith('/shop/') && pathname !== '/shop'; useEffect(() => { identity.current = token(); try { const saved = localStorage.getItem('canina-support-conversation'); if (saved) setConversationId(saved); } catch {} const check = () => { if (identity.current !== token()) { identity.current = token(); try { const saved = localStorage.getItem('canina-support-conversation'); if (saved) setConversationId(saved); } catch {} pending.current?.abort(); setRows([]); setMessage(''); setBusy(false); } }; window.addEventListener('focus', check); window.addEventListener('storage', check); const interval = window.setInterval(check, 500); return () => { window.removeEventListener('focus', check); window.removeEventListener('storage', check); clearInterval(interval); pending.current?.abort(); }; }, []); useEffect(() => { if (chatScrollRef.current) { chatScrollRef.current.scrollTop = chatScrollRef.current.scrollHeight; } }, [rows, busy]); useEffect(() => { if (!conversationId || !config?.enabled) return; const current = token(); const key = `${current}:${conversationId}`; if (historyKey.current === key) return; historyKey.current = key; const controller = new AbortController(); pending.current = controller; const loadHistory = async () => { try { const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL || '/api'}/support-chat/${encodeURIComponent(conversationId)}`, { credentials: 'include', headers: { 'X-Requested-With': 'XMLHttpRequest', ...(current ? { Authorization: `Bearer ${current}` } : {}) }, signal: controller.signal }); if (!response.ok) throw new Error('history'); const data = await response.json(); if (!Array.isArray(data?.messages) || data.conversationId !== conversationId) throw new Error('history'); const messages = data.messages.filter((message: unknown): message is PersistedMessage => { if (!message || typeof message !== 'object') return false; const value = message as Record; return (value.role === 'user' || value.role === 'assistant') && typeof value.content === 'string'; }); const restored: { question: string; answer: string }[] = []; for (let i = 0; i < messages.length; i += 1) { const message = messages[i]; if (message.role === 'user') { const next = messages[i + 1]; if (next?.role === 'assistant') i += 1; restored.push({ question: message.content, answer: next?.role === 'assistant' ? next.content : '' }); } else if (!restored.length || restored[restored.length - 1].answer) { restored.push({ question: '', answer: message.content }); } } if (!controller.signal.aborted && token() === current) setRows(restored); } catch { if (!controller.signal.aborted && token() === current) { setRows([]); setConversationId(''); setContextLimited(false); try { localStorage.removeItem('canina-support-conversation'); } catch {} } } finally { if (pending.current === controller) pending.current = null; } }; void loadHistory(); return () => controller.abort(); }, [conversationId, config?.enabled]); async function send(event: FormEvent) { event.preventDefault(); if (busy || !message.trim() || !config?.enabled) return; const current = token(); if (current !== identity.current) { setRows([]); identity.current = current; } const question = message.trim(); setMessage(''); setBusy(true); setRows((r) => [...r.slice(-9), { question, answer: 'در حال بررسی…' }]); const controller = new AbortController(); pending.current = controller; let answer = unavailable; try { const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL || '/api'}/support-chat/ask`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', ...(current ? { Authorization: `Bearer ${current}` } : {}) }, credentials: 'include', body: JSON.stringify({ message: question, ...(conversationId ? { conversationId } : {}), entryPath: window.location.pathname }), signal: AbortSignal.any([controller.signal, AbortSignal.timeout(50000)]) }); if (response.status === 401) { answer = 'لطفاً دوباره وارد حساب کاربری شوید.'; } else if (response.ok) { const data = await response.json(); if (typeof data.answer === 'string') answer = data.answer; if (typeof data.conversationId === 'string') { setConversationId(data.conversationId); try { localStorage.setItem('canina-support-conversation', data.conversationId); } catch {} } setContextLimited(data.contextLimited === true); } } catch { // safe fallback kept } if (!controller.signal.aborted && token() === current) { // Typewriting animation for smooth AI assistant response streaming feel const fullAnswer = answer; const stepSize = Math.max(2, Math.floor(fullAnswer.length / 40)); let currentIdx = 0; const typeInterval = setInterval(() => { currentIdx += stepSize; if (currentIdx >= fullAnswer.length || controller.signal.aborted) { clearInterval(typeInterval); setRows((r) => { const next = [...r]; const i = next.length - 1; if (i >= 0 && next[i].question === question) next[i] = { question, answer: fullAnswer }; return next; }); if (pending.current === controller) setBusy(false); } else { const partial = fullAnswer.slice(0, currentIdx) + " ▍"; setRows((r) => { const next = [...r]; const i = next.length - 1; if (i >= 0 && next[i].question === question) next[i] = { question, answer: partial }; return next; }); } }, 18); } else { if (pending.current === controller) setBusy(false); } } if (!config?.enabled) return configError ? تنظیمات پشتیبان هوشمند در دسترس نیست. : null; const botIcon = { chat: '💬', paw: '🐾', bot: '🤖' }[config.icon]; return (