Spaces:
Running

File size: 21,619 Bytes
88db97e
 
 
c61a308
88db97e
 
 
 
 
 
c61a308
88db97e
 
 
f1fbc6a
88db97e
 
 
 
 
 
 
 
 
 
 
 
f1fbc6a
c61a308
88db97e
 
 
e9f9cca
8c1ffc7
88db97e
 
0921d73
 
 
9bf36ba
0921d73
88db97e
 
 
e9f9cca
 
 
 
0921d73
 
e9f9cca
0921d73
87a5ed4
0921d73
 
 
60f05fc
87a5ed4
 
 
 
 
 
 
0921d73
88db97e
f6403d2
0921d73
 
f6403d2
88db97e
 
 
 
 
e132d11
9bf36ba
88db97e
 
 
 
 
 
 
e132d11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1fbc6a
e132d11
 
 
88db97e
f1fbc6a
88db97e
 
 
 
9bf36ba
88db97e
 
 
 
 
 
 
 
 
f1fbc6a
 
 
 
 
c61a308
88db97e
 
 
0fd6da7
 
88db97e
 
 
 
 
 
 
 
 
f1fbc6a
0fd6da7
c61a308
0fd6da7
f1fbc6a
0fd6da7
f1fbc6a
0fd6da7
f1fbc6a
88db97e
 
 
 
0fd6da7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88db97e
 
 
 
 
04fe651
88db97e
 
 
04fe651
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88db97e
 
f1fbc6a
88db97e
 
 
 
 
 
c7d27eb
49dcf8e
 
1269ee4
49dcf8e
aecbce0
 
 
1269ee4
aecbce0
 
 
1269ee4
aecbce0
1269ee4
aecbce0
49dcf8e
 
1269ee4
 
 
 
 
 
c7d27eb
49dcf8e
f1fbc6a
87a5ed4
c61a308
87a5ed4
 
 
 
 
f1fbc6a
0fd6da7
 
 
1269ee4
c7d27eb
 
 
f1fbc6a
 
2f7ae1c
 
88db97e
66a0f3d
8932582
88db97e
33757b5
3118010
 
33757b5
49dcf8e
be18371
49dcf8e
 
66a0f3d
be18371
49dcf8e
 
 
 
 
be18371
 
49dcf8e
 
 
 
 
be18371
49dcf8e
1326b8d
e9f9cca
e58beec
 
 
 
aecbce0
60f05fc
 
0921d73
 
 
 
 
 
 
aecbce0
0921d73
 
 
e58beec
 
 
 
aecbce0
0921d73
e58beec
 
 
0921d73
 
 
 
 
 
 
 
 
 
e58beec
 
0921d73
e58beec
e9f9cca
 
aecbce0
 
 
 
 
0921d73
aecbce0
49dcf8e
e9f9cca
 
 
 
 
 
 
 
 
 
49dcf8e
e9f9cca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c1ffc7
e9f9cca
8c1ffc7
e9f9cca
 
49dcf8e
e9f9cca
 
be18371
 
 
 
7b1eec7
 
 
 
 
 
 
 
 
 
 
66a0f3d
fafcde0
66a0f3d
fafcde0
66a0f3d
fafcde0
66a0f3d
 
fafcde0
5f8e071
fafcde0
66a0f3d
 
88db97e
 
2f7ae1c
88db97e
fafcde0
 
66a0f3d
04fe651
66a0f3d
04fe651
 
8932582
66a0f3d
88db97e
fafcde0
2f7ae1c
fafcde0
2f7ae1c
04fe651
66a0f3d
04fe651
 
2f7ae1c
 
 
04fe651
fafcde0
66a0f3d
04fe651
cd61bf7
8932582
66a0f3d
2f7ae1c
fafcde0
 
2f7ae1c
fafcde0
04fe651
2f7ae1c
88db97e
2f7ae1c
88db97e
 
2f7ae1c
7b1eec7
cd61bf7
 
