File size: 26,525 Bytes
98b6d67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
<!DOCTYPE html>
<html lang="uz">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>Help.me - Tez Tibbiy Yordam</title>

    <link rel="icon" href="/static/favicon.ico" type="image/x-icon">
    <link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">

    <style>

        :root {

            --bg-dark: #0f172a;

            --bg-medium: #1e293b;

            --bg-light: #334155;

            --text-primary: #f1f5f9;

            --text-secondary: #94a3b8;

            --accent-red: #ef4444;

            --accent-green: #10b981;

            --accent-blue: #3b82f6;

            --accent-purple: #8b5cf6;

        }



        * {

            margin: 0;

            padding: 0;

            box-sizing: border-box;

        }



        body {

            font-family: 'Inter', -apple-system, sans-serif;

            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

            color: var(--text-primary);

            display: flex;

            justify-content: center;

            align-items: center;

            min-height: 100vh;

            padding: 1rem;

            overflow: hidden;

        }



        .app-container {

            width: 100%;

            max-width: 420px;

            height: 90vh;

            max-height: 850px;

            background: var(--bg-dark);

            border-radius: 24px;

            box-shadow: 0 50px 100px -20px rgba(0, 0, 0, 0.5);

            display: flex;

            flex-direction: column;

            overflow: hidden;

            position: relative;

            border: 1px solid rgba(255, 255, 255, 0.1);

            animation: slideInFromBottom 0.5s ease-out;

        }



        @keyframes slideInFromBottom {

            from {

                transform: translateY(50px);

                opacity: 0;

            }



            to {

                transform: translateY(0);

                opacity: 1;

            }

        }



        .app-header {

            padding: 16px 20px;

            text-align: center;

            flex-shrink: 0;

            position: relative;

            background: var(--bg-medium);

            border-bottom: 1px solid var(--bg-light);

        }



        .app-header h1 {

            font-size: 1.25rem;

            font-weight: 600;

            margin: 0;

            display: flex;

            align-items: center;

            justify-content: center;

            gap: 10px;

            color: var(--accent-blue);

        }



        /* YANGI: Admin paneli tugmasi uchun yaxshilangan stillar */

        .admin-panel-btn {

            position: absolute;

            top: 12px;

            right: 12px;

            background: var(--accent-blue);

            color: white;

            border: none;

            border-radius: 8px;

            padding: 6px 10px;

            font-size: 0.75rem;

            font-weight: 600;

            text-decoration: none;

            transition: all 0.2s ease;

            animation: pulse-admin 2s infinite;

            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);

        }



        .admin-panel-btn:hover {

            background: var(--accent-blue);

            color: white;

            transform: scale(1.05);

        }



        /* YANGI: Admin tugmasi uchun pulsatsiya animatsiyasi */

        @keyframes pulse-admin {

            0% {

                box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.7);

            }



            70% {

                box-shadow: 0 0 0 10px rgba(59, 130, 246, 0);

            }



            100% {

                box-shadow: 0 0 0 0 rgba(59, 130, 246, 0);

            }

        }



        .connection-status {

            padding: 8px 16px;

            text-align: center;

            font-size: 0.8rem;

            flex-shrink: 0;

            transition: all 0.3s ease;

            background: var(--bg-medium);

        }



        .connection-status.connected {

            color: var(--accent-green);

        }



        .connection-status.disconnected {

            color: var(--accent-red);

        }



        .chat-container {

            flex: 1;

            overflow-y: auto;

            padding: 20px;

            background: var(--bg-dark);

        }



        .message {

            margin-bottom: 16px;

            display: flex;

            gap: 10px;

            animation: messageSlide 0.3s ease-out;

        }



        @keyframes messageSlide {

            from {

                opacity: 0;

                transform: translateY(20px);

            }



            to {

                opacity: 1;

                transform: translateY(0);

            }

        }



        .message.user {

            flex-direction: row-reverse;

        }



        .message-avatar {

            width: 36px;

            height: 36px;

            border-radius: 50%;

            display: flex;

            align-items: center;

            justify-content: center;

            font-size: 1.2rem;

            flex-shrink: 0;

        }



        .message.ai .message-avatar {

            background: linear-gradient(135deg, var(--accent-blue), #2563eb);

        }



        .message.user .message-avatar {

            background: linear-gradient(135deg, var(--accent-green), #059669);

        }



        .message-content {

            max-width: 75%;

            padding: 12px 16px;

            border-radius: 16px;

            line-height: 1.5;

            font-size: 0.95rem;

        }



        .message.ai .message-content {

            background: var(--bg-medium);

            color: var(--text-primary);

            border-bottom-left-radius: 4px;

        }



        .message.user .message-content {

            background: var(--accent-blue);

            color: white;

            border-bottom-right-radius: 4px;

        }



        .typing-indicator {

            display: none;

            align-items: center;

            gap: 10px;

            padding: 12px 16px;

            background: var(--bg-medium);

            border-radius: 16px;

            width: fit-content;

            margin-bottom: 16px;

        }



        .typing-indicator.show {

            display: flex;

        }



        .typing-dots {

            display: flex;

            gap: 4px;

        }



        .typing-dots span {

            width: 8px;

            height: 8px;

            border-radius: 50%;

            background: var(--text-secondary);

            animation: typingBounce 1.4s infinite ease-in-out both;

        }



        .typing-dots span:nth-child(1) {

            animation-delay: -0.32s;

        }



        .typing-dots span:nth-child(2) {

            animation-delay: -0.16s;

        }



        @keyframes typingBounce {



            0%,

            80%,

            100% {

                transform: scale(0);

            }



            40% {

                transform: scale(1.0);

            }

        }



        .input-container {

            background: var(--bg-dark);

            padding: 20px;

            border-top: 1px solid var(--bg-light);

            flex-shrink: 0;

        }



        .recording-mode {

            display: flex;

            flex-direction: column;

            align-items: center;

            gap: 16px;

        }



        .record-button-wrapper {

            position: relative;

            width: 90px;

            height: 90px;

            display: flex;

            align-items: center;

            justify-content: center;

            margin-top: 10px;

        }



        .record-button {

            width: 80px;

            height: 80px;

            border-radius: 50%;

            border: none;

            background: var(--accent-red);

            color: white;

            font-size: 2rem;

            cursor: pointer;

            box-shadow: 0 0 0 4px rgba(239, 68, 68, 0.5);

            transition: all 0.3s ease;

            z-index: 5;

            animation: pulse-red 2s infinite;

        }



        @keyframes pulse-red {

            0% {

                box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7);

            }



            70% {

                box-shadow: 0 0 0 10px rgba(239, 68, 68, 0);

            }



            100% {

                box-shadow: 0 0 0 0 rgba(239, 68, 68, 0);

            }

        }



        .record-button.recording {

            background: var(--accent-green);

            animation: none;

            box-shadow: 0 0 0 4px rgba(16, 185, 129, 0.5);

        }



        .visualizer-ring {

            position: absolute;

            width: 90px;

            height: 90px;

            border: 2px solid var(--accent-green);

            border-radius: 50%;

            opacity: 0;

            transform: scale(1);

        }



        .recording .visualizer-ring {

            animation: wave 2s infinite ease-out;

        }



        .visualizer-ring:nth-child(2) {

            animation-delay: 0.5s;

        }



        .visualizer-ring:nth-child(3) {

            animation-delay: 1s;

        }



        .visualizer-ring:nth-child(4) {

            animation-delay: 1.5s;

        }



        @keyframes wave {

            0% {

                transform: scale(1);

                opacity: 0.7;

            }



            100% {

                transform: scale(2.5);

                opacity: 0;

            }

        }



        .recording-status {

            text-align: center;

            color: var(--text-secondary);

            font-size: 0.9rem;

            height: 25px;

            display: flex;

            align-items: center;

            justify-content: center;

        }



        .lang-switcher {

            display: flex;

            justify-content: center;

            gap: 8px;

            margin-top: 8px;

            margin-bottom: 8px;

        }



        .lang-btn {

            background: var(--bg-light);

            border: none;

            color: var(--text-secondary);

            padding: 4px 12px;

            border-radius: 16px;

            font-size: 0.75rem;

            font-weight: 600;

            cursor: pointer;

            transition: all 0.2s ease;

        }



        .lang-btn:hover {

            background: var(--bg-light);

            color: var(--text-primary);

        }



        .lang-btn.active {

            background: var(--accent-blue);

            color: white;

        }

    </style>
</head>

<body>
    <div class="app-container">
        <!-- App Header -->
        <div class="app-header">
            <a href="/dispatcher" target="_blank" class="admin-panel-btn" title="Dispetcher Panel">
                <i class="bi bi-shield-lock-fill"></i> Admin Panel
            </a>
            <h1 data-translate-key="appTitle">
                Tez Tibbiy Yordam
            </h1>
        </div>

        <!-- Connection Status -->
        <div id="connection-status" class="connection-status disconnected">
            <i class="bi bi-circle-fill" style="font-size: 0.6rem; margin-right: 6px;"></i>
            <span data-translate-key="connecting">Serverga ulanmoqda...</span>
        </div>

        <!-- Chat Messages -->
        <div id="chat-container" class="chat-container">
            <!-- Salomlashuv xabari uchun joy -->
        </div>

        <!-- Input Container -->
        <div class="input-container">
            <div id="recording-mode" class="recording-mode">
                <p class="text-center" data-translate-key="speakLangs"

                    style="font-size: 0.85rem; color: var(--text-secondary); letter-spacing: 0.5px;">
                    (GAPIRING: UZB / ENG / RUS)
                </p>
                <div class="lang-switcher">
                    <button class="lang-btn active" onclick="setLanguage('uz')">UZ</button>
                    <button class="lang-btn" onclick="setLanguage('ru')">RU</button>
                    <button class="lang-btn" onclick="setLanguage('en')">EN</button>
                </div>

                <div id="record-button-wrapper" class="record-button-wrapper">
                    <div class="visualizer-ring"></div>
                    <div class="visualizer-ring"></div>
                    <div class="visualizer-ring"></div>
                    <div class="visualizer-ring"></div>
                    <button id="record-button" class="record-button">
                        <i class="bi bi-mic-fill"></i>
                    </button>
                </div>
                <div class="recording-status">
                    <span id="recording-text" data-translate-key="recordInstruction">
                        Yordam so'rash uchun tugmani bosing
                    </span>
                </div>
            </div>
        </div>
    </div>

    <script>

        // ==================== GLOBAL VARIABLES ====================

        let ws = null;

        let mediaRecorder = null;

        let audioChunks = [];

        let isRecording = false;

        let reconnectAttempts = 0;

        const MAX_RECONNECT_ATTEMPTS = 5;



        const translations = {

            uz: {

                appTitle: 'Tez Tibbiy Yordam',

                speakLangs: '(GAPIRING: UZB / ENG / RUS)',

                connecting: 'Serverga ulanmoqda...',

                connected: 'Ulandi',

                disconnected: 'Uzildi',

                connectionFailed: 'Ulanib bo\'lmadi. Sahifani yangilang.',

                recordInstruction: 'Yordam so\'rash uchun tugmani bosing',

                recording: 'Yozilmoqda... To\'xtatish uchun bosing',

                micError: 'Mikrofonni ishlatib bo\'lmadi. Ruxsat bering.',

                wsNotConnected: 'Server bilan aloqa yo\'q. Iltimos, kuting...',

                welcomeMessage: 'Assalomu alaykum! Men sizning AI yordamchingizman. Sizga qanday yordam bera olaman?'

            },

            ru: {

                appTitle: 'Скорая Помощь',

                speakLangs: '(ГОВОРИТЕ: UZB / ENG / RUS)',

                connecting: 'Соединение с сервером...',

                connected: 'Подключено',

                disconnected: 'Отключено',

                connectionFailed: 'Не удалось подключиться. Обновите страницу.',

                recordInstruction: 'Нажмите кнопку, чтобы позвать на помощь',

                recording: 'Идет запись... Нажмите, чтобы остановить',

                micError: 'Не удалось получить доступ к микрофону. Разрешите доступ.',

                wsNotConnected: 'Нет соединения с сервером. Подождите...',

                welcomeMessage: 'Здравствуйте! Я ваш AI-помощник. Чем я могу вам помочь?'

            },

            en: {

                appTitle: 'Emergency Service',

                speakLangs: '(SPEAK IN: UZB / ENG / RUS)',

                connecting: 'Connecting to server...',

                connected: 'Connected',

                disconnected: 'Disconnected',

                connectionFailed: 'Failed to connect. Please refresh the page.',

                recordInstruction: 'Press the button to call for help',

                recording: 'Recording... Press to stop',

                micError: 'Could not access the microphone. Please grant permission.',

                wsNotConnected: 'Not connected to the server. Please wait...',

                welcomeMessage: 'Hello! I am your AI assistant. How can I help you?'

            }

        };



        // ==================== DOM ELEMENTS ====================

        const chatContainer = document.getElementById('chat-container');

        const connectionStatusDiv = document.getElementById('connection-status');

        const recordButton = document.getElementById('record-button');

        const recordButtonWrapper = document.getElementById('record-button-wrapper');

        const recordingText = document.getElementById('recording-text');



        // ==================== LANGUAGE FUNCTIONALITY ====================

        function setLanguage(lang) {

            if (!translations[lang]) return;

            document.documentElement.lang = lang;

            document.querySelectorAll('[data-translate-key]').forEach(el => {

                const key = el.dataset.translateKey;

                if (translations[lang][key]) {

                    el.innerHTML = translations[lang][key];

                }

            });

            document.querySelectorAll('.lang-btn').forEach(btn => {

                btn.classList.remove('active');

                if (btn.innerText.toLowerCase() === lang) {

                    btn.classList.add('active');

                }

            });

            localStorage.setItem('preferredLanguage', lang);

            updateConnectionStatus(ws && ws.readyState === WebSocket.OPEN);

        }



        // ==================== WEBSOCKET CONNECTION ====================

        function connectWebSocket() {

            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';

            const wsUrl = `${protocol}//${window.location.host}/ws/chat`;

            console.log('🔌 WebSocket ulanish:', wsUrl);

            ws = new WebSocket(wsUrl);

            ws.onopen = () => {

                console.log('✅ WebSocket ulandi');

                reconnectAttempts = 0;

                updateConnectionStatus(true);

            };

            ws.onmessage = (event) => {

                try {

                    const data = JSON.parse(event.data);

                    console.log('📨 Xabar olindi:', data);

                    handleWebSocketMessage(data);

                } catch (e) {

                    console.error('❌ Xabar parse xatoligi:', e);

                }

            };

            ws.onerror = (error) => {

                console.error('❌ WebSocket xatolik:', error);

                updateConnectionStatus(false);

            };

            ws.onclose = () => {

                console.log('📴 WebSocket uzildi');

                updateConnectionStatus(false);

                if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {

                    reconnectAttempts++;

                    setTimeout(connectWebSocket, 3000);

                } else {

                    const lang = localStorage.getItem('preferredLanguage') || 'uz';

                    connectionStatusDiv.querySelector('span').textContent = translations[lang].connectionFailed;

                }

            };

        }



        function updateConnectionStatus(connected) {

            const lang = localStorage.getItem('preferredLanguage') || 'uz';

            const statusText = connected ? translations[lang].connected : translations[lang].disconnected;

            connectionStatusDiv.className = `connection-status ${connected ? 'connected' : 'disconnected'}`;

            connectionStatusDiv.innerHTML = `<i class="bi bi-circle-fill" style="font-size: 0.6rem; margin-right: 6px;"></i> ${statusText}`;

        }



        // ==================== MESSAGE HANDLING ====================

        function handleWebSocketMessage(data) {

            hideTypingIndicator();

            switch (data.type) {

                case 'ai_response': addMessage('ai', data.text); break;

                case 'audio_response': playAudioResponse(data.audio_url); break;

                case 'transcription_result':

                    addMessage('user', data.text);

                    showTypingIndicator();

                    break;

                case 'error': addMessage('ai', `❌ Xatolik: ${data.message}`); break;

                default: console.log('📦 Noma\'lum xabar turi:', data.type);

            }

        }



        function playAudioResponse(audioUrl) {

            try {

                console.log('🔊 Audio ijro etilmoqda:', audioUrl);

                const audio = new Audio(audioUrl);

                audio.play().catch(error => console.error('❌ Audio play xatoligi:', error));

            } catch (error) {

                console.error('❌ playAudioResponse xatoligi:', error);

            }

        }



        function addMessage(sender, text, isWelcome = false) {

            const typingIndicator = document.getElementById('typing-indicator');



            const messageDiv = document.createElement('div');

            messageDiv.className = `message ${sender}`;

            const avatar = document.createElement('div');

            avatar.className = 'message-avatar';

            avatar.innerHTML = sender === 'ai' ? '<i class="bi bi-robot"></i>' : '<i class="bi bi-person-fill"></i>';

            const content = document.createElement('div');

            content.className = 'message-content';

            content.textContent = text;

            messageDiv.appendChild(avatar);

            messageDiv.appendChild(content);



            if (isWelcome && chatContainer.children.length > 0) {

                chatContainer.insertBefore(messageDiv, chatContainer.firstChild);

            } else if (typingIndicator) {

                chatContainer.insertBefore(messageDiv, typingIndicator);

            } else {

                chatContainer.appendChild(messageDiv);

            }

            chatContainer.scrollTop = chatContainer.scrollHeight;

        }



        function showTypingIndicator() {

            const indicator = document.getElementById('typing-indicator');

            if (indicator) {

                indicator.classList.add('show');

                chatContainer.scrollTop = chatContainer.scrollHeight;

            }

        }



        function hideTypingIndicator() {

            const indicator = document.getElementById('typing-indicator');

            if (indicator) {

                indicator.classList.remove('show');

            }

        }



        // ==================== VOICE RECORDING ====================

        async function startRecording() {

            const lang = localStorage.getItem('preferredLanguage') || 'uz';

            try {

                if (!ws || ws.readyState !== WebSocket.OPEN) {

                    alert(translations[lang].wsNotConnected);

                    return;

                }

                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });

                mediaRecorder = new MediaRecorder(stream, { mimeType: 'audio/webm' });

                audioChunks = [];

                mediaRecorder.ondataavailable = event => event.data.size > 0 && audioChunks.push(event.data);

                mediaRecorder.onstop = () => {

                    sendAudioToServer(new Blob(audioChunks, { type: 'audio/webm' }));

                    stream.getTracks().forEach(track => track.stop());

                };

                mediaRecorder.start();

                isRecording = true;

                recordButton.classList.add('recording');

                recordButtonWrapper.classList.add('recording');

                recordButton.innerHTML = '<i class="bi bi-stop-fill"></i>';

                recordingText.textContent = translations[lang].recording;

            } catch (error) {

                console.error('❌ Mikrofon xatoligi:', error);

                alert(translations[lang].micError);

            }

        }



        function stopRecording() {

            if (mediaRecorder && isRecording) {

                mediaRecorder.stop();

                isRecording = false;

                const lang = localStorage.getItem('preferredLanguage') || 'uz';

                recordButton.classList.remove('recording');

                recordButtonWrapper.classList.remove('recording');

                recordButton.innerHTML = '<i class="bi bi-mic-fill"></i>';

                recordingText.textContent = translations[lang].recordInstruction;

                showTypingIndicator();

            }

        }



        async function sendAudioToServer(audioBlob) {

            try {

                const arrayBuffer = await audioBlob.arrayBuffer();

                ws.send(new Uint8Array(arrayBuffer));

                ws.send('__END__');

            } catch (error) {

                console.error('❌ Audio yuborishda xatolik:', error);

                hideTypingIndicator();

            }

        }



        // ==================== EVENT LISTENERS ====================

        recordButton.addEventListener('click', () => isRecording ? stopRecording() : startRecording());



        // ==================== INITIALIZATION ====================

        function initialize() {

            const savedLang = localStorage.getItem('preferredLanguage') || 'uz';

            setLanguage(savedLang);

            connectWebSocket();

            const lang = localStorage.getItem('preferredLanguage') || 'uz';



            const welcomeMessageHTML = `

                <div class="message ai">

                    <div class="message-avatar"><i class="bi bi-robot"></i></div>

                    <div class="message-content">${translations[lang].welcomeMessage}</div>

                </div>`;



            const typingIndicatorHTML = `

                <div id="typing-indicator" class="message ai typing-indicator">

                    <div class="message-avatar"><i class="bi bi-robot"></i></div>

                    <div class="message-content">

                        <div class="typing-dots">

                            <span></span><span></span><span></span>

                        </div>

                    </div>

                </div>`;



            chatContainer.innerHTML = welcomeMessageHTML + typingIndicatorHTML;

        }



        document.addEventListener('DOMContentLoaded', initialize);

    </script>
</body>

</html>