// ─────────────────────────────────────────────────────────── // Huio Control Panel — Live Support View (cp-support-view.jsx) // ─────────────────────────────────────────────────────────── if (!window.CP_STYLES) throw new Error('[cp-support-view] window.CP_STYLES not loaded'); function renderSupport({ lang, t, appStyles: rawAppStyles, supportQueue = [], supportLoading, supportFilter = 'all', setSupportFilter, supportSearchQuery, setSupportSearchQuery, selectedSupportConv, setSelectedSupportConv, fetchSupportQueue, supabaseClient, users = [], onOpenOrganizer, }) { const appStyles = rawAppStyles || window.CP_STYLES || {}; // Fast user resolution lookup const userMap = React.useMemo(() => { const map = new Map(); (users || []).forEach(u => { if (!u) return; if (u.id) map.set(String(u.id), u); if (u.phone) map.set(String(u.phone), u); }); return map; }, [users]); const getSupportUser = React.useCallback((conv) => { if (!conv) return null; return (conv.user_id && userMap.get(String(conv.user_id))) || (conv.user_phone && userMap.get(String(conv.user_phone))) || null; }, [userMap]); const isSupportPaidUser = React.useCallback((conv) => { const u = getSupportUser(conv); if (!u) return false; return u.subscriptionSource === 'payment' || u.subscriptionSource === 'cp_grant' || ['organizer_pro', 'organizer_business', 'premium_auto', 'basic_assistant', 'pro', 'business'].includes(u.plan); }, [getSupportUser]); // Safe data array & pre-normalized filter criteria (O(1) loop invariant hoisting) const queueList = Array.isArray(supportQueue) ? supportQueue : []; const q = (typeof supportSearchQuery === 'string') ? supportSearchQuery.trim().toLowerCase() : ''; const totalCount = queueList.length; // Single-pass computation of metrics (0 intermediate array allocations) let waitingCount = 0; let paidCount = 0; let paidWaitingCount = 0; for (let i = 0; i < totalCount; i++) { const conv = queueList[i]; if (!conv) continue; const isWaiting = Boolean(conv.is_waiting_reply); const isPaid = isSupportPaidUser(conv); if (isWaiting) waitingCount++; if (isPaid) paidCount++; if (isWaiting && isPaid) paidWaitingCount++; } // Filters with defensive null/type safety on string properties const filteredQueue = queueList.filter(conv => { if (!conv) return false; if (supportFilter === 'waiting' && !conv.is_waiting_reply) return false; if (supportFilter === 'paid' && !isSupportPaidUser(conv)) return false; if (!q) return true; const name = (conv.user_name || '').toLowerCase(); const phone = String(conv.user_phone || ''); const msg = (conv.last_message_text || '').toLowerCase(); return name.includes(q) || phone.includes(q) || msg.includes(q); }); return (

{t('support.title') || 'Support Queue'}

{t('support.sub') || 'Manage all live support conversations with users.'}

{/* Quick Metrics Bar */}
0 ? '4px solid var(--hu-ochre)' : undefined }}>
👑
{lang === 'vi' ? 'Khách trả phí chờ' : 'Paid Waiting'}
0 ? 'var(--hu-ochre)' : 'var(--hu-fg)' }}> {paidWaitingCount} / {paidCount} {lang === 'vi' ? 'tổng' : 'total'}
⏳
{t('support.stats.waiting') || 'Waiting for reply'}
0 ? 'var(--hu-rust)' : 'var(--hu-fg)' }}> {waitingCount}
💬
{t('support.stats.total') || 'Total conversations'}
{totalCount}
{/* Controls Bar */}
{/* Filter Buttons */}
{/* Search query */}
setSupportSearchQuery(e.target.value)} placeholder={t('common.search')} className="hu-input" style={{ height: '100%', fontSize: '13px' }} />
{/* Support Queue List Table */}
👉 {lang === 'vi' ? 'Vuốt sang phải để xem tin nhắn và mở hội thoại hỗ trợ' : 'Swipe horizontally to view full message and open chat'}
{supportLoading && queueList.length === 0 ? ( ) : filteredQueue.length === 0 ? ( ) : ( filteredQueue.map((conv, index) => { const rawDate = conv.last_message_at || conv.created_at; const dateObj = rawDate ? new Date(rawDate) : null; const isInvalidDate = !dateObj || isNaN(dateObj.getTime()); const timeStr = isInvalidDate ? '—' : dateObj.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); const dateStr = isInvalidDate ? '—' : dateObj.toLocaleDateString(lang === 'vi' ? 'vi-VN' : 'en-US', { month: 'short', day: 'numeric' }); const unreadNum = Number(conv.unread_count || 0); const rowKey = conv.conversation_id || `conv_${conv.user_id || index}_${index}`; const displayName = conv.user_name || t('support.anonymous') || 'Anonymous'; const avatarInitial = String(displayName).charAt(0).toUpperCase() || 'U'; const matchedUser = getSupportUser(conv); const isPaid = isSupportPaidUser(conv); const defaultBg = conv.is_waiting_reply && isPaid ? 'rgba(184, 115, 51, 0.08)' : conv.is_waiting_reply ? 'rgba(217, 83, 79, 0.03)' : isPaid ? 'rgba(184, 115, 51, 0.03)' : 'inherit'; const hoverBg = conv.is_waiting_reply ? 'rgba(217, 83, 79, 0.08)' : isPaid ? 'rgba(184, 115, 51, 0.08)' : 'var(--hu-bg-elev)'; return ( setSelectedSupportConv(conv)} onMouseEnter={(e) => { e.currentTarget.style.background = hoverBg; }} onMouseLeave={(e) => { e.currentTarget.style.background = defaultBg; }} > ); }) )}
{t('support.col.user') || 'User'} {t('support.col.last_message') || 'Last message'} {t('support.col.time') || 'Time'} {t('support.col.status') || 'Status'} {lang === 'vi' ? 'Hành động' : 'Actions'}
⏳
{lang === 'vi' ? 'Đang tải hàng đợi hỗ trợ...' : 'Loading support queue...'}
🎉
{supportFilter === 'waiting' ? (lang === 'vi' ? 'Không có yêu cầu nào đang chờ phản hồi!' : 'All support requests have been answered!') : (t('support.empty') || 'No support conversations found')}
{lang === 'vi' ? 'Hệ thống hỗ trợ đang hoạt động bình thường.' : 'All incoming messages are handled.'}
{conv.user_avatar ? ( {displayName} ) : ( avatarInitial )}
{displayName} {isPaid && ( 👑 {matchedUser?.plan ? matchedUser.plan.replace('organizer_', '').toUpperCase() : 'VIP'} )} {unreadNum > 0 && ( {unreadNum} )}
{conv.user_phone ? conv.user_phone : 'No phone'}
{matchedUser && typeof onOpenOrganizer === 'function' && ( )}
{conv.last_message_text || ( {lang === 'vi' ? 'Chưa có tin nhắn' : 'No messages'} )}
{timeStr}
{dateStr}
{conv.is_waiting_reply ? ( 🔴 {t('support.status.waiting') || 'Waiting'} ) : ( ✓ {t('support.status.replied') || 'Replied'} )}
{/* Support Chat Modal */} setSelectedSupportConv(null)} title={lang === 'vi' ? 'Hỗ trợ khách hàng' : 'Live Support'} userName={selectedSupportConv?.user_name} userPhone={selectedSupportConv?.user_phone} waitingBadge={selectedSupportConv?.is_waiting_reply} > {selectedSupportConv && ( fetchSupportQueue(supportFilter)} /> )}
); } window.CpSupportView = { renderSupport, };