'use client' import { useState, useEffect } from 'react' import { Lead, AISummaryJson } from '@/lib/api' import { cn } from '@/lib/utils' import { Brain, TrendingUp, DollarSign, Target, Clock, AlertCircle, Lightbulb, User as UserIcon, CheckCircle2, Phone, Check, Loader2, RefreshCw, Bot, Zap, Database, Shield, MessageSquare, AlertTriangle, ThumbsUp, PenTool, Copy, ChevronDown, ChevronUp, Mail, Archive, PhoneCall, MapPin, Briefcase, Flame, Star } from 'lucide-react' import { useToast } from '@/contexts/ToastContext' import { motion, AnimatePresence } from 'framer-motion' import { useTranslation } from '@/lib/i18n' interface ClientCardProps { lead: Lead onTakeover: () => void isAnalyzing?: boolean onRefresh?: () => void conversationId?: string tenantId?: string } export function ClientCard({ lead, onTakeover, isAnalyzing, onRefresh, conversationId, tenantId }: ClientCardProps) { const { success, error } = useToast() const { t } = useTranslation() const summary = (lead.ai_summary_json || {}) as AISummaryJson const [expandedSection, setExpandedSection] = useState(null) const [isReanalyzing, setIsReanalyzing] = useState(false) const [currentStage, setCurrentStage] = useState(null) const [selectedFields, setSelectedFields] = useState([]) const [fieldsLoaded, setFieldsLoaded] = useState(false) // Prevent flickering useEffect(() => { // 1. Fetch current stage for criteria filtering const token = localStorage.getItem('auth_token') fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/playbook/stages`, { headers: { 'Authorization': `Bearer ${token}` } }) .then(r => r.ok ? r.json() : []) .then(stages => { if (lead.current_stage_id) { const stage = stages.find((s: any) => s.id === lead.current_stage_id) if (stage) setCurrentStage(stage) } }) .catch(err => console.error('Failed to fetch stages:', err)) // 2. Fetch MASTER LIST of selected fields from AI Settings (Brain) fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/tenants/me`, { headers: { 'Authorization': `Bearer ${token}` } }) .then(r => r.ok ? r.json() : {}) .then((tenantData: any) => { const brainFields = tenantData?.ai_settings?.qualification_fields if (Array.isArray(brainFields) && brainFields.length > 0) { setSelectedFields(brainFields) } else { // Default fields if none selected setSelectedFields(["Имя", "Контакт", "Потребность"]) } setFieldsLoaded(true) }) .catch(err => { console.error('Failed to fetch selected fields:', err) setFieldsLoaded(true) }) }, [lead.current_stage_id]) const handleReanalyze = async () => { setIsReanalyzing(true) try { // 1. Trigger analysis const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/leads/${lead.id}/analyze`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` } }) if (!res.ok) throw new Error('Failed') // 2. Wait a bit for analysis to complete await new Promise(resolve => setTimeout(resolve, 2000)) // 3. Fetch updated lead data const updatedRes = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/leads/${lead.id}`, { headers: { 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` } }) if (updatedRes.ok) { const updatedLead = await updatedRes.json() // Trigger parent refresh with new data onRefresh?.() success(t('clientCard.analysisComplete'), t('clientCard.summaryUpdated')) } else { throw new Error('Failed to fetch updated data') } } catch { error(t('common.error'), t('clientCard.failedToAnalyze')) } finally { setIsReanalyzing(false) } } // Helper to clean values const cleanValue = (value: any, fallback: string): string => { if (!value || typeof value !== 'string') return fallback const errorPatterns = ['unknown', 'error', 'failed', 'undefined'] return errorPatterns.some(p => value.toLowerCase().includes(p)) ? fallback : value } // Structured Data const data = { intent: cleanValue(summary.intent, t('clientCard.notDetermined')), need: cleanValue(summary.need || lead.need, t('clientCard.notDetermined')), budget: cleanValue(summary.budget || lead.budget, t('clientCard.notDefined')), authority: cleanValue(summary.authority || lead.authority, t('common.unknown')), timeline: cleanValue(summary.timeline || lead.timeline, t('clientCard.notSpecified')), niche: cleanValue(summary.niche || summary.industry || (lead as any).industry || (lead as any).business_type, t('clientCard.notSpecified')), pain_points: Array.isArray(summary.pain_points) ? summary.pain_points : [], objections: Array.isArray(summary.objections) ? summary.objections : [], psychotype: cleanValue(summary.psychotype || lead.psychotype, 'unknown'), behavioral_type: summary.behavioral_type, buying_motive: summary.buying_motive, hidden_signals: summary.hidden_signals, recommendation: summary.recommendation, draft_reply: summary.draft_reply, heat_score: typeof summary.heat_score === 'number' ? summary.heat_score : (lead.heat_score || 0) } // Psychotype Colors & Labels const getPsychotypeInfo = (type: string) => { const map: Record = { 'dominant': { label: t('psychotypes.dominant'), color: 'text-red-600', bg: 'bg-red-50', icon: Zap }, 'driven': { label: 'Целеустремленный', color: 'text-red-600', bg: 'bg-red-50', icon: Zap }, 'influential': { label: t('psychotypes.influential'), color: 'text-amber-600', bg: 'bg-amber-50', icon: Star }, 'emotional': { label: 'Эмоциональный', color: 'text-amber-600', bg: 'bg-amber-50', icon: Star }, 'steady': { label: t('psychotypes.steady'), color: 'text-emerald-600', bg: 'bg-emerald-50', icon: Shield }, 'harmonic': { label: 'Гармонический', color: 'text-emerald-600', bg: 'bg-emerald-50', icon: Shield }, 'conscientious': { label: t('psychotypes.conscientious'), color: 'text-blue-600', bg: 'bg-blue-50', icon: Database }, 'analytical': { label: 'Аналитический', color: 'text-blue-600', bg: 'bg-blue-50', icon: Database }, 'unknown': { label: t('clientCard.notDetermined'), color: 'text-slate-500', bg: 'bg-slate-50', icon: UserIcon } } return map[type.toLowerCase()] || map['unknown'] } const getBehavioralLabel = (type: string) => { const map: Record = { 'know_it_all': 'Знайка', 'silent': 'Молчун', 'talkative': 'Болтун', 'despot': 'Деспот', 'indecisive': 'Нерешительный', } return map[type.toLowerCase()] || type } const getSaboneLabel = (motive: string) => { const map: Record = { 'S': 'Безопасность', 'A': 'Привязанность', 'B': 'Комфорт', 'O': 'Престиж', 'N': 'Новизна', 'E': 'Экономия', } return map[motive.toUpperCase()] || motive } const psychotype = getPsychotypeInfo(data.psychotype) // Score Color const getScoreColor = (score: number) => { if (score >= 80) return 'text-red-500' if (score >= 40) return 'text-orange-500' return 'text-blue-500' } const getHeatVisuals = (score: number) => { if (score >= 80) return { gradient: 'from-red-600 to-orange-500', bulb: 'bg-red-500', glow: 'bg-red-500/10', shadow: 'rgba(239,68,68,0.5)' } if (score >= 40) return { gradient: 'from-orange-600 to-amber-500', bulb: 'bg-orange-500', glow: 'bg-orange-500/10', shadow: 'rgba(249,115,22,0.5)' } return { gradient: 'from-blue-600 to-cyan-500', bulb: 'bg-blue-500', glow: 'bg-blue-500/10', shadow: 'rgba(59,130,246,0.5)' } } const visuals = getHeatVisuals(data.heat_score) const copyToClipboard = (text: string, label: string) => { navigator.clipboard.writeText(text) success(t('common.copied'), `${label} ${t('clientCard.copiedToClipboard')}`) } const toggleSection = (section: string) => { setExpandedSection(expandedSection === section ? null : section) } // Construct real summary points from 11-point AI data // Filter out points that are already in the qualification card to avoid duplication const qualData = (lead as any).qualification_data || {} const hasQualField = (label: string) => { const labelLower = label.toLowerCase().trim() return Object.entries(qualData).some(([k, v]) => { const kLower = k.toLowerCase().trim() const isValueEmpty = !v || (typeof v === 'string' && ( v.toLowerCase().includes('не выявлено') || v.toLowerCase().includes('не указано') || v.toLowerCase() === 'none' || v.toLowerCase() === '...' )) return (kLower === labelLower || kLower.includes(labelLower) || labelLower.includes(kLower)) && !isValueEmpty }) } // Sanitize recommendation to remove redundant prefix let cleanRecommendation = data.recommendation if (cleanRecommendation && typeof cleanRecommendation === 'string') { cleanRecommendation = cleanRecommendation.replace(/^(Рекомендация|Recommendation):\s*/i, '').trim() } const realSummaryPoints = [ !hasQualField(t('clientCard.name')) && `${t('clientCard.name')}: ${lead.name || t('common.unknown')}`, data.intent && `${t('clientCard.goals')}: ${data.intent}`, !hasQualField(t('clientCard.niche')) && data.niche && `${t('clientCard.niche')}: ${data.niche}`, !hasQualField(t('clientCard.need')) && data.need && data.need !== t('clientCard.notDetermined') && `${t('clientCard.need')}: ${data.need}`, !hasQualField(t('clientCard.budget')) && data.budget && data.budget !== t('clientCard.notDefined') && `${t('clientCard.budget')}: ${data.budget}`, !hasQualField(t('clientCard.decisionMaker')) && data.authority && data.authority !== t('common.unknown') && `${t('clientCard.decisionMaker')}: ${data.authority}`, !hasQualField(t('clientCard.timeline')) && data.timeline && data.timeline !== t('clientCard.notSpecified') && `${t('clientCard.timeline')}: ${data.timeline}`, (data.pain_points && data.pain_points.length > 0) && `${t('clientCard.painPoints')}: ${data.pain_points.join(', ')}`, (data.objections && data.objections.length > 0) && `${t('clientCard.objections')}: ${data.objections.join(', ')}`, data.hidden_signals && `${t('clientCard.signals')}: ${data.hidden_signals}`, data.psychotype && data.psychotype !== 'unknown' && `Психотип: ${getPsychotypeInfo(data.psychotype).label}`, data.behavioral_type && `Поведение: ${getBehavioralLabel(data.behavioral_type)}`, data.buying_motive && `Мотив (SABONE): ${getSaboneLabel(data.buying_motive)}`, cleanRecommendation && `${t('clientCard.recommendation')}: ${cleanRecommendation}`, ].filter(Boolean) as string[] const summaryPoints = realSummaryPoints.length > 0 ? realSummaryPoints : [ t('clientCard.analysisNotDone'), t('clientCard.waitingFirstMessage') ] return (
{/* Content */}
{/* QUALIFICATION GRID - Premium View */} {(lead as any).qualification_data && Object.keys((lead as any).qualification_data).length > 0 && (
{t('clientCard.qualification') || 'Квалификация'}
{(lead as any).qualification_complete && ( COMPLETE )}
{Object.entries((lead as any).qualification_data) .filter(([field, value]) => { // Wait for stages to load once to prevent flickering if (!fieldsLoaded) return false // Use lowercased key for matching const fieldLower = field.toLowerCase().trim() // 1. Check if this field is explicitly selected in Brain Settings const isSelected = selectedFields.some(sf => { const sfLower = sf.toLowerCase().trim() return sfLower === fieldLower || fieldLower.includes(sfLower) || sfLower.includes(fieldLower) }) if (!isSelected) return false // 2. Determine if it's "empty" const isNotFound = !value || (typeof value === 'string' && ( value.toLowerCase().includes('не выявлено') || value.toLowerCase().includes('не указано') || value.toLowerCase() === 'none' || value.toLowerCase() === '...' )) if (isNotFound) { // Only show empty placeholder if it's ALSO in current stage's exit_criteria const isRequiredInStage = Array.isArray(currentStage?.exit_criteria) && currentStage.exit_criteria.some((sf: string) => { const sfLower = sf.toLowerCase().trim() return sfLower === fieldLower || fieldLower.includes(sfLower) || sfLower.includes(fieldLower) }) return isRequiredInStage } // If it HAS data and is SELECTED, show it return true }) .map(([field, value]: [string, any]) => { const isNotFound = !value || (typeof value === 'string' && ( value.toLowerCase().includes('не выявлено') || value.toLowerCase().includes('не указано') || value.toLowerCase() === 'none' || value.toLowerCase() === '...' )) // Dynamic Icon selection let Icon = Target const f = field.toLowerCase() if (f.includes('имя')) Icon = UserIcon if (f.includes('тел') || f.includes('контакт') || f.includes('номер')) Icon = Phone if (f.includes('бюджет') || f.includes('деньги') || f.includes('цена')) Icon = DollarSign if (f.includes('срок') || f.includes('когда') || f.includes('даты')) Icon = Clock if (f.includes('почта') || f.includes('email')) Icon = Mail if (f.includes('бизнес') || f.includes('компания')) Icon = Briefcase if (f.includes('город') || f.includes('адрес')) Icon = MapPin return (
{field}
{isNotFound ? '...' : String(value)}
) })}
)} {/* Header Title with Icon */}

{t('clientCard.chatSummary')}

{t('common.aiGenerated') || 'AI Generated'}

{/* Numbered Summary List */}
{summaryPoints.map((point, i) => (
{i + 1} {i < summaryPoints.length - 1 &&
}

{point}

))}
{/* Glow Effect */}

{t('clientCard.heatLevel')}

{/* Thermometer Icon Placeholder (Custom Graphic) */}
{/* Bulb */}
{data.heat_score}%

{data.heat_score >= 80 ? t('clientCard.high') : data.heat_score >= 40 ? t('clientCard.medium') : t('clientCard.low')}

) } // Helper icon for Influential type function StarIcon(props: any) { return ( ) }