File size: 23,567 Bytes
3910b9e
 
 
 
 
 
e53daf8
3910b9e
e53daf8
3910b9e
 
e53daf8
3910b9e
 
 
 
 
e53daf8
 
 
 
3910b9e
e53daf8
3910b9e
 
 
 
e53daf8
 
 
cc9fda7
 
3910b9e
cc9fda7
3910b9e
 
e53daf8
 
 
 
 
 
3910b9e
 
 
 
cc9fda7
 
e53daf8
 
 
3910b9e
 
 
e53daf8
 
 
3910b9e
e53daf8
 
3910b9e
 
 
 
 
e53daf8
3910b9e
 
 
 
e53daf8
3910b9e
 
 
e53daf8
3910b9e
 
e53daf8
 
 
 
3910b9e
 
 
e53daf8
 
3910b9e
 
e53daf8
3910b9e
 
 
 
e53daf8
 
3910b9e
 
e53daf8
3910b9e
 
 
e53daf8
3910b9e
 
e53daf8
 
3910b9e
 
 
e53daf8
 
 
 
3910b9e
 
 
e53daf8
 
 
 
 
 
3910b9e
 
 
 
e53daf8
3910b9e
 
 
 
 
 
e53daf8
3910b9e
 
e53daf8
 
3910b9e
 
98092f5
 
 
 
 
 
 
 
 
3910b9e
e53daf8
3910b9e
 
 
e53daf8
3910b9e
 
 
 
 
 
e53daf8
 
3910b9e
 
e53daf8
 
 
3910b9e
 
 
 
e53daf8
 
 
 
 
3910b9e
 
 
e53daf8
3910b9e
 
e53daf8
 
3910b9e
 
 
 
 
e53daf8
 
 
 
 
3910b9e
 
e53daf8
 
 
 
 
 
 
 
 
3910b9e
e53daf8
 
 
 
 
 
 
 
3910b9e
e53daf8
 
 
 
3910b9e
 
e53daf8
 
3910b9e
e53daf8
 
3910b9e
 
 
 
e53daf8
 
 
 
3910b9e
 
 
 
 
 
 
 
 
 
 
 
e53daf8
3910b9e
 
e53daf8
3910b9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8dc6bca
 
3910b9e
98092f5
 
 
 
 
 
 
 
 
 
3910b9e
 
 
98092f5
3910b9e
 
 
 
 
8dc6bca
 
 
 
 
 
 
 
 
3910b9e
8dc6bca
2a507e3
 
 
3910b9e
2a507e3
8dc6bca
 
 
 
 
 
 
2a507e3
8dc6bca
 
 
3910b9e
 
 
 
 
 
8dc6bca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b336189
8dc6bca
 
b336189
8dc6bca
 
 
 
 
 
b336189
8dc6bca
 
 
3910b9e
2a507e3
3910b9e
 
 
 
 
 
2a507e3
3910b9e
 
e441398
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8dc6bca
 
 
3910b9e
 
 
 
 
 
 
 
 
 
 
 
 
 
c7920aa
e441398
6a7ee8f
c7920aa
 
 
 
 
 
 
8dc6bca
6a7ee8f
2a507e3
8dc6bca
e441398
 
8dc6bca
 
 
 
e441398
 
2a507e3
 