0ca368e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
'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<string | null>(null)
  const [isReanalyzing, setIsReanalyzing] = useState(false)
  const [currentStage, setCurrentStage] = useState<any>(null)
  const [selectedFields, setSelectedFields] = useState<string[]>([])
  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<string, { label: string; color: string; bg: string; icon: any }> = {
      '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<string, string> = {
      'know_it_all': 'Знайка',
      'silent': 'Молчун',
      'talkative': 'Болтун',
      'despot': 'Деспот',
      'indecisive': 'Нерешительный',
    }
    return map[type.toLowerCase()] || type
  }

  const getSaboneLabel = (motive: string) => {
    const map: Record<string, string> = {
      '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 (
    <div className="h-full flex flex-col bg-[#0D0E18] font-['Inter'] relative">

      {/* Content */}
      <div
        className="flex-1 overflow-y-auto p-4 md:p-5 space-y-4 md:space-y-5 scrollbar-thin scrollbar-thumb-white/10 scroll-smooth"
        style={{ overscrollBehavior: 'contain', willChange: 'scroll-position', WebkitOverflowScrolling: 'touch' }}
      >
        {/* QUALIFICATION GRID - Premium View */}
        {(lead as any).qualification_data && Object.keys((lead as any).qualification_data).length > 0 && (
          <div className="space-y-3 mb-6">
            <div className="flex items-center justify-between px-1">
              <div className="flex items-center gap-2">
                <div className={cn(
                  "w-2 h-2 rounded-full animate-pulse",
                  (lead as any).qualification_complete ? "bg-emerald-500" : "bg-amber-500"
                )} />
                <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">
                  {t('clientCard.qualification') || 'Квалификация'}
                </span>
              </div>
              {(lead as any).qualification_complete && (
                <span className="text-[10px] font-bold text-emerald-400 bg-emerald-400/10 px-2 py-0.5 rounded-full border border-emerald-400/20">
                  COMPLETE
                </span>
              )}
            </div>

            <div className="flex flex-col gap-2">
              {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 (
                    <div
                      key={field}
                      className={cn(
                        "p-2.5 rounded-xl border transition-all duration-300 flex flex-col gap-1",
                        isNotFound
                          ? "bg-white/[0.02] border-white/5 opacity-60 hover:opacity-100"
                          : "bg-indigo-500/[0.03] border-indigo-500/10 hover:border-indigo-500/30 shadow-sm"
                      )}
                    >
                      <div className="flex items-center gap-1.5 overflow-hidden">
                        <Icon className={cn("w-3 h-3 shrink-0", isNotFound ? "text-slate-500" : "text-indigo-400")} />
                        <span className="text-[10px] text-slate-500 font-medium truncate">{field}</span>
                      </div>
                      <span className={cn(
                        "text-[11px] font-semibold leading-tight break-words",
                        isNotFound ? "text-slate-600 italic" : "text-slate-200"
                      )} title={String(value)}>
                        {isNotFound ? '...' : String(value)}
                      </span>
                    </div>
                  )
                })}
            </div>
          </div>
        )}

        {/* Header Title with Icon */}
        <div className="flex items-center gap-3 mb-2 p-1">
          <div className="w-10 h-10 rounded-xl bg-indigo-500/10 flex items-center justify-center text-indigo-400 border border-indigo-500/20">
            <Brain className="w-5 h-5" />
          </div>
          <div>
            <h2 className="text-base font-bold text-white tracking-tight">{t('clientCard.chatSummary')}</h2>
            <p className="text-[10px] text-slate-500 uppercase tracking-widest font-semibold">{t('common.aiGenerated') || 'AI Generated'}</p>
          </div>
        </div>

        {/* Numbered Summary List */}
        <div className="space-y-3 md:space-y-4 px-1">
          {summaryPoints.map((point, i) => (
            <div key={i} className="flex gap-3 md:gap-4 items-start group/point">
              <div className="flex flex-col items-center gap-1 mt-1">
                <span className="text-[10px] md:text-[11px] font-bold text-slate-500 bg-white/5 w-5 h-5 md:w-6 md:h-6 rounded-md flex items-center justify-center group-hover/point:text-indigo-400 group-hover/point:bg-indigo-500/10 transition-colors">
                  {i + 1}
                </span>
                {i < summaryPoints.length - 1 && <div className="w-[1px] h-3 md:h-4 bg-white/5" />}
              </div>
              <p className="text-slate-300 text-xs md:text-sm leading-relaxed flex-1 group-hover/point:text-white transition-colors">{point}</p>
            </div>
          ))}
        </div>

      </div>

      <div className="p-4 md:p-5 pb-6 md:pb-8 mt-auto border-t border-white/5 bg-[#0D0E18]">
        <div className="bg-[#1A1B26]/50 rounded-2xl p-4 md:p-5 border border-white/5 relative overflow-hidden group">
          {/* Glow Effect */}
          <div className={cn(
            "absolute top-0 right-0 w-32 h-32 blur-[40px] rounded-full pointer-events-none group-hover:opacity-100 opacity-50 transition-all duration-500",
            visuals.glow
          )} />

          <h3 className="text-sm font-medium text-slate-300 mb-4 relative z-10">{t('clientCard.heatLevel')}</h3>

          <div className="flex items-center gap-3 md:gap-4 relative z-10">
            {/* Thermometer Icon Placeholder (Custom Graphic) */}
            <div className="h-12 md:h-16 w-6 md:w-8 bg-slate-800 rounded-full relative overflow-hidden ring-1 ring-white/10">
              <div
                className={cn(
                  "absolute bottom-0 left-0 right-0 bg-gradient-to-t transition-all duration-1000",
                  visuals.gradient
                )}
                style={{ height: `${data.heat_score}%` }}
              />
              {/* Bulb */}
              <div
                className={cn("absolute bottom-0.5 left-1 right-1 h-4 w-4 md:h-5 md:w-5 rounded-full transition-colors duration-500", visuals.bulb)}
                style={{ boxShadow: `0 0 10px ${visuals.shadow}` }}
              />
            </div>

            <div>
              <div className="flex items-baseline gap-2">
                <span className="text-3xl md:text-4xl font-bold text-white tracking-tight">{data.heat_score}%</span>
                <Flame className={cn("w-5 h-5 md:w-6 md:h-6 animate-pulse", getScoreColor(data.heat_score))} />
              </div>
              <p className={cn("text-xs md:text-sm font-medium mt-0.5 md:mt-1", getScoreColor(data.heat_score))}>
                {data.heat_score >= 80 ? t('clientCard.high') : data.heat_score >= 40 ? t('clientCard.medium') : t('clientCard.low')}
              </p>
            </div>
          </div>
        </div>
      </div>

    </div >
  )
}

// Helper icon for Influential type
function StarIcon(props: any) {
  return (
    <svg
      {...props}
      xmlns="http://www.w3.org/2000/svg"
      width="24"
      height="24"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
    </svg>
  )
}