Files
canina/frontend/application/components/SupportChat.tsx
T

349 lines
17 KiB
TypeScript

'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);
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 [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<AbortController | null>(null);
const chatScrollRef = useRef<HTMLDivElement | null>(null);
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<string, unknown>;
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 ? <span role="status" className="sr-only">تنظیمات پشتیبان هوشمند در دسترس نیست.</span> : null;
const botIcon = { chat: '💬', paw: '🐾', bot: '🤖' }[config.icon];
return (
<aside dir="rtl" className={`fixed ${isPdpPage ? "bottom-[138px]" : "bottom-24"} sm:bottom-6 left-4 sm:left-6 z-30 max-w-[calc(100vw-2.5rem)] font-vazir select-none pb-[env(safe-area-inset-bottom,0px)]`}>
{/* Floating Launcher Button */}
<button
type="button"
onClick={() => setOpen(!open)}
aria-expanded={open}
aria-label={open ? 'بستن گفتگو با پشتیبان' : config.label}
className={`group relative flex items-center gap-2.5 rounded-full px-4 py-3 text-white shadow-2xl transition-all duration-300 ${
open
? 'bg-medical-gray-800 hover:bg-medical-gray-900 rotate-0'
: 'bg-canina-blue hover:bg-opacity-95 hover:shadow-canina-blue/30 hover:scale-105'
}`}
>
<span className="relative flex h-3 w-3">
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-canina-gold opacity-75"></span>
<span className="relative inline-flex h-3 w-3 rounded-full bg-canina-gold"></span>
</span>
<svg className="h-5 w-5 transition-transform duration-300 group-hover:scale-110" fill="none" viewBox="0 0 24 24" stroke="currentColor">
{open ? (
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.2} d="M6 18L18 6M6 6l12 12" />
) : (
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
)}
</svg>
<span className="text-sm font-semibold tracking-wide">{!open && <span aria-label="آیکون دستیار">{botIcon}</span>}{open ? 'بستن گفتگو' : config.label}</span>
</button>
{/* Chat Window */}
{open && (
<section
aria-label="پشتیبان کنینا"
className="absolute bottom-16 left-0 flex flex-col w-[min(360px,calc(100vw-2rem))] sm:w-[400px] h-[540px] max-h-[calc(100vh-7rem)] rounded-2xl border border-medical-gray-200 bg-white/95 backdrop-blur-md shadow-2xl overflow-hidden transition-all duration-300 animate-in fade-in slide-in-from-bottom-4"
>
{/* Header */}
<div className="bg-gradient-to-r from-canina-blue to-medical-gray-800 text-white p-4 flex items-center justify-between border-b border-white/10">
<div className="flex items-center gap-3">
<div className="relative flex h-10 w-10 items-center justify-center rounded-xl bg-white/10 border border-white/20 text-canina-gold font-bold text-lg">
<span aria-label="آیکون دستیار">{botIcon}</span>
<span className="absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full border-2 border-canina-blue bg-emerald-500"></span>
</div>
<div>
<h3 className="text-sm font-bold flex items-center gap-1.5">
{config.label}
<span className="text-[10px] bg-canina-gold/20 text-canina-gold px-1.5 py-0.5 rounded border border-canina-gold/30">AI</span>
</h3>
<p className="text-[11px] text-white/70">راهنمای محصولات و سلامت پت</p>
<button type="button" className="text-[11px] text-canina-gold hover:underline" onClick={() => { setRows([]); setConversationId(''); setContextLimited(false); try { localStorage.removeItem('canina-support-conversation'); } catch {} }}>گفتگوی جدید</button>
</div>
</div>
<button
type="button"
onClick={() => setOpen(false)}
className="rounded-lg p-1 text-white/70 hover:bg-white/10 hover:text-white transition-colors"
aria-label="بستن"
>
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{/* Message Area */}
<div
ref={chatScrollRef}
aria-live="polite"
className="flex-1 overflow-y-auto p-4 space-y-3.5 bg-gradient-to-b from-medical-gray-50/50 to-white text-xs select-text"
>
<div className="rounded-xl bg-medical-gray-100 p-3 text-[11px] text-medical-gray-600 leading-relaxed border border-medical-gray-200 flex items-start gap-2">
<svg className="h-4 w-4 text-canina-blue shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
</svg>
<span>پشتیبان هوشمند کنینا · پیام‌ها در همین گفت‌وگو حفظ می‌شوند. اطلاعات تغذیه و مکمل‌ها جایگزین تشخیص دامپزشک نیست.</span>
</div>
{rows.length === 0 && (
<div className="text-center py-8 text-medical-gray-400">
<p className="text-xs">سوالی درباره مکمل‌ها، تغذیه یا سفارش‌ها دارید؟</p>
<p className="text-[11px] mt-1 text-medical-gray-500">به فارسی یا فینگلیش بپرسید تا راهنماییتان کنم.</p>
</div>
)}
{rows.map((r, i) => (
<div key={i} className="space-y-2">
{/* User Message */}
<div className="flex justify-start">
<div className="max-w-[85%] rounded-2xl rounded-tr-sm bg-canina-blue text-white px-3.5 py-2.5 shadow-sm text-xs leading-relaxed whitespace-pre-wrap">
{r.question}
</div>
</div>
{/* Assistant Message */}
<div className="flex justify-end">
<div className="max-w-[90%] rounded-2xl rounded-tl-sm bg-medical-gray-100 text-medical-gray-900 border border-medical-gray-200 px-3.5 py-2.5 shadow-sm text-xs leading-relaxed whitespace-pre-wrap">
{r.answer}
</div>
</div>
</div>
))}
</div>
{/* Input & Footer */}
<div className="p-3 bg-white border-t border-medical-gray-200">
<form onSubmit={send} className="relative flex items-center">
<textarea
aria-label="پیام شما"
value={message}
maxLength={1500}
rows={1}
placeholder="پیام یا سوال خود را بنویسید…"
onChange={(e) => setMessage(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
if (!busy && message.trim()) send(e);
}
}}
className="w-full resize-none rounded-xl border border-medical-gray-300 bg-medical-gray-50/50 py-2.5 pr-3 pl-12 text-xs text-medical-gray-900 placeholder-medical-gray-400 focus:border-canina-blue focus:bg-white focus:outline-none transition-all"
/>
<button
type="submit"
disabled={busy || !message.trim()}
aria-label="ارسال"
className="absolute left-1.5 flex h-8 w-8 items-center justify-center rounded-lg bg-canina-blue text-white shadow-sm transition-all hover:bg-opacity-90 disabled:opacity-30 disabled:hover:bg-canina-blue"
>
<svg className="h-4 w-4 rotate-180" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.2} d="M14 5l7 7m0 0l-7 7m7-7H3" />
</svg>
</button>
</form>
{contextLimited && <div role="status" className="mb-2 rounded bg-amber-50 p-2 text-[11px] text-amber-800">برای ادامه دقیق‌تر، گفتگوی جدیدی شروع کنید یا با پشتیبانی تماس بگیرید.</div>}
<div className="mt-2 flex items-center justify-between px-1 text-[11px] text-medical-gray-500">
<span>Shift+Enter خط جدید</span>
<a
href="/dashboard?tab=tickets"
className="text-canina-blue font-medium hover:underline hover:text-medical-gray-800 transition-colors"
>
ثبت تیکت پشتیبانی ←
</a>
</div>
</div>
</section>
)}
</aside>
);
}