8dc6bca
3910b9e
c7920aa
 
 
 
 
 
 
 
 
 
 
3910b9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e53daf8
3910b9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98092f5
108e51d
98092f5
 
 
 
 
 
 
 
 
3910b9e
98092f5
 
 
 
 
3910b9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Martechsol Assistant Widget</title>
<style>

    /* Premium Design for Martechsol Assistant */

    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap');



    #martech-chat-wrapper {

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

    }



    /* Floating Action Button (FAB) */

    #martech-chat-fab {

        position: fixed;

        right: 10px;

        bottom: 25px;

        width: auto;

        height: auto;

        background: transparent;

        border-radius: 50%;

        display: flex;

        align-items: center;

        justify-content: center;

        cursor: pointer;

        z-index: 999999;

        transition: transform 0.4s cubic-bezier(0.34, 1.56, 0.64, 1), background 0.3s ease, box-shadow 0.3s ease;

        -webkit-tap-highlight-color: transparent;

    }



    #martech-chat-fab:hover {

        transform: scale(1.1);

    }



    #martech-chat-fab.is-active {

        background: #1e293b;

        box-shadow: 0 10px 25px rgba(30, 41, 59, 0.4);

        transform: scale(0.8);

    }



    /* Chat Window Styling */

    #martech-chat-box {

        position: fixed;

        right: 25px;

        bottom: 100px;

        width: 400px;

        height: 550px;

        background: #ffffff;

        border-radius: 16px;

        overflow: hidden;

        display: none;

        flex-direction: column;

        box-shadow: 0 12px 50px rgba(0, 0, 0, 0.2);

        z-index: 999998;

        border: 1px solid #e2e8f0;

        opacity: 0;

        transform: translateY(20px);

        transition: opacity 0.3s ease, transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);

    }



    #martech-chat-box.is-visible {

        display: flex;

        opacity: 1;

        transform: translateY(0);

    }



    #martech-chat-header {

        background: #ffffff;

        padding: 16px 20px;

        border-bottom: 1px solid #f1f5f9;

        display: flex;

        align-items: center;

        gap: 12px;

    }



    @keyframes pulse-dot {

        0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); }

        70% { transform: scale(1.1); box-shadow: 0 0 0 10px rgba(16, 185, 129, 0); }

        100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }

    }



    #martech-chat-header .dot {

        width: 10px;

        height: 10px;

        background: #10b981;

        border-radius: 50%;

        animation: pulse-dot 2s infinite;

    }



    #martech-chat-header span {

        font-weight: 600;

        color: #1e293b;

        font-size: 15px;

    }



    /* Custom Chat Area Styling */

    #chat-messages {

        flex: 1;

        overflow-y: auto;

        padding: 16px;

        display: flex;

        flex-direction: column;

        gap: 12px;

        background: #f8fafc;

        scroll-behavior: smooth;

    }



    /* Custom Scrollbar for messages */

    #chat-messages::-webkit-scrollbar { width: 6px; }

    #chat-messages::-webkit-scrollbar-track { background: transparent; }

    #chat-messages::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }



    .chat-message {

        max-width: 85%;

        padding: 12px 16px;

        border-radius: 16px;

        font-size: 14px;

        line-height: 1.5;

        word-wrap: break-word;

        white-space: pre-wrap;

    }



    .chat-message.user {

        align-self: flex-end;

        background: #1e293b;

        color: white;

        border-bottom-right-radius: 4px;

    }



    .chat-message.bot {

        align-self: flex-start;

        background: #ffffff;

        color: #334155;

        border-bottom-left-radius: 4px;

        border: 1px solid #e2e8f0;

        box-shadow: 0 2px 4px rgba(0,0,0,0.02);

    }



    /* Surgical Bolding & List Style */

    .chat-message b {

        font-weight: 800;

        color: #0f172a;

    }

    .chat-message.user b {

        color: #ffffff;

    }



    #chat-input-area {

        padding: 16px;

        background: #ffffff;

        border-top: 1px solid #f1f5f9;

        display: flex;

        gap: 8px;

        align-items: center;

    }



    #chat-input {

        flex: 1;

        border: 1px solid #e2e8f0;

        border-radius: 20px;

        padding: 12px 16px;

        font-size: 14px;

        outline: none;

        transition: border-color 0.2s;

        font-family: inherit;

        box-shadow: inset 0 1px 2px rgba(0,0,0,0.02);

    }



    #chat-input:focus {

        border-color: #10b981;

    }



    #chat-input:disabled {

        background: #f1f5f9;

        cursor: not-allowed;

    }



    #chat-send {

        background: #10b981;

        color: white;

        border: none;

        width: 44px;

        height: 44px;

        border-radius: 50%;

        display: flex;

        align-items: center;

        justify-content: center;

        cursor: pointer;

        transition: background 0.2s, transform 0.1s;

    }



    #chat-send:hover {

        background: #059669;

    }



    #chat-send:active {

        transform: scale(0.95);

    }



    #chat-send:disabled {

        background: #cbd5e1;

        cursor: not-allowed;

        transform: none;

    }



    /* Loading / Typing Animation */

    .typing-indicator {

        display: flex;

        gap: 4px;

        padding: 4px 2px;

        align-items: center;

        height: 18px;

    }

    .typing-indicator span {

        width: 6px;

        height: 6px;

        background: #94a3b8;

        border-radius: 50%;

        animation: typing-dots 1.4s infinite ease-in-out both;

    }

    .typing-indicator span:nth-child(1) { animation-delay: -0.32s; }

    .typing-indicator span:nth-child(2) { animation-delay: -0.16s; }

    @keyframes typing-dots {

        0%, 80%, 100% { transform: scale(0); }

        40% { transform: scale(1); }

    }



    @media (max-width: 480px) {

        #martech-chat-box {

            right: 15px;

            bottom: 100px;

            width: calc(100vw - 30px);

            height: 70vh;

        }

    }

