'use client'; import { FormEvent, useEffect, useRef, useState } from 'react'; 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 identity = useRef(''); const pending = useRef(null); const chatScrollRef = useRef(null); useEffect(() => { identity.current = token(); const check = () => { if (identity.current !== token()) { identity.current = token(); 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]); 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); 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 }), 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; } } catch { // safe fallback kept } if (!controller.signal.aborted && token() === current) { setRows((r) => [...r.slice(-9), { question, answer }]); } if (pending.current === controller) setBusy(false); } if (!config?.enabled) return configError ? تنظیمات پشتیبان هوشمند در دسترس نیست. : null; const botIcon = { chat: '💬', paw: '🐾', bot: '🤖' }[config.icon]; return (