File size: 38,574 Bytes
f4a40f2
0261885
f4a40f2
6c86393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4a40f2
6c86393
0261885
6c86393
0261885
6c86393
 
 
 
 
 
 
 
 
f4a40f2
6c86393
 
 
 
 
 
 
 
 
 
 
195ec86
6c86393
 
 
 
 
f3977be
6c86393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195ec86
f3977be
6c86393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3977be
0261885
f3977be
6c86393
f3977be
6c86393
 
 
 
 
 
 
 
 
f3977be
6c86393
 
 
 
 
 
 
 
 
 
 
 
0261885
6c86393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0261885
f4a40f2
0261885
6c86393
 
 
f3977be
6c86393
 
 
195ec86
6c86393
f3977be
6c86393
 
 
 
 
 
 
f3977be
 
6c86393
 
 
 
 
f3977be
6c86393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3977be
f4a40f2
6c86393
 
 
 
 
 
 
 
0261885
6c86393
 
 
f3977be
6c86393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3977be
6c86393
 
 
 
 
 
 
 
f3977be
 
6c86393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3977be
6c86393
 
 
195ec86
f3977be
6c86393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3977be
6c86393
 
 
 
f3977be
 
6c86393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0261885
6c86393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195ec86
6c86393
f3977be
6c86393
 
 
 
 
0261885
6c86393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0261885
6c86393
 
 
195ec86
6c86393
 
195ec86
6c86393
0261885
6c86393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0261885
 