</style>
</head>
<body>

<!-- Lottie Player Script -->
<script src="https://unpkg.com/@dotlottie/player-component@latest/dist/dotlottie-player.mjs" type="module"></script>

<div id="martech-chat-wrapper">
    <div id="martech-chat-fab">
        <!-- Animated Chatbot Icon -->
        <div id="chat-icon" style="width: 233px; height: 238px; display: flex; align-items: center; justify-content: center; pointer-events: none;">
            <dotlottie-player

                src="https://joedown11-chatrag.hf.space/static/bot-icon.lottie"

                background="transparent" speed="1" style="width: 100%; height: 100%; will-change: transform;" loop autoplay>
            </dotlottie-player>
        </div>
        <!-- Close Icon -->
        <svg id="close-icon" viewBox="0 0 24 24" style="display:none; width: 60px; height: 60px;">
            <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" fill="white" />
        </svg>
    </div>

    <div id="martech-chat-box">
        <div id="martech-chat-header">
            <div class="dot"></div>
            <span>Martechsol Assistant</span>
        </div>
        
        <!-- Custom Chat UI replacing iframe -->
        <div id="chat-messages">
            <div class="chat-message bot">Welcome! How can I help you today?</div>
        </div>
        
        <div id="chat-input-area">
            <input type="text" id="chat-input" placeholder="Type your question here..." autocomplete="off" />
            <button id="chat-send" title="Send">
                <!-- Send Icon -->
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <line x1="22" y1="2" x2="11" y2="13"></line>
                    <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
                </svg>
            </button>
        </div>
    </div>
</div>

<script>

(function () {

    // UI Elements

    const fab = document.getElementById('martech-chat-fab');

    const box = document.getElementById('martech-chat-box');

    const chatIcon = document.getElementById('chat-icon');

    const closeIcon = document.getElementById('close-icon');

    const messagesContainer = document.getElementById('chat-messages');

    const inputField = document.getElementById('chat-input');

    const sendButton = document.getElementById('chat-send');



    // FAB Toggle Logic

    fab.addEventListener('click', function () {

        const isVisible = box.classList.contains('is-visible');

        if (isVisible) {

            box.classList.remove('is-visible');

            setTimeout(() => { box.style.display = 'none'; }, 300);

            chatIcon.style.display = 'block';

            closeIcon.style.display = 'none';

            fab.classList.remove('is-active');

        } else {

            box.style.display = 'flex';

            setTimeout(() => { box.classList.add('is-visible'); inputField.focus(); }, 10);

            chatIcon.style.display = 'none';

            closeIcon.style.display = 'block';

            fab.classList.add('is-active');

        }

    });



    // Chat Logic

    const API_URL = "https://joedown11-chatrag.hf.space/api/chat";

    const BASE_URL = API_URL.replace("/api/chat", "");

    let chatHistory = [];



    // ── Session ID: generate once, persist in localStorage ──

    let sessionId = localStorage.getItem('martech_session_id');

    if (!sessionId) {

        // Use a temporary name/id until we get the real one

        sessionId = 'user-' + Date.now() + '-' + Math.random().toString(36).slice(2, 9);

        localStorage.setItem('martech_session_id', sessionId);

    }

    // Bug fix: if existing session is still a generic temp ID, mark it for re-resolution

    const _isGenericId = (id) => id && id.startsWith('user-') && /^user-\d+-[a-z0-9]+$/.test(id);



    function formatMessage(text) {

        if (!text) return "";

        // 1. Convert Markdown Bold to HTML Bold (safety)

        let formatted = text.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>');

        // 2. Remove the '*' at the start of lines and use a bullet

        formatted = formatted.replace(/^\* /gm, 'β€’ ');

        // 3. Newlines to BR

        return formatted.replace(/\n/g, '<br>');

    }



    function appendMessage(role, content) {

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

        div.className = `chat-message ${role}`;

        div.innerHTML = formatMessage(content);

        messagesContainer.appendChild(div);

        messagesContainer.scrollTop = messagesContainer.scrollHeight;

        return div;

    }



    // ── Shared helper: resolve user name from all 3 options ─────────────────

    async function _resolveUserName() {

        // ── OPTION 0: Window injection by HR portal (fastest, zero cost) ──

        // The HR portal page sets window.HR_USER_NAME = "John Doe" before this script loads

        if (window.HR_USER_NAME && typeof window.HR_USER_NAME === 'string' && window.HR_USER_NAME.trim().length > 1) {

            return window.HR_USER_NAME.trim();

        }



        // ── OPTION 1: Scan localStorage / sessionStorage for profile objects ──

        try {

            const storageKeys = ['userInfo', 'user', 'profile', 'auth', 'currentUser', 'account', 'userData', 'loginUser'];

            for (const key of storageKeys) {

                const stored = localStorage.getItem(key) || sessionStorage.getItem(key);

                if (stored) {

                    try {

                        const parsed = JSON.parse(stored);

                        // Covers: {name}, {fullName}, {user:{name}}, {display_name}, {personalDetails:{fullName}}

                        const found = parsed.name

                            || parsed.fullName

                            || (parsed.user && parsed.user.name)

                            || parsed.display_name

                            || (parsed.personalDetails && parsed.personalDetails.fullName);

                        if (found && found.trim().length > 1) return found.trim();

                    } catch(err) {

                        // Plain string value (e.g. name stored directly)

                        if (typeof stored === 'string' && stored.length < 80 && !stored.includes('{')) {

                            return stored.trim();

                        }

                    }

                }

            }

        } catch (e) {}



        // ── OPTION 2: Call the HR profile API directly ──

        // API confirmed to return: { name: "Ghulam Baqir", ... }

        try {

            const tokenKeys = ['token', 'accessToken', 'access_token', 'authToken', 'auth_token', 'jwt', 'jwtToken'];

            let authToken = null;

            for (const tk of tokenKeys) {

                const tv = localStorage.getItem(tk) || sessionStorage.getItem(tk);

                if (tv && tv.length > 20) { authToken = tv.replace(/^Bearer\s+/i, ''); break; }

            }

            const headers = { 'Content-Type': 'application/json' };

            if (authToken) headers['Authorization'] = 'Bearer ' + authToken;



            const pResp = await fetch("https://hrmmartechsol-ba71e8dc3fa2.herokuapp.com/api/users/profile", {

                headers: headers,

                credentials: 'include'   // also sends cookies (session-based auth)

            });

            if (pResp.ok) {

                const pData = await pResp.json();

                // API top-level 'name' field is confirmed; personalDetails.fullName is fallback

                const found = pData.name || (pData.personalDetails && pData.personalDetails.fullName);

                if (found && found.trim().length > 1) return found.trim();

            }

        } catch (e) {}



        return null;  // all options exhausted

    }



    // ── User Integration & History ──────────────────────────────────────────

    async function initUserSession() {



        // Bug fix: if this is a returning visit but the stored ID is still a generic

        // temp ID (resolution failed last time), retry resolution now

        const needsResolution = _isGenericId(sessionId);



        let userName = await _resolveUserName();



        // Multi-user logic: if name changed since last visit, start a fresh session

        const lastKnownName = localStorage.getItem('martech_last_user_name');

        if (userName && lastKnownName && userName !== lastKnownName) {

            localStorage.removeItem('martech_session_id');

            sessionId = 'user-' + Date.now() + '-' + Math.random().toString(36).slice(2, 9);

            localStorage.setItem('martech_session_id', sessionId);

            messagesContainer.innerHTML = '<div class="chat-message bot">Welcome! How can I help you today?</div>';

        }

        if (userName) {

            localStorage.setItem('martech_last_user_name', userName);

        }



        // ── PRE-CREATE SESSION AT BACKEND ON WIDGET LOAD ────────────────────

        // This creates the session with the user's name BEFORE the user even

        // opens the chat window, so it is immediately visible in the admin panel.

        try {

            const initData = await fetch(BASE_URL + "/api/session/init", {

                method: 'POST',

                headers: { 'Content-Type': 'application/json' },

                body: JSON.stringify({ session_id: sessionId, user_name: userName || null })

            }).then(r => r.json());

            // Backend may return a canonical named session_id (e.g. "Ali_Hassan")

            if (initData.session_id && initData.session_id !== sessionId) {

                sessionId = initData.session_id;

                localStorage.setItem('martech_session_id', sessionId);

            }

        } catch (e) {

            // Non-fatal: session will still be created on first message if this fails

            console.warn('Martech: background session pre-creation failed', e);

        }



        // Now fetch history using the finalized session ID

        try {

            const hResp = await fetch(BASE_URL + "/api/session/history/" + sessionId);

            if (hResp.ok) {

                const hData = await hResp.json();

                if (hData.history && hData.history.length > 0) {

                    messagesContainer.innerHTML = '';

                    chatHistory = hData.history;

                    chatHistory.forEach(m => {

                        appendMessage(m.role === 'assistant' ? 'bot' : 'user', m.content);

                    });

                }

            }

        } catch (e) {}



        // If name still not found, set up continuous lightweight background resolution

        // so the session gets named as soon as auth is available

        if (!userName) {

            let _isResolving = false;

            

            const _attemptSync = async () => {

                // Stop checking if we already got a real name, or if a check is currently running

                if (!_isGenericId(sessionId) || _isResolving) return;

                

                _isResolving = true;

                const resolved = await _resolveUserName();

                if (resolved) {

                    localStorage.setItem('martech_last_user_name', resolved);

                    try {

                        // Re-init with the now-known name to promote temp β†’ named session

                        const rData = await fetch(BASE_URL + "/api/session/init", {

                            method: 'POST',

                            headers: { 'Content-Type': 'application/json' },

                            body: JSON.stringify({ session_id: sessionId, user_name: resolved })

                        }).then(r => r.json());

                        if (rData.session_id && rData.session_id !== sessionId) {

                            sessionId = rData.session_id;

                            localStorage.setItem('martech_session_id', sessionId);

                        }

                    } catch (e) {}

                }

                _isResolving = false;

            };



            // Event 1: Instantly trigger when the main app writes a token to storage

            window.addEventListener('storage', _attemptSync);

            

            // Event 2: Instantly trigger when user refocuses the tab (e.g. after auth redirect)

            window.addEventListener('focus', _attemptSync);



            // Fallback: Check every 15 seconds (virtually zero cost once session is named)

            setInterval(_attemptSync, 15000);

        }

    }



    initUserSession();



    function showTypingIndicator() {

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

        div.className = 'chat-message bot';

        div.innerHTML = '<div class="typing-indicator"><span></span><span></span><span></span></div>';

        messagesContainer.appendChild(div);

        messagesContainer.scrollTop = messagesContainer.scrollHeight;

        return div;

    }



    // Typo Configuration for Human-like Typing

    const NEARBY_KEYS = {

        'a': 'sqwz', 'b': 'vghn', 'c': 'xdfv', 'd': 'sfecx', 'e': 'wrsdf',

        'f': 'dgrtcv', 'g': 'fhtybn', 'h': 'gjyunb', 'i': 'uojkl', 'j': 'hkunmi',

        'k': 'jlomi', 'l': 'kop', 'm': 'njk', 'n': 'bhjm', 'o': 'ipkl',

        'p': 'ol', 'q': 'wa', 'r': 'edft', 's': 'awedxz', 't': 'rfgy',

        'u': 'yihj', 'v': 'cfgb', 'w': 'qase', 'x': 'zsdc', 'y': 'tghu',

        'z': 'xas',

    };

    const TYPO_CHANCE = 0.07;



    function getNearbyChar(ch) {

        const lower = ch.toLowerCase();

        if (NEARBY_KEYS[lower]) {

            const options = NEARBY_KEYS[lower];

            const replacement = options.charAt(Math.floor(Math.random() * options.length));

            return ch === ch.toUpperCase() ? replacement.toUpperCase() : replacement;

        }

        const abc = "abcdefghijklmnopqrstuvwxyz";

        return abc.charAt(Math.floor(Math.random() * abc.length));

    }



    const sleep = ms => new Promise(r => setTimeout(r, ms));



    async function typeMessageWithTypos(element, text) {

        const fullHtml = formatMessage(text);

        

        // Simple HTML-aware typing: split by tags

        const tokens = fullHtml.split(/(<[^>]*>)/);

        let currentHtml = "";

        

        for (const token of tokens) {

            if (token.startsWith("<")) {

                // Instantly add tags

                currentHtml += token;

                element.innerHTML = currentHtml;

            } else {

                // Type text content char by char

                for (let char of token) {

                    currentHtml += char;

                    element.innerHTML = currentHtml;

                    await sleep(Math.random() * 15 + 5);

                }

            }

            messagesContainer.scrollTop = messagesContainer.scrollHeight;

        }

    }



    async function handleSend() {

        const text = inputField.value.trim();

        if (!text) return;



        // UI state lock

        inputField.value = '';

        inputField.disabled = true;

        sendButton.disabled = true;



        appendMessage('user', text);

        const typingEl = showTypingIndicator();



        try {

            // Call the FastAPI Backend directly

            const response = await fetch(API_URL, {

                method: 'POST',

                headers: { 'Content-Type': 'application/json' },

                body: JSON.stringify({ 

                    message: text, 

                    history: chatHistory,

                    session_id: sessionId

                })

            });



            if (!response.ok) {

                if (response.status === 429) throw new Error("Rate limit exceeded.");

                throw new Error("Server error.");

            }



            const data = await response.json();

            const reply = data.reply;



            typingEl.remove();

            const botEl = appendMessage('bot', '');



            // Update local memory

            chatHistory.push({ role: "user", content: text });

            chatHistory.push({ role: "assistant", content: reply });



            // Stream text out

            await typeMessageWithTypos(botEl, reply);



        } catch (error) {

            console.error(error);

            typingEl.remove();

            appendMessage('bot', "⚠️ I'm sorry, I encountered an error. Please try again.");

        } finally {

            inputField.disabled = false;

            sendButton.disabled = false;

            inputField.focus();

        }

    }



    // Event Listeners

    sendButton.addEventListener('click', handleSend);

    inputField.addEventListener('keypress', function(e) {

        if (e.key === 'Enter') handleSend();

    });



})();

</script>

</body>
</html>