6c86393
 
 
 
 
 
 
 
 
0261885
f4a40f2
195ec86
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Arjun Compound | Advanced AI</title>
    
    <!-- Fonts & Icons -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=Fira+Code:wght@400;500&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Markdown & Syntax Highlighting -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/12.0.1/marked.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>

    <style>
        /* --- CORE VARIABLES --- */
        :root {
            --bg-main: #F5F5F7; --bg-panel: #FFFFFF;
            --text-dark: #1D1D1F; --text-muted: #86868B;
            --accent-blue: #007AFF; --accent-hover: #0056b3;
            --danger: #FF3B30; --success: #34C759;
            --border-light: rgba(0,0,0,0.08); --border-focus: rgba(0, 122, 255, 0.3);
            --shadow-sm: 0 4px 12px rgba(0,0,0,0.05); --shadow-md: 0 12px 32px rgba(0,0,0,0.08);
            --font-sans: 'Plus Jakarta Sans', sans-serif; --font-mono: 'Fira Code', monospace;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; -webkit-font-smoothing: antialiased; }
        body { font-family: var(--font-sans); background: var(--bg-main); color: var(--text-dark); height: 100dvh; width: 100vw; overflow: hidden; display: flex; }

        /* --- TOAST NOTIFICATIONS --- */
        #toast-container { position: absolute; top: 20px; left: 50%; transform: translateX(-50%); z-index: 10000; display: flex; flex-direction: column; gap: 10px; }
        .toast { background: var(--text-dark); color: #fff; padding: 12px 24px; border-radius: 50px; font-size: 14px; font-weight: 600; box-shadow: var(--shadow-md); animation: slideDown 0.4s ease; display: flex; align-items: center; gap: 10px; }
        @keyframes slideDown { from { opacity: 0; transform: translateY(-20px); } to { opacity: 1; transform: translateY(0); } }

        /* --- LAYOUT SHELL --- */
        .app-shell { display: flex; width: 100%; height: 100%; position: relative; }

        /* --- SIDEBAR --- */
        .sidebar { width: 300px; background: var(--bg-panel); border-right: 1px solid var(--border-light); display: flex; flex-direction: column; flex-shrink: 0; transition: transform 0.3s ease; z-index: 100; }
        .brand-header { padding: 24px; border-bottom: 1px solid var(--border-light); display: flex; justify-content: space-between; align-items: center; }
        .brand-info h1 { font-size: 20px; font-weight: 800; letter-spacing: -0.5px; }
        .brand-info p { font-size: 11px; color: var(--text-muted); font-weight: 600; text-transform: uppercase; letter-spacing: 1px; margin-top: 2px; }
        .close-sidebar-btn { display: none; background: none; border: none; font-size: 20px; color: var(--text-dark); cursor: pointer; }

        .auth-section { padding: 20px; border-bottom: 1px solid var(--border-light); }
        .btn-primary { width: 100%; padding: 14px; background: var(--text-dark); color: #fff; border: none; border-radius: 14px; font-size: 14px; font-weight: 700; cursor: pointer; transition: 0.2s; display: flex; align-items: center; justify-content: center; gap: 8px; }
        .btn-primary:hover { background: #333; transform: translateY(-1px); box-shadow: var(--shadow-sm); }
        
        /* Logged In User Profile */
        .user-profile { display: none; align-items: center; justify-content: space-between; background: var(--bg-main); padding: 12px 16px; border-radius: 14px; border: 1px solid var(--border-light); }
        .user-details { display: flex; align-items: center; gap: 12px; overflow: hidden; }
        .user-avatar { width: 36px; height: 36px; border-radius: 50%; background: var(--accent-blue); color: #fff; display: flex; align-items: center; justify-content: center; font-weight: 700; flex-shrink: 0; }
        .user-email { font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 140px;}
        .btn-logout { background: none; border: none; color: var(--danger); cursor: pointer; font-size: 16px; padding: 8px; border-radius: 8px; transition: 0.2s; }
        .btn-logout:hover { background: #FFEBEE; }

        .sidebar-menu { padding: 20px; flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 10px; }
        .menu-btn { width: 100%; padding: 14px; text-align: left; background: transparent; border: 1px solid transparent; border-radius: 12px; font-size: 14px; font-weight: 600; color: var(--text-dark); cursor: pointer; transition: 0.2s; display: flex; align-items: center; gap: 12px; }
        .menu-btn:hover { background: var(--bg-main); border-color: var(--border-light); }
        .menu-btn.danger { color: var(--danger); margin-top: auto; border: 1px solid var(--border-light); }
        .menu-btn.danger:hover { background: #FFEBEE; border-color: var(--danger); }

        /* --- MAIN WORKSPACE --- */
        .main-area { flex: 1; display: flex; flex-direction: column; position: relative; min-width: 0; background: var(--bg-main); }
        
        .top-nav { height: 60px; padding: 0 24px; display: flex; align-items: center; gap: 16px; background: rgba(245,245,247,0.8); backdrop-filter: blur(10px); border-bottom: 1px solid var(--border-light); z-index: 10; }
        .hamburger { background: none; border: none; font-size: 20px; color: var(--text-dark); cursor: pointer; display: none; padding: 8px; border-radius: 8px; }
        .nav-title { font-size: 15px; font-weight: 700; display: flex; align-items: center; gap: 8px; }
        .nav-status { width: 8px; height: 8px; background: var(--success); border-radius: 50%; box-shadow: 0 0 0 2px rgba(52,199,89,0.2); }

        /* --- CHAT HISTORY --- */
        .chat-container { flex: 1; overflow-y: auto; padding: 30px 40px; display: flex; flex-direction: column; gap: 24px; scroll-behavior: smooth; }
        .chat-container::-webkit-scrollbar { width: 6px; }
        .chat-container::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.15); border-radius: 10px; }

        .welcome-screen { margin: auto; text-align: center; max-width: 600px; animation: fadeIn 0.5s ease; }
        .welcome-icon { font-size: 48px; margin-bottom: 20px; background: -webkit-linear-gradient(45deg, var(--text-dark), var(--accent-blue)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
        .welcome-title { font-size: 32px; font-weight: 800; margin-bottom: 10px; letter-spacing: -0.5px; }
        .welcome-desc { color: var(--text-muted); font-size: 15px; line-height: 1.6; margin-bottom: 30px; }
        
        .guest-badge { display: inline-flex; align-items: center; gap: 8px; background: #FFF4E5; color: #FF9500; padding: 8px 16px; border-radius: 20px; font-size: 13px; font-weight: 700; border: 1px solid #FFE0B2; margin-bottom: 20px; }

        .msg-row { display: flex; gap: 16px; max-width: 85%; animation: slideUp 0.3s ease; }
        @keyframes slideUp { from { opacity: 0; transform: translateY(15px); } to { opacity: 1; transform: translateY(0); } }
        .msg-row.user { align-self: flex-end; flex-direction: row-reverse; }
        .msg-row.bot { align-self: flex-start; }
        
        .avatar { width: 36px; height: 36px; border-radius: 50%; display: flex; justify-content: center; align-items: center; font-size: 14px; font-weight: 700; flex-shrink: 0; box-shadow: var(--shadow-sm); }
        .msg-row.user .avatar { background: var(--text-dark); color: #fff; }
        .msg-row.bot .avatar { background: #fff; color: var(--accent-blue); border: 1px solid var(--border-light); }

        .msg-bubble { padding: 16px 20px; border-radius: 20px; font-size: 15px; line-height: 1.6; word-wrap: break-word; overflow-wrap: anywhere; box-shadow: var(--shadow-sm); }
        .msg-row.user .msg-bubble { background: var(--text-dark); color: #fff; border-top-right-radius: 4px; }
        .msg-row.bot .msg-bubble { background: var(--bg-panel); color: var(--text-dark); border-top-left-radius: 4px; border: 1px solid var(--border-light); width: 100%; }

        /* Markdown Styles */
        .msg-bubble p { margin-bottom: 12px; }
        .msg-bubble p:last-child { margin-bottom: 0; }
        .msg-bubble code { font-family: var(--font-mono); background: rgba(0,0,0,0.05); padding: 3px 6px; border-radius: 6px; font-size: 0.9em; color: #E91E63; }
        .msg-row.user .msg-bubble code { background: rgba(255,255,255,0.2); color: #fff; }
        .msg-bubble pre { background: #1E1E1E; padding: 16px; border-radius: 12px; overflow-x: auto; margin: 12px 0; border: 1px solid #333; }
        .msg-bubble pre code { background: transparent; color: #D4D4D4; padding: 0; }
        .msg-bubble img { max-width: 100%; border-radius: 12px; margin: 10px 0; box-shadow: var(--shadow-sm); }
        .copy-btn { background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.2); color: #fff; padding: 4px 10px; border-radius: 6px; font-size: 11px; cursor: pointer; float: right; margin-bottom: 8px; }

        /* Attachment Previews in Chat */
        .chat-attachment { display: flex; align-items: center; gap: 10px; background: rgba(255,255,255,0.1); padding: 8px 12px; border-radius: 10px; border: 1px solid rgba(255,255,255,0.2); margin-bottom: 8px; font-size: 12px; }
        .chat-attachment i { font-size: 16px; }
        .msg-row.bot .chat-attachment { background: rgba(0,0,0,0.04); border-color: rgba(0,0,0,0.1); }

        /* --- INPUT AREA --- */
        .input-zone { padding: 0 40px 30px; background: linear-gradient(to top, var(--bg-main) 70%, transparent); position: relative; z-index: 20; }
        .input-wrapper { background: rgba(255,255,255,0.9); backdrop-filter: blur(20px); border: 1px solid var(--border-light); border-radius: 24px; box-shadow: var(--shadow-md); display: flex; flex-direction: column; transition: 0.3s; }
        .input-wrapper:focus-within { border-color: var(--border-focus); box-shadow: 0 12px 40px rgba(0,122,255,0.15); }

        /* File Preview Area */
        .file-preview { display: none; padding: 16px 20px 0; align-items: center; gap: 12px; border-bottom: 1px solid rgba(0,0,0,0.05); padding-bottom: 12px; margin: 12px 20px 0; }
        .file-preview.active { display: flex; }
        .file-thumb { width: 40px; height: 40px; border-radius: 8px; object-fit: cover; background: #f0f0f0; display: flex; justify-content: center; align-items: center; font-size: 20px; color: var(--text-muted); }
        .file-info { flex: 1; overflow: hidden; }
        .file-name { font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .file-meta { font-size: 11px; color: var(--text-muted); }
        .remove-file { background: #FFEBEE; color: var(--danger); border: none; width: 28px; height: 28px; border-radius: 50%; cursor: pointer; display: flex; justify-content: center; align-items: center; transition: 0.2s; }
        .remove-file:hover { background: var(--danger); color: #fff; }

        .input-row { display: flex; align-items: flex-end; gap: 12px; padding: 12px 16px 12px 20px; }
        
        .action-icon-btn { width: 40px; height: 40px; border-radius: 12px; background: transparent; border: none; font-size: 18px; color: var(--text-muted); cursor: pointer; display: flex; justify-content: center; align-items: center; transition: 0.2s; position: relative; overflow: hidden; }
        .action-icon-btn:hover { background: rgba(0,0,0,0.05); color: var(--text-dark); }
        .action-icon-btn input[type="file"] { position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%; }
        
        /* Voice Active Animation */
        .action-icon-btn.recording { color: var(--danger); animation: pulseRecord 1.5s infinite; }
        @keyframes pulseRecord { 0% { background: rgba(255,59,48,0.1); } 50% { background: rgba(255,59,48,0.3); } 100% { background: rgba(255,59,48,0.1); } }

        .chat-input { flex: 1; border: none; outline: none; background: transparent; font-family: var(--font-sans); font-size: 15px; color: var(--text-dark); resize: none; min-height: 24px; max-height: 200px; padding: 8px 0; line-height: 1.5; }
        
        .send-btn { width: 44px; height: 44px; border-radius: 14px; border: none; background: var(--text-dark); color: #fff; display: flex; justify-content: center; align-items: center; cursor: pointer; transition: 0.2s; box-shadow: 0 4px 12px rgba(0,0,0,0.1); flex-shrink: 0; }
        .send-btn:hover { background: #333; transform: translateY(-2px); box-shadow: 0 6px 16px rgba(0,0,0,0.2); }
        .send-btn:disabled { background: #ccc; cursor: not-allowed; transform: none; box-shadow: none; }

        /* --- AUTH MODAL --- */
        .modal-overlay { position: fixed; inset: 0; background: rgba(245,245,247,0.8); backdrop-filter: blur(20px); z-index: 5000; display: none; justify-content: center; align-items: center; animation: fadeIn 0.3s ease; }
        @keyframes fadeIn { from{opacity:0;} to{opacity:1;} }
        
        .modal-card { background: #fff; padding: 40px; border-radius: 32px; width: 100%; max-width: 440px; border: 1px solid var(--border-light); box-shadow: var(--shadow-md); position: relative; margin: 20px; }
        .close-modal { position: absolute; top: 20px; right: 20px; background: none; border: none; font-size: 20px; color: var(--text-muted); cursor: pointer; transition: 0.2s; }
        .close-modal:hover { color: var(--danger); transform: rotate(90deg); }
        
        .modal-header { text-align: center; margin-bottom: 24px; }
        .modal-header h2 { font-size: 26px; font-weight: 800; color: var(--text-dark); }
        
        .auth-tabs { display: flex; background: var(--bg-main); padding: 4px; border-radius: 12px; margin-bottom: 24px; }
        .auth-tab { flex: 1; padding: 10px; text-align: center; border-radius: 8px; font-size: 14px; font-weight: 700; color: var(--text-muted); cursor: pointer; transition: 0.2s; }
        .auth-tab.active { background: #fff; color: var(--text-dark); box-shadow: var(--shadow-sm); }

        .auth-step { display: none; flex-direction: column; animation: slideIn 0.3s ease; }
        .auth-step.active { display: flex; }
        @keyframes slideIn { from{opacity:0; transform:translateX(20px);} to{opacity:1; transform:translateX(0);} }

        .input-group { position: relative; margin-bottom: 16px; }
        .input-group i { position: absolute; left: 16px; top: 50%; transform: translateY(-50%); color: var(--text-muted); font-size: 16px; }
        .input-group input { width: 100%; padding: 16px 16px 16px 48px; border: 1px solid var(--border-light); border-radius: 14px; font-size: 15px; background: #FAFAFA; outline: none; transition: 0.3s; font-family: var(--font-sans); }
        .input-group input:focus { border-color: var(--accent-blue); background: #fff; box-shadow: 0 4px 12px rgba(0,122,255,0.1); }
        
        .btn-text { background: none; border: none; color: var(--text-muted); font-size: 14px; font-weight: 600; cursor: pointer; margin-top: 10px; padding: 10px; width: 100%; transition: 0.2s; }
        .btn-text:hover { color: var(--text-dark); }

        /* --- RESPONSIVE MOBILE ADAPTIVE --- */
        @media (max-width: 850px) {
            .sidebar { position: absolute; left: -300px; height: 100%; box-shadow: var(--shadow-md); }
            .sidebar.open { left: 0; transform: translateX(0); }
            .hamburger, .close-sidebar-btn { display: block; }
            .chat-container { padding: 20px 20px; }
            .input-zone { padding: 0 15px 20px; }
            .msg-row { max-width: 95%; }
            .modal-card { padding: 30px 24px; }
        }
    </style>
</head>
<body>

<div id="toast-container"></div>

<div class="app-shell">
    <!-- Sidebar -->
    <aside class="sidebar" id="sidebar">
        <div class="brand-header">
            <div class="brand-info">
                <h1>Arjun Compound</h1>
                <p>By Abhay Kumar</p>
            </div>
            <button class="close-sidebar-btn" onclick="toggleSidebar()"><i class="fa-solid fa-xmark"></i></button>
        </div>

        <!-- Auth / Profile Section -->
        <div class="auth-section">
            <button id="loginBtn" class="btn-primary" onclick="openAuthModal()"><i class="fa-solid fa-shield-halved"></i> Secure Login</button>
            <div id="userProfile" class="user-profile">
                <div class="user-details">
                    <div class="user-avatar" id="uAvatar">U</div>
                    <div class="user-email" id="uEmail">user@email.com</div>
                </div>
                <button class="btn-logout" onclick="logout()" title="Logout Account"><i class="fa-solid fa-power-off"></i></button>
            </div>
        </div>

        <div class="sidebar-menu">
            <button class="menu-btn" onclick="sendEx('Write a python script for a simple HTTP server.')"><i class="fa-solid fa-code"></i> Code Assistant</button>
            <button class="menu-btn" onclick="sendEx('Create a cinematic image of a futuristic Indian city.')"><i class="fa-solid fa-image"></i> Generate Image</button>
            <button class="menu-btn danger" onclick="clearMemory()"><i class="fa-solid fa-trash-can"></i> Clear History</button>
        </div>
    </aside>

    <!-- Main Workspace -->
    <main class="main-area">
        <header class="top-nav">
            <button class="hamburger" onclick="toggleSidebar()"><i class="fa-solid fa-bars"></i></button>
            <div class="nav-title"><div class="nav-status"></div> Arjun AI Connected</div>
        </header>

        <div class="chat-container" id="chatArea">
            <div class="welcome-screen" id="welcomeScreen">
                <div class="welcome-icon"><i class="fa-solid fa-microchip"></i></div>
                <h2 class="welcome-title">How can I help you today?</h2>
                <p class="welcome-desc">I am Arjun Compound, an advanced AI developed by Abhay Kumar. I can write code, analyze files, understand voice, and generate images.</p>
                
                <div id="guestBadge" class="guest-badge" style="display: none;">
                    <i class="fa-solid fa-circle-exclamation"></i> Guest Mode: <span id="guestCount">0</span>/3 Queries Used. Login to unlock.
                </div>
            </div>
        </div>

        <div class="input-zone">
            <div class="input-wrapper">
                <!-- File Preview UI -->
                <div class="file-preview" id="filePreview">
                    <div class="file-thumb" id="fileThumb"><i class="fa-solid fa-file-lines"></i></div>
                    <div class="file-info">
                        <div class="file-name" id="fileName">document.pdf</div>
                        <div class="file-meta" id="fileMeta">Processing...</div>
                    </div>
                    <button class="remove-file" onclick="removeFile()"><i class="fa-solid fa-xmark"></i></button>
                </div>

                <div class="input-row">
                    <!-- Universal File Attach -->
                    <button class="action-icon-btn" title="Attach File or Image">
                        <i class="fa-solid fa-paperclip"></i>
                        <input type="file" id="fileInput" accept="*/*" onchange="handleFile(this)">
                    </button>
                    
                    <!-- Voice Input (Google Speech API) -->
                    <button class="action-icon-btn" id="voiceBtn" onclick="toggleVoice()" title="Voice Input">
                        <i class="fa-solid fa-microphone"></i>
                    </button>

                    <textarea class="chat-input" id="chatInput" placeholder="Type a message or use voice..." rows="1" oninput="autoGrow(this)" onkeydown="handleKey(event)"></textarea>
                    
                    <button class="send-btn" id="sendBtn" onclick="sendMsg()">
                        <i class="fa-solid fa-paper-plane"></i>
                    </button>
                </div>
            </div>
        </div>
    </main>
</div>

<!-- Authentication Modal (GAS Powered) -->
<div class="modal-overlay" id="authModal">
    <div class="modal-card">
        <button class="close-modal" onclick="closeAuthModal()"><i class="fa-solid fa-xmark"></i></button>
        <div class="modal-header"><h2>Arjun Network</h2></div>
        
        <div class="auth-tabs">
            <div class="auth-tab active" id="tab-login" onclick="switchAuthTab('login')">Login</div>
            <div class="auth-tab" id="tab-register" onclick="switchAuthTab('register')">Create Account</div>
        </div>

        <!-- Login Flow -->
        <div id="flow-login">
            <div class="auth-step active" id="log-step-1">
                <div class="input-group"><i class="fa-solid fa-envelope"></i><input type="email" id="logEmail" placeholder="Registered Email"></div>
                <button class="btn-primary" id="btn-log-otp" onclick="processAuth('login_send_otp')">Send Secure OTP</button>
            </div>
            <div class="auth-step" id="log-step-2">
                <div class="input-group"><i class="fa-solid fa-key"></i><input type="number" id="logOTP" placeholder="Enter 6-Digit OTP"></div>
                <button class="btn-primary" id="btn-log-verify" onclick="processAuth('login_verify')">Verify & Login</button>
                <button class="btn-text" onclick="switchStep('log-step-2', 'log-step-1')">Back</button>
            </div>
        </div>

        <!-- Register Flow -->
        <div id="flow-register" style="display: none;">
            <div class="auth-step active" id="reg-step-1">
                <div class="input-group"><i class="fa-solid fa-user"></i><input type="text" id="regName" placeholder="Full Name"></div>
                <div class="input-group"><i class="fa-solid fa-envelope"></i><input type="email" id="regEmail" placeholder="Email Address"></div>
                <button class="btn-primary" id="btn-reg-otp" onclick="processAuth('register_send_otp')">Generate OTP</button>
            </div>
            <div class="auth-step" id="reg-step-2">
                <div class="input-group"><i class="fa-solid fa-shield-check"></i><input type="number" id="regOTP" placeholder="Enter Verification OTP"></div>
                <button class="btn-primary" id="btn-reg-verify" onclick="processAuth('register_verify')">Create Account</button>
                <button class="btn-text" onclick="switchStep('reg-step-2', 'reg-step-1')">Back</button>
            </div>
        </div>
    </div>
</div>

<script>
// --- CORE CONFIGURATION & STATE ---
const GAS_URL = "https://script.google.com/macros/s/AKfycbzTsXGoVh97JjtFAAG825GF4WUZqf7FDB3Zbxyf0nrLXt_1HjJSSqA829UcdoamRPvg0A/exec";
const STATE = { history: [], pendingFile: null, isProcessing: false };

// CACHE MEMORY (Persistent Login)
let currentUser = localStorage.getItem('arjun_user');
let guestCount = parseInt(localStorage.getItem('arjun_guest') || '0');

// --- INITIALIZATION ---
window.onload = () => {
    updateUIForAuth();
    if (currentUser) { fetchHistoryFromGAS(); } 
    else { 
        document.getElementById('guestBadge').style.display = 'inline-flex';
        document.getElementById('guestCount').innerText = guestCount;
    }
    setupMarkdown();
};

function showToast(msg) {
    const t = document.createElement('div'); t.className = 'toast';
    t.innerHTML = `<i class="fa-solid fa-circle-info"></i> ${msg}`;
    document.getElementById('toast-container').appendChild(t);
    setTimeout(() => t.remove(), 3000);
}

function toggleSidebar() { document.getElementById('sidebar').classList.toggle('open'); }
function autoGrow(el) { el.style.height = 'auto'; el.style.height = Math.min(el.scrollHeight, 200) + 'px'; }
function handleKey(e) { if(e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMsg(); } }
function scrollChat() { const c = document.getElementById('chatArea'); c.scrollTo({ top: c.scrollHeight, behavior: 'smooth' }); }

// --- AUTHENTICATION (Login / Register / Cache) ---
function updateUIForAuth() {
    if (currentUser) {
        document.getElementById('loginBtn').style.display = 'none';
        document.getElementById('userProfile').style.display = 'flex';
        document.getElementById('uEmail').innerText = currentUser;
        document.getElementById('uAvatar').innerText = currentUser.charAt(0).toUpperCase();
        document.getElementById('guestBadge').style.display = 'none';
    } else {
        document.getElementById('loginBtn').style.display = 'flex';
        document.getElementById('userProfile').style.display = 'none';
    }
}

function openAuthModal() { document.getElementById('authModal').style.display = 'flex'; }
function closeAuthModal() { document.getElementById('authModal').style.display = 'none'; }

function switchAuthTab(tab) {
    document.querySelectorAll('.auth-tab').forEach(e => e.classList.remove('active'));
    document.getElementById(`tab-${tab}`).classList.add('active');
    document.getElementById('flow-login').style.display = tab === 'login' ? 'block' : 'none';
    document.getElementById('flow-register').style.display = tab === 'register' ? 'block' : 'none';
}
function switchStep(curr, next) {
    document.getElementById(curr).classList.remove('active');
    document.getElementById(next).classList.add('active');
}

async function processAuth(action) {
    let payload = { action }; let btnId = '';
    
    if (action === 'register_send_otp') {
        payload.name = document.getElementById('regName').value.trim();
        payload.email = document.getElementById('regEmail').value.trim();
        payload.phone = "0000000000"; payload.organization = "Arjun Compound";
        if(!payload.email || !payload.name) return showToast("Name and Email required."); 
        btnId = 'btn-reg-otp';
    } else if (action === 'login_send_otp') {
        payload.email = document.getElementById('logEmail').value.trim();
        if(!payload.email) return showToast("Enter email first."); 
        btnId = 'btn-log-otp';
    } else if (action === 'register_verify' || action === 'login_verify') {
        payload.email = document.getElementById(action === 'register_verify' ? 'regEmail' : 'logEmail').value.trim();
        payload.otp = document.getElementById(action === 'register_verify' ? 'regOTP' : 'logOTP').value.trim();
        if(!payload.otp) return showToast("Enter OTP!"); 
        btnId = action === 'register_verify' ? 'btn-reg-verify' : 'btn-log-verify';
    }

    const btn = document.getElementById(btnId); const ogText = btn.innerHTML;
    btn.disabled = true; btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Processing...';

    try {
        const res = await fetch(GAS_URL, { method: 'POST', body: JSON.stringify(payload) });
        const data = await res.json();
        
        if (data.status === 'success') {
            showToast(data.message);
            if (action === 'register_send_otp') switchStep('reg-step-1', 'reg-step-2');
            else if (action === 'login_send_otp') switchStep('log-step-1', 'log-step-2');
            else if (action === 'register_verify' || action === 'login_verify') {
                currentUser = payload.email; 
                localStorage.setItem('arjun_user', currentUser); // Persistent Cache Update
                closeAuthModal(); updateUIForAuth(); fetchHistoryFromGAS();
            }
        } else showToast(data.message);
    } catch (e) { showToast("Network Error."); }
    btn.disabled = false; btn.innerHTML = ogText;
}

function logout() { localStorage.removeItem('arjun_user'); location.reload(); }
async function clearMemory() {
    if(currentUser) {
        showToast("Clearing Cloud History...");
        await fetch(GAS_URL, { method: 'POST', body: JSON.stringify({ action: "delete_history", email: currentUser }) });
    }
    location.reload();
}

async function fetchHistoryFromGAS() {
    document.getElementById('welcomeScreen').style.display = 'none';
    const c = document.getElementById('chatArea');
    c.innerHTML = '<div style="text-align:center; color:var(--text-muted); margin-top:20px;"><i class="fa-solid fa-spinner fa-spin"></i> Syncing Arjun Network...</div>';
    
    try {
        const res = await fetch(GAS_URL, { method: 'POST', body: JSON.stringify({ action: "get_history", email: currentUser }) });
        const data = await res.json();
        c.innerHTML = '';
        if (data.status === 'success' && data.historyJSON !== "[]") {
            STATE.history = JSON.parse(data.historyJSON);
            STATE.history.forEach(m => appendMsg(m.content, m.role, true));
            setTimeout(scrollChat, 100);
        } else { document.getElementById('welcomeScreen').style.display = 'block'; }
    } catch(e) { c.innerHTML = ''; document.getElementById('welcomeScreen').style.display = 'block'; }
}

function syncHistory() {
    if(currentUser) fetch(GAS_URL, { method: 'POST', body: JSON.stringify({ action: "save_history", email: currentUser, historyJSON: JSON.stringify(STATE.history) }) });
}

// --- VOICE RECOGNITION (Google Speech API) ---
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
let recognition = null;
let isRecording = false;

if (SpeechRecognition) {
    recognition = new SpeechRecognition();
    recognition.continuous = false; recognition.interimResults = true; recognition.lang = 'en-US';
    
    recognition.onstart = () => { isRecording = true; document.getElementById('voiceBtn').classList.add('recording'); };
    recognition.onresult = (event) => {
        let transcript = '';
        for (let i = event.resultIndex; i < event.results.length; ++i) { transcript += event.results[i][0].transcript; }
        document.getElementById('chatInput').value = transcript; autoGrow(document.getElementById('chatInput'));
    };
    recognition.onend = () => { isRecording = false; document.getElementById('voiceBtn').classList.remove('recording'); };
    recognition.onerror = () => { showToast("Voice recognition failed. Try again."); };
}

function toggleVoice() {
    if(!recognition) return showToast("Voice input not supported in this browser.");
    if(isRecording) recognition.stop(); else recognition.start();
}

// --- MULTI-FILE ATTACHMENT HANDLING ---
function handleFile(input) {
    const file = input.files[0]; if(!file) return;
    const reader = new FileReader();
    
    document.getElementById('fileName').innerText = file.name;
    document.getElementById('fileThumb').innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i>';
    document.getElementById('filePreview').classList.add('active');

    // Categorize: Image vs Text vs Binary(PDF/Doc)
    if (file.type.startsWith('image/')) {
        reader.onload = (e) => {
            STATE.pendingFile = { type: 'image', data: e.target.result, name: file.name };
            document.getElementById('fileThumb').innerHTML = `<img src="${e.target.result}" style="width:100%; height:100%; border-radius:8px; object-fit:cover;">`;
            document.getElementById('fileMeta').innerText = 'Image Ready';
        };
        reader.readAsDataURL(file);
    } else if (file.type.match(/(text|json|csv|xml)/) || file.name.match(/\.(txt|md|csv|json)$/i)) {
        reader.onload = (e) => {
            STATE.pendingFile = { type: 'text', data: e.target.result, name: file.name };
            document.getElementById('fileThumb').innerHTML = '<i class="fa-solid fa-file-code" style="color:var(--accent-blue)"></i>';
            document.getElementById('fileMeta').innerText = 'Text Extracted';
        };
        reader.readAsText(file);
    } else {
        // Fallback for PDFs, DOCs (Sends as Base64. Actual parsing depends on AI backend capability)
        reader.onload = (e) => {
            STATE.pendingFile = { type: 'document', data: e.target.result, name: file.name };
            document.getElementById('fileThumb').innerHTML = '<i class="fa-solid fa-file-pdf" style="color:var(--danger)"></i>';
            document.getElementById('fileMeta').innerText = 'Document Ready';
        };
        reader.readAsDataURL(file);
    }
}
function removeFile() { STATE.pendingFile = null; document.getElementById('filePreview').classList.remove('active'); document.getElementById('fileInput').value = ''; }

// --- CHAT & MARKDOWN SYSTEM ---
function setupMarkdown() {
    const renderer = new marked.Renderer();
    renderer.code = function(code, lang) {
        const valid = (lang && hljs.getLanguage(lang)) ? lang : 'plaintext';
        const highlighted = hljs.highlight(code, { language: valid }).value;
        const safeCode = encodeURIComponent(code);
        return `<div style="position:relative;">
            <button class="copy-btn" onclick="navigator.clipboard.writeText(decodeURIComponent('${safeCode}')).then(()=>{this.innerText='Copied!';setTimeout(()=>this.innerText='Copy Code',2000)})">Copy Code</button>
            <pre><code class="hljs ${valid}">${highlighted}</code></pre>
        </div>`;
    };
    marked.use({ renderer, breaks: true });
}

async function sendMsg() {
    if (STATE.isProcessing) return;
    const inp = document.getElementById('chatInput');
    let msg = inp.value.trim(); 
    
    if (!msg && !STATE.pendingFile) return;

    if (!currentUser) {
        if (guestCount >= 3) { openAuthModal(); return showToast("Guest limit reached. Please Login."); }
        guestCount++; localStorage.setItem('arjun_guest', guestCount.toString());
        document.getElementById('guestCount').innerText = guestCount;
    }

    inp.value = ''; inp.style.height = 'auto';
    document.getElementById('welcomeScreen').style.display = 'none';
    STATE.isProcessing = true; document.getElementById('sendBtn').disabled = true;

    // Handle Attached File Content
    let displayMsg = msg;
    let backendPayloadMsg = msg;
    let attachmentHTML = '';

    if (STATE.pendingFile) {
        if (STATE.pendingFile.type === 'text') {
            backendPayloadMsg = `[User attached file: ${STATE.pendingFile.name}]\nFile Content:\n${STATE.pendingFile.data}\n\nUser Message: ${msg}`;
            attachmentHTML = `<div class="chat-attachment"><i class="fa-solid fa-file-lines"></i> ${STATE.pendingFile.name} (Text Data)</div>`;
        } else if (STATE.pendingFile.type === 'image') {
            // If backend handles image base64, we send it in attachments array (like previous logic).
            attachmentHTML = `<div class="chat-attachment"><i class="fa-solid fa-image"></i> ${STATE.pendingFile.name}</div><img src="${STATE.pendingFile.data}" style="max-width:200px; border-radius:10px; margin-top:10px;">`;
        } else {
            backendPayloadMsg = `[User attached document: ${STATE.pendingFile.name}]\nUser Message: ${msg}`;
            attachmentHTML = `<div class="chat-attachment"><i class="fa-solid fa-file"></i> ${STATE.pendingFile.name}</div>`;
        }
        removeFile();
    }

    const finalUserHTML = attachmentHTML + (msg ? `<p>${msg.replace(/</g,'&lt;')}</p>` : '');
    appendMsg(finalUserHTML, 'user');
    STATE.history.push({ role: 'user', content: backendPayloadMsg }); // Save text to history

    const botNode = appendMsg('<i class="fa-solid fa-circle-notch fa-spin"></i> Processing...', 'bot');
    scrollChat();

    const sysPrompt = "You are Arjun Compound, an advanced AI developed by Abhay Kumar. Always respond in English unless requested otherwise. To generate images, reply with ![Arjun AI Image](https://image.pollinations.ai/prompt/{URL_ENCODED_PROMPT}?width=1024&height=1024&nologo=true&model=flux)";

    try {
        const res = await fetch('/api/chat', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ message: backendPayloadMsg, system_prompt: sysPrompt, history: STATE.history.slice(0, -1) })
        });

        const reader = res.body.getReader();
        const decoder = new TextDecoder();
        let fullText = "";

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            const lines = decoder.decode(value, {stream: true}).split('\n');
            
            for (let line of lines) {
                if (line.startsWith('data: ') && !line.includes('[DONE]')) {
                    try {
                        const dataObj = JSON.parse(line.substring(6));
                        if (dataObj.choices && dataObj.choices[0].delta.content) {
                            fullText += dataObj.choices[0].delta.content;
                            // Regex to clean up think tags if present
                            let cleanText = fullText.replace(/<think>[\s\S]*?(<\/think>|$)/gi, '');
                            botNode.querySelector('.msg-bubble').innerHTML = marked.parse(cleanText) + '<span style="display:inline-block;width:6px;height:12px;background:var(--accent-blue);animation:blink 1s infinite;"></span>';
                            scrollChat();
                        }
                    } catch (e) { }
                }
            }
        }
        
        let finalText = fullText.replace(/<think>[\s\S]*?(<\/think>|$)/gi, '');
        botNode.querySelector('.msg-bubble').innerHTML = marked.parse(finalText);
        STATE.history.push({ role: 'bot', content: fullText });
        syncHistory();

    } catch(err) { botNode.querySelector('.msg-bubble').innerHTML = "<b>Error:</b> Connection failed."; }

    STATE.isProcessing = false; document.getElementById('sendBtn').disabled = false; scrollChat();
}

function sendEx(t) { document.getElementById('chatInput').value = t; sendMsg(); }

function appendMsg(htmlContent, role, isMD = false) {
    const d = document.createElement('div'); d.className = `msg-row ${role}`;
    let displayHtml = isMD ? marked.parse(htmlContent.replace(/<think>[\s\S]*?(<\/think>|$)/gi, '')) : htmlContent;
    d.innerHTML = `<div class="avatar">${role === 'user' ? 'U' : '<i class="fa-solid fa-microchip"></i>'}</div><div class="msg-bubble">${displayHtml}</div>`;
    document.getElementById('chatArea').appendChild(d);
    return d;
}
</script>
</body>
</html>