File size: 50,202 Bytes
84e1dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a32d2df
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="user-scalable=yes">
    <title>AI Coder Studio Pro</title>

    <link href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>

    <style>

        :root {

            --bg-base: #0a0e1a;

            --bg-panel: #131b2e;

            --bg-panel-2: #1a2338;

            --bg-hover: #263049;

            --border: #253049;

            --border-soft: #1c2540;

            --accent: #4f7cff;

            --accent-2: #8b5cf6;

            --accent-glow: rgba(79, 124, 255, 0.35);

            --text-main: #f4f6fb;

            --text-muted: #8b96b3;

            --success: #22c55e;

            --warn: #f59e0b;

            --danger: #ef4444;

            --font-ui: 'Inter', sans-serif;

            --font-code: 'Fira Code', monospace;

        }



        * { box-sizing: border-box; }

        body {

            margin: 0; padding: 0; background: var(--bg-base); color: var(--text-main);

            font-family: var(--font-ui); display: flex; flex-direction: column;

            height: 100vh; overflow: hidden;

        }

        ::-webkit-scrollbar { width: 8px; height: 8px; }

        ::-webkit-scrollbar-track { background: transparent; }

        ::-webkit-scrollbar-thumb { background: #2a3556; border-radius: 8px; }

        ::-webkit-scrollbar-thumb:hover { background: #3a4770; }



        @keyframes fadeIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } }

        @keyframes popIn { 0% { transform: scale(0.4); opacity: 0; } 70% { transform: scale(1.15); } 100% { transform: scale(1); opacity: 1; } }

        @keyframes softPulse { 0%, 100% { box-shadow: 0 0 0 0 var(--accent-glow); } 50% { box-shadow: 0 0 0 10px rgba(79,124,255,0); } }

        @keyframes spin { to { transform: rotate(360deg); } }

        @keyframes shimmerBar { 0% { background-position: -300px 0; } 100% { background-position: 300px 0; } }

        @keyframes blinkCursor { 0%, 45% { opacity: 1; } 50%, 100% { opacity: 0; } }

        @keyframes floatOrb { 0%, 100% { transform: translate(0,0) scale(1); } 50% { transform: translate(20px,-24px) scale(1.05); } }

        @keyframes shake { 10%,90%{transform:translateX(-1px)} 20%,80%{transform:translateX(2px)} 30%,50%,70%{transform:translateX(-4px)} 40%,60%{transform:translateX(4px)} }

        @keyframes dotBounce { 0%,80%,100%{ transform: scale(0.6); opacity:.4 } 40%{ transform: scale(1); opacity:1 } }

        @keyframes gradientShift { 0% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } 100% { background-position: 0% 50%; } }

        @keyframes scanline { 0% { transform: translateY(-100%); } 100% { transform: translateY(2200%); } }



        /* --- BUTTONS & INPUTS --- */

        .btn {

            background: var(--bg-hover); color: var(--text-main); border: 1px solid var(--border);

            padding: 10px 18px; border-radius: 9px; font-weight: 500; cursor: pointer;

            transition: 0.18s ease; display: flex; align-items: center; gap: 8px; font-size: 14px;

            font-family: var(--font-ui);

        }

        .btn:hover:not(:disabled) { background: #324066; border-color: #3a4770; transform: translateY(-1px); }

        .btn:active:not(:disabled) { transform: translateY(0); }

        .btn:disabled { opacity: 0.55; cursor: not-allowed; }

        .btn.primary {

            background: linear-gradient(135deg, var(--accent), var(--accent-2));

            color: white; border: none; box-shadow: 0 4px 16px rgba(79,124,255,0.28);

        }

        .btn.primary:hover:not(:disabled) { box-shadow: 0 6px 22px rgba(79,124,255,0.42); transform: translateY(-1px); }

        .input-box {

            background: var(--bg-base); border: 1px solid var(--border); color: var(--text-main);

            padding: 14px 20px; border-radius: 10px; font-family: var(--font-ui); font-size: 15px;

            outline: none; transition: 0.2s; width: 100%;

        }

        .input-box:focus { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(79, 124, 255, 0.18); }



        /* --- Loading dots (used in buttons while a stage is running) --- */

        .dot-loader { display: inline-flex; gap: 3px; align-items: center; }

        .dot-loader span {

            width: 5px; height: 5px; border-radius: 50%; background: currentColor;

            animation: dotBounce 1.1s infinite ease-in-out;

        }

        .dot-loader span:nth-child(2) { animation-delay: 0.15s; }

        .dot-loader span:nth-child(3) { animation-delay: 0.3s; }



        .spinner-ring {

            width: 14px; height: 14px; border-radius: 50%;

            border: 2px solid rgba(255,255,255,0.25); border-top-color: currentColor;

            animation: spin 0.7s linear infinite; flex-shrink: 0;

        }



        /* --- DASHBOARD VIEW --- */

        #dashboardView {

            display: flex; flex-direction: column; height: 100%; padding: 40px 40px 60px;

            max-width: 1040px; margin: 0 auto; width: 100%; overflow-y: auto; position: relative;

        }

        .bg-orb {

            position: fixed; border-radius: 50%; filter: blur(70px); opacity: 0.28; pointer-events: none; z-index: 0;

            animation: floatOrb 14s ease-in-out infinite;

        }

        .bg-orb.o1 { width: 380px; height: 380px; background: var(--accent); top: -120px; left: -100px; }

        .bg-orb.o2 { width: 320px; height: 320px; background: var(--accent-2); bottom: -100px; right: -80px; animation-delay: -6s; }



        .dash-header { text-align: center; margin-bottom: 40px; position: relative; z-index: 1; animation: fadeIn 0.5s ease; }

        .dash-header h1 {

            font-size: 34px; margin: 0 0 10px 0; font-weight: 800; letter-spacing: -0.5px;

            background: linear-gradient(100deg, #fff 20%, var(--accent) 55%, var(--accent-2) 90%);

            background-size: 200% auto; -webkit-background-clip: text; background-clip: text; color: transparent;

            animation: gradientShift 6s ease infinite;

        }

        .dash-header p { color: var(--text-muted); margin: 0; font-size: 15px; }

        .create-section { display: flex; gap: 15px; margin-bottom: 50px; position: relative; z-index: 1; animation: fadeIn 0.5s ease 0.05s backwards; }

        .projects-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; position: relative; z-index: 1; }

        .project-card {

            background: var(--bg-panel); border: 1px solid var(--border); padding: 20px; border-radius: 14px;

            cursor: pointer; transition: 0.22s ease; display: flex; flex-direction: column; gap: 10px;

            position: relative; overflow: hidden; animation: fadeIn 0.4s ease backwards;

        }

        .project-card::before {

            content: ""; position: absolute; inset: 0 0 auto 0; height: 3px;

            background: linear-gradient(90deg, var(--accent), var(--accent-2));

            opacity: 0; transition: 0.2s;

        }

        .project-card:hover { transform: translateY(-4px); border-color: #33437a; box-shadow: 0 14px 30px rgba(0,0,0,0.35), 0 0 0 1px rgba(79,124,255,0.15); }

        .project-card:hover::before { opacity: 1; }

        .project-title { font-weight: 700; font-size: 16px; }

        .project-meta { font-size: 12px; color: var(--text-muted); }

        .project-actions { display: flex; justify-content: space-between; align-items: center; margin-top: auto; padding-top: 15px; border-top: 1px solid var(--border-soft); }



        /* --- WORKSPACE VIEW --- */

        #workspaceView { display: none; flex-direction: column; height: 100%; }

        .navbar {

            display: flex; justify-content: space-between; align-items: center; padding: 12px 24px;

            background: var(--bg-panel); border-bottom: 1px solid var(--border); z-index: 5;

        }

        .navbar-title { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 16px; }

        .verdict-pill {

            font-size: 11px; font-weight: 700; padding: 3px 10px; border-radius: 20px; letter-spacing: 0.3px;

            display: none; align-items: center; gap: 5px; animation: popIn 0.35s ease;

        }

        .verdict-pill.pass { display: inline-flex; background: rgba(34,197,94,0.15); color: var(--success); border: 1px solid rgba(34,197,94,0.35); }

        .verdict-pill.issues { display: inline-flex; background: rgba(245,158,11,0.15); color: var(--warn); border: 1px solid rgba(245,158,11,0.35); }

        .workspace-core { display: flex; flex: 1; overflow: hidden; }



        /* --- SIDEBAR (EXPLORER) --- */

        .sidebar { width: 280px; background: var(--bg-panel); border-right: 1px solid var(--border); display: flex; flex-direction: column; }

        .sidebar-header { padding: 15px; font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase; letter-spacing: 1px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; }

        .nav-path { padding: 10px 15px; background: var(--bg-base); font-size: 12px; color: var(--text-muted); border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 10px; word-break: break-all; }

        .back-btn { cursor: pointer; padding: 4px 8px; background: var(--bg-hover); border-radius: 4px; color: var(--text-main); font-weight: bold; }

        .file-list { flex: 1; overflow-y: auto; padding: 8px 0; }

        .file-item { padding: 10px 20px; display: flex; align-items: center; gap: 12px; cursor: pointer; font-size: 13px; color: var(--text-main); border-left: 3px solid transparent; transition: 0.15s; animation: fadeIn 0.25s ease backwards; }

        .file-item:hover { background: var(--bg-hover); }

        .file-item.active { background: rgba(79, 124, 255, 0.12); border-left-color: var(--accent); color: #a9c1ff; font-weight: 600; }

        .file-item.just-updated { animation: popIn 0.4s ease; }

        .file-icon { font-size: 16px; }

        .file-badge-new { font-size: 9px; background: var(--success); color: #06240f; padding: 1px 6px; border-radius: 10px; font-weight: 800; margin-left: auto; }



        /* --- EDITOR AREA --- */

        .main-editor { flex: 1; display: flex; flex-direction: column; position: relative; background: var(--bg-base); }

        .code-header { display: flex; justify-content: space-between; align-items: center; padding: 12px 24px; background: var(--bg-panel); border-bottom: 1px solid var(--border); font-size: 14px; font-family: var(--font-code); color: var(--text-muted); position: relative; overflow: hidden; }

        .code-header .stream-bar {

            position: absolute; left: 0; right: 0; bottom: -1px; height: 2px;

            background: linear-gradient(90deg, transparent, var(--accent), var(--accent-2), transparent);

            background-size: 300px 100%; opacity: 0; transition: opacity 0.2s;

        }

        .code-header.streaming .stream-bar { opacity: 1; animation: shimmerBar 1.1s linear infinite; }

        .code-view-wrapper { flex: 1; overflow: auto; display: flex; position: relative; }

        .code-view-wrapper.streaming::after {

            content: ""; position: absolute; left: 0; right: 0; top: 0; height: 90px; pointer-events: none;

            background: linear-gradient(180deg, rgba(79,124,255,0.10), transparent);

            animation: scanline 2.6s linear infinite;

        }

        #codeEditor { flex: 1; padding: 24px; margin: 0; color: #e2e8f0; font-family: var(--font-code); font-size: 14px; white-space: pre-wrap; outline: none; tab-size: 4; line-height: 1.65; word-wrap: break-word; }

        .stream-placeholder { color: var(--text-muted); }

        .type-cursor { display: inline-block; width: 7px; height: 15px; background: var(--accent); margin-left: 1px; vertical-align: -2px; animation: blinkCursor 0.9s step-end infinite; }



        /* --- PIPELINE TRACKER --- */

        .pipeline-tracker {

            display: flex; align-items: flex-start; gap: 0; padding: 16px 24px 12px;

            background: var(--bg-panel-2); border-bottom: 1px solid var(--border);

            animation: fadeIn 0.3s ease;

        }

        .pipe-node { display: flex; flex-direction: column; align-items: center; gap: 6px; width: 110px; text-align: center; }

        .pipe-icon-wrap {

            width: 40px; height: 40px; border-radius: 50%; background: var(--bg-hover);

            display: flex; align-items: center; justify-content: center; font-size: 18px;

            border: 2px solid var(--border); position: relative; transition: 0.25s ease;

        }

        .pipe-node.active .pipe-icon-wrap { border-color: var(--accent); animation: softPulse 1.6s ease-in-out infinite; background: rgba(79,124,255,0.12); }

        .pipe-node.done .pipe-icon-wrap { border-color: var(--success); background: rgba(34,197,94,0.14); animation: popIn 0.4s ease; }

        .pipe-node.warning .pipe-icon-wrap { border-color: var(--warn); background: rgba(245,158,11,0.14); }

        .pipe-node.error .pipe-icon-wrap { border-color: var(--danger); background: rgba(239,68,68,0.14); animation: shake 0.4s ease; }

        .pipe-label { font-size: 12px; font-weight: 700; color: var(--text-main); }

        .pipe-sub { font-size: 10.5px; color: var(--text-muted); min-height: 14px; }

        .pipe-node.active .pipe-sub { color: #a9c1ff; }

        .pipe-node.done .pipe-sub { color: var(--success); }

        .pipe-node.warning .pipe-sub { color: var(--warn); }

        .pipe-node.error .pipe-sub { color: var(--danger); }

        .pipe-connector { flex: 1; height: 2px; background: var(--border); margin: 19px 4px 0; border-radius: 2px; position: relative; overflow: hidden; }

        .pipe-connector .fill { position: absolute; inset: 0; width: 0%; background: linear-gradient(90deg, var(--accent), var(--accent-2)); transition: width 0.5s ease; }



        /* --- TERMINAL / CHAT AREA --- */

        .chat-panel { height: 300px; background: #0b0f19; border-top: 1px solid var(--border); display: flex; flex-direction: column; transition: height 0.3s ease; }

        .chat-panel.collapsed { height: 45px; }

        .chat-panel.collapsed .pipeline-tracker { display: none; }

        .chat-header { padding: 12px 24px; background: var(--bg-panel); font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase; letter-spacing: 1px; display: flex; justify-content: space-between; cursor: pointer; border-bottom: 1px solid var(--border); }

        .chat-content { flex: 1; overflow-y: auto; padding: 16px 24px; font-family: var(--font-code); font-size: 13px; line-height: 1.65; color: #cbd5e1; }

        .log-msg { margin-bottom: 9px; animation: fadeIn 0.25s ease; }

        .log-user { color: var(--accent); font-weight: bold; }

        .log-ai { color: #a5b4fc; }

        .log-sys { color: var(--success); }

        .log-warn { color: var(--warn); }

        .log-error { color: var(--danger); }

        .log-plan { color: #c4b5fd; }

        .log-build { color: #93c5fd; }

        .log-test { color: #6ee7b7; }

        .log-live-body { white-space: pre-wrap; margin-top: 4px; padding: 10px 12px; background: rgba(255,255,255,0.03); border-left: 2px solid var(--border); border-radius: 4px; font-size: 12px; color: #b6c2e0; max-height: 160px; overflow-y: auto; }

        .verdict-inline { display: inline-flex; align-items: center; gap: 5px; font-weight: 700; padding: 2px 9px; border-radius: 12px; font-size: 11px; margin-left: 4px; }

        .verdict-inline.pass { background: rgba(34,197,94,0.15); color: var(--success); }

        .verdict-inline.issues { background: rgba(245,158,11,0.15); color: var(--warn); }

        details.report-toggle { margin-top: 6px; }

        details.report-toggle summary { cursor: pointer; color: var(--text-muted); font-size: 11px; user-select: none; }

        details.report-toggle summary:hover { color: var(--text-main); }



        .prompt-bar { padding: 15px 24px; background: var(--bg-panel); border-top: 1px solid var(--border); display: flex; gap: 12px; }



        /* --- PREVIEW MODAL --- */

        #previewModal { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.82); z-index: 9999; flex-direction: column; padding: 40px; backdrop-filter: blur(2px); }

        .preview-box { flex: 1; display: flex; flex-direction: column; background: white; border-radius: 12px; overflow: hidden; animation: popIn 0.25s ease; box-shadow: 0 30px 80px rgba(0,0,0,0.5); }

        .preview-header { padding: 16px 24px; background: var(--bg-panel); border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; color: white; font-weight: 600; }

        #previewFrame { flex: 1; width: 100%; border: none; background: #fff; }

    </style>
</head>
<body>

    <div class="bg-orb o1"></div>
    <div class="bg-orb o2"></div>

    <!-- DASHBOARD VIEW -->
    <div id="dashboardView">
        <div class="dash-header">
            <h1>AI Coder Studio Pro</h1>
            <p>A 3-stage AI pipeline — Architect plans it, Builder codes it, QA tests it.</p>
        </div>
        <div class="create-section">
            <input type="text" id="newProjectPrompt" class="input-box" placeholder="Describe a new project (e.g. A fully functional Kanban board in HTML/CSS/JS)...">
            <button class="btn primary" onclick="createNewProject()" id="createProjectBtn" style="white-space: nowrap;">
                <span id="createProjectBtnLabel">🚀 Build New Project</span>
            </button>
        </div>
        <h3 style="margin-bottom: 20px; border-bottom: 1px solid var(--border); padding-bottom: 10px; position: relative; z-index: 1;">Recent Projects</h3>
        <div class="projects-grid" id="projectsGrid">
            <!-- Projects loaded here -->
        </div>
    </div>

    <!-- WORKSPACE VIEW -->
    <div id="workspaceView">
        <div class="navbar">
            <div class="navbar-title">
                <span id="workspaceTitle">Project Workspace</span>
                <span class="verdict-pill" id="navVerdictPill"></span>
            </div>
            <div style="display: flex; gap: 10px;">
                <button class="btn" onclick="runHtmlPreview()" id="previewBtnTop" style="display:none; color: var(--success); border-color: var(--success);">▶ Live Preview</button>
                <button class="btn" onclick="downloadAllZip()">📦 Download ZIP</button>
                <button class="btn" onclick="exitToDashboard()">🏠 Dashboard</button>
            </div>
        </div>

        <div class="workspace-core">
            <div class="sidebar" id="sidebar">
                <div class="sidebar-header">
                    <span>Explorer</span>
                    <span id="fileBadge" style="background:var(--border); padding:2px 8px; border-radius:12px; font-size:11px;">0 Files</span>
                </div>
                <div class="nav-path" id="navPath" style="display: none;">
                    <span class="back-btn" onclick="navigateUp()">🔙 Back</span>
                    <span id="currentDirPath" style="margin-left: 8px;">/</span>
                </div>
                <div class="file-list" id="fileList"></div>
            </div>

            <div class="main-editor">
                <div class="code-header" id="codeHeader">
                    <span id="currentFileName">No file selected</span>
                    <div style="display: flex; gap: 8px;" id="codeActions">
                        <button class="btn" onclick="copyCurrentCode()">Copy</button>
                    </div>
                    <div class="stream-bar"></div>
                </div>

                <div class="code-view-wrapper" id="codeViewWrapper">
                    <div id="codeEditor"><span class="stream-placeholder">// Select a file from the explorer to view code...</span></div>
                </div>

                <div class="chat-panel" id="terminalPanel">
                    <div class="pipeline-tracker" id="pipelineTracker" style="display:none;">
                        <div class="pipe-node" data-stage="plan" id="pipeNode-plan">
                            <div class="pipe-icon-wrap"><span>🧠</span></div>
                            <div class="pipe-label">Architect</div>
                            <div class="pipe-sub" id="pipeSub-plan">Waiting…</div>
                        </div>
                        <div class="pipe-connector"><div class="fill" id="pipeFill-1"></div></div>
                        <div class="pipe-node" data-stage="build" id="pipeNode-build">
                            <div class="pipe-icon-wrap"><span>⚡</span></div>
                            <div class="pipe-label">Builder</div>
                            <div class="pipe-sub" id="pipeSub-build">Waiting…</div>
                        </div>
                        <div class="pipe-connector"><div class="fill" id="pipeFill-2"></div></div>
                        <div class="pipe-node" data-stage="test" id="pipeNode-test">
                            <div class="pipe-icon-wrap"><span>🧪</span></div>
                            <div class="pipe-label">QA Test</div>
                            <div class="pipe-sub" id="pipeSub-test">Waiting…</div>
                        </div>
                    </div>

                    <div class="chat-header" onclick="toggleTerminal()">
                        <span>Conversation & Logs</span>
                        <span id="termToggleBtn">▼ Hide</span>
                    </div>
                    <div class="chat-content" id="terminalLog"></div>
                    <div class="prompt-bar">
                        <input type="text" id="updatePrompt" class="input-box" placeholder="Ask the AI to update the code, fix a bug, or add a new feature...">
                        <button class="btn primary" id="updateBtn" onclick="sendUpdatePrompt()">
                            <span id="updateBtnLabel">Send Update</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- PREVIEW MODAL -->
    <div id="previewModal">
        <div class="preview-box">
            <div class="preview-header">
                <span>Local Preview</span>
                <button class="btn" style="color: #fca5a5; border-color: #fca5a5;" onclick="document.getElementById('previewModal').style.display='none'">Close</button>
            </div>
            <iframe id="previewFrame"></iframe>
        </div>
    </div>

    <script>

        // --- DATA STRUCTURES & MEMORY ---

        let projects = [];

        let currentProject = null;

        let currentDirectory = ""; // For folder drill-down

        let activeFilePath = null;

        let isStreaming = false;



        // Per-run buffers for the 3-stage pipeline

        let planBuffer = "";

        let buildBuffer = "";

        let testBuffer = "";

        let lastVerdict = null;

        let filesTouchedThisRun = new Set();



        // --- INITIALIZATION ---

        window.onload = () => {

            loadProjectsFromStorage();

            renderDashboard();

        };



        function loadProjectsFromStorage() {

            const saved = localStorage.getItem("ai_coder_projects");

            if (saved) {

                try { projects = JSON.parse(saved); } catch (e) { projects = []; }

            }

        }



        function saveProjectsToStorage() {

            localStorage.setItem("ai_coder_projects", JSON.stringify(projects));

        }



        // --- DASHBOARD LOGIC ---

        function renderDashboard() {

            document.getElementById("dashboardView").style.display = "flex";

            document.getElementById("workspaceView").style.display = "none";



            const grid = document.getElementById("projectsGrid");

            if (projects.length === 0) {

                grid.innerHTML = `<div style="grid-column: 1/-1; text-align: center; color: var(--text-muted); padding: 40px;">No projects yet. Build one above!</div>`;

                return;

            }



            grid.innerHTML = projects.map((p, idx) => `

                <div class="project-card" style="animation-delay:${idx * 0.04}s" onclick="openProject('${p.id}')">

                    <div class="project-title">${p.name}</div>

                    <div class="project-meta">Last Updated: ${new Date(p.lastUpdated || Date.now()).toLocaleString()}</div>

                    <div class="project-meta">📁 ${p.files.length} Files</div>

                    <div class="project-actions">

                        <span style="color: var(--accent); font-size: 13px; font-weight: bold;">Open Workspace ➔</span>

                        <button class="btn" style="padding: 4px 8px; font-size: 12px; color: var(--danger); border-color: transparent;" onclick="deleteProject('${p.id}', event)">Delete</button>

                    </div>

                </div>

            `).join("");

        }



        function exitToDashboard() {

            currentProject = null;

            renderDashboard();

        }



        function deleteProject(id, event) {

            event.stopPropagation();

            if(!confirm("Delete this project permanently?")) return;

            projects = projects.filter(p => p.id !== id);

            saveProjectsToStorage();

            renderDashboard();

        }



        // --- WORKSPACE & FILE EXPLORER LOGIC ---

        function openProject(id) {

            currentProject = projects.find(p => p.id === id);

            if (!currentProject) return;

            if (!currentProject.history) currentProject.history = [];



            document.getElementById("dashboardView").style.display = "none";

            document.getElementById("workspaceView").style.display = "flex";

            document.getElementById("workspaceTitle").innerText = currentProject.name;



            currentDirectory = "";

            activeFilePath = null;

            document.getElementById("codeEditor").innerHTML = '<span class="stream-placeholder">// Select a file from the explorer to view code...</span>';

            document.getElementById("currentFileName").innerText = "No file selected";

            document.getElementById("previewBtnTop").style.display = "none";

            document.getElementById("navVerdictPill").className = "verdict-pill";

            hidePipelineTracker();



            renderTerminalHistory();

            renderFileTree();

        }



        async function createNewProject() {

            const promptEl = document.getElementById("newProjectPrompt");

            const prompt = promptEl.value.trim();

            if (!prompt) return alert("Please enter a project description.");



            const createBtn = document.getElementById("createProjectBtn");

            const createLabel = document.getElementById("createProjectBtnLabel");

            createBtn.disabled = true;

            createLabel.innerHTML = `<span class="spinner-ring"></span> Spinning up workspace...`;



            const rawName = prompt.split(" ").slice(0, 4).join("_").replace(/[^a-zA-Z0-9_]/g, '');

            const newProj = {

                id: "proj_" + Date.now(),

                name: rawName || "New_Project",

                files: [],

                history: []

            };



            projects.unshift(newProj);

            saveProjectsToStorage();

            promptEl.value = "";



            openProject(newProj.id);



            createBtn.disabled = false;

            createLabel.innerHTML = `🚀 Build New Project`;



            // Automatically start the build

            document.getElementById("updatePrompt").value = prompt;

            await sendUpdatePrompt();

        }



        function navigateUp() {

            if (currentDirectory === "") return;

            const parts = currentDirectory.split("/").filter(Boolean);

            parts.pop();

            currentDirectory = parts.length > 0 ? parts.join("/") + "/" : "";

            renderFileTree();

        }



        function enterDirectory(dirName) {

            currentDirectory += dirName + "/";

            renderFileTree();

        }



        function renderFileTree() {

            const list = document.getElementById("fileList");

            const navPath = document.getElementById("navPath");

            const pathText = document.getElementById("currentDirPath");



            document.getElementById("fileBadge").innerText = `${currentProject.files.length} Files`;



            if (currentDirectory === "") {

                navPath.style.display = "none";

            } else {

                navPath.style.display = "flex";

                pathText.innerText = "/" + currentDirectory;

            }



            const itemsMap = new Map();



            currentProject.files.forEach(f => {

                if (f.path.startsWith(currentDirectory)) {

                    const relativePath = f.path.substring(currentDirectory.length);

                    const parts = relativePath.split("/");



                    if (parts.length > 1) {

                        itemsMap.set(parts[0], { type: "folder", name: parts[0] });

                    } else {

                        itemsMap.set(parts[0], { type: "file", name: parts[0], fullPath: f.path });

                    }

                }

            });



            const sortedItems = Array.from(itemsMap.values()).sort((a, b) => {

                if (a.type === b.type) return a.name.localeCompare(b.name);

                return a.type === "folder" ? -1 : 1;

            });



            if (sortedItems.length === 0) {

                list.innerHTML = `<div style="padding: 20px; text-align: center; color: var(--text-muted); font-size: 13px;">No files here.</div>`;

                return;

            }



            list.innerHTML = sortedItems.map((item, idx) => {

                const delay = `style="animation-delay:${idx * 0.02}s"`;

                if (item.type === "folder") {

                    return `

                        <div class="file-item" ${delay} onclick="enterDirectory('${item.name}')">

                            <span class="file-icon">📁</span>

                            <span style="font-weight: 500;">${item.name}</span>

                        </div>`;

                } else {

                    const isActive = activeFilePath === item.fullPath ? "active" : "";

                    const justUpdated = filesTouchedThisRun.has(item.fullPath) ? "just-updated" : "";

                    const icon = item.name.endsWith(".html") ? "📄" : (item.name.endsWith(".js") ? "⚡" : (item.name.endsWith(".css") ? "🎨" : "📄"));

                    const badge = filesTouchedThisRun.has(item.fullPath) ? '<span class="file-badge-new">NEW</span>' : '';

                    return `

                        <div class="file-item ${isActive} ${justUpdated}" ${delay} onclick="openFileByPath('${item.fullPath}')">

                            <span class="file-icon">${icon}</span>

                            <span style="white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">${item.name}</span>

                            ${badge}

                        </div>`;

                }

            }).join("");

        }



        function openFileByPath(path) {

            if (isStreaming) return;

            activeFilePath = path;

            renderFileTree();



            const file = currentProject.files.find(f => f.path === path);

            if (!file) return;



            document.getElementById("currentFileName").innerText = file.path;

            const safeCode = escapeHtml(file.content);

            document.getElementById("codeEditor").innerHTML = safeCode;



            document.getElementById("previewBtnTop").style.display = file.path.endsWith('.html') ? "flex" : "none";

        }



        function escapeHtml(str) {

            return String(str).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");

        }



        // --- TERMINAL & LOGGING ---

        function appendTerminal(msg, type = "sys") {

            if (!currentProject) return;

            const term = document.getElementById("terminalLog");

            const time = new Date().toLocaleTimeString('en-US', { hour12: false });



            const entry = `<div class="log-msg log-${type}">[${time}] ${msg}</div>`;

            term.insertAdjacentHTML('beforeend', entry);

            term.scrollTop = term.scrollHeight;



            if (type === "user" || type === "ai") {

                currentProject.history.push({ role: type, content: msg, time });

                saveProjectsToStorage();

            }

        }



        // Creates a log line that can be live-updated as chunks stream in (for PLAN / TEST stages)

        function appendLiveLog(id, label, type) {

            const term = document.getElementById("terminalLog");

            const time = new Date().toLocaleTimeString('en-US', { hour12: false });

            const html = `<div class="log-msg log-${type}" id="${id}-wrap">[${time}] ${label}<div class="log-live-body" id="${id}-body"></div></div>`;

            term.insertAdjacentHTML('beforeend', html);

            term.scrollTop = term.scrollHeight;

        }



        function updateLiveLog(id, text) {

            const body = document.getElementById(id + "-body");

            if (!body) return;

            body.textContent = text;

            const term = document.getElementById("terminalLog");

            term.scrollTop = term.scrollHeight;

        }



        function renderTerminalHistory() {

            const term = document.getElementById("terminalLog");

            term.innerHTML = `<div class="log-sys">Workspace loaded. System ready.</div>`;

            if (!currentProject) return;



            currentProject.history.forEach(h => {

                term.insertAdjacentHTML('beforeend', `<div class="log-msg log-${h.role}">[${h.time}] ${h.content}</div>`);

            });

            term.scrollTop = term.scrollHeight;

        }



        function toggleTerminal() {

            const pnl = document.getElementById('terminalPanel');

            pnl.classList.toggle('collapsed');

            document.getElementById('termToggleBtn').innerText = pnl.classList.contains('collapsed') ? '▲ Show' : '▼ Hide';

        }



        // --- PIPELINE TRACKER UI ---

        const STAGE_ORDER = ['plan', 'build', 'test'];



        function showPipelineTracker() {

            document.getElementById('pipelineTracker').style.display = 'flex';

        }

        function hidePipelineTracker() {

            document.getElementById('pipelineTracker').style.display = 'none';

        }



        function resetPipelineTracker() {

            STAGE_ORDER.forEach(stage => {

                const node = document.getElementById('pipeNode-' + stage);

                node.className = 'pipe-node';

                document.getElementById('pipeSub-' + stage).innerText = 'Waiting…';

            });

            document.getElementById('pipeFill-1').style.width = '0%';

            document.getElementById('pipeFill-2').style.width = '0%';

        }



        function setPipeNodeState(stage, state) {

            const node = document.getElementById('pipeNode-' + stage);

            if (!node) return;

            node.className = 'pipe-node ' + state;

            if (state === 'done' || state === 'warning') {

                if (stage === 'plan') document.getElementById('pipeFill-1').style.width = '100%';

                if (stage === 'build') document.getElementById('pipeFill-2').style.width = '100%';

            }

        }



        function setPipeSub(stage, text) {

            const el = document.getElementById('pipeSub-' + stage);

            if (el) el.innerText = text;

        }



        function stageLabel(stage) {

            return stage === 'plan' ? '🧠 Architect' : stage === 'build' ? '⚡ Builder' : stage === 'test' ? '🧪 QA Tester' : stage;

        }



        // Parses markdown and UPDATES the project files array

        function updateProjectFilesFromMarkdown(markdown) {

            const regex = /###\s*([a-zA-Z0-9_.\/-]+)\s*[\r\n]+(?:```[a-zA-Z0-9]*\s*[\r\n]+)?([\s\S]*?)(?:```|$)/gi;

            let match;

            let updatedCount = 0;

            let newCount = 0;

            filesTouchedThisRun = new Set();



            while ((match = regex.exec(markdown)) !== null) {

                const path = match[1].trim();

                const content = match[2].trim();



                filesTouchedThisRun.add(path);

                const existingIndex = currentProject.files.findIndex(f => f.path === path);

                if (existingIndex !== -1) {

                    currentProject.files[existingIndex].content = content;

                    updatedCount++;

                } else {

                    currentProject.files.push({ path, content });

                    newCount++;

                }

            }



            if (updatedCount > 0 || newCount > 0) {

                currentProject.lastUpdated = Date.now();

                saveProjectsToStorage();

                renderFileTree();

                if (activeFilePath) openFileByPath(activeFilePath);

            }

            return { newCount, updatedCount };

        }



        // --- LIVE CODE STREAM RENDERING (Builder stage) ---

        function renderCodeStream(text) {

            const wrapper = document.getElementById('codeViewWrapper');

            const header = document.getElementById('codeHeader');

            wrapper.classList.add('streaming');

            header.classList.add('streaming');

            const editor = document.getElementById('codeEditor');

            editor.innerHTML = escapeHtml(text) + '<span class="type-cursor"></span>';

            wrapper.scrollTop = wrapper.scrollHeight;

        }



        function stopCodeStream() {

            document.getElementById('codeViewWrapper').classList.remove('streaming');

            document.getElementById('codeHeader').classList.remove('streaming');

        }



        // --- BUTTON BUSY STATE ---

        function setBtnBusy(btn, labelEl, busyText) {

            if (busyText) {

                labelEl.innerHTML = `<span class="spinner-ring"></span> ${busyText}`;

            }

        }



        // --- PIPELINE EVENT HANDLER ---

        function handlePipelineEvent(evt) {

            switch (evt.type) {

                case 'stage_start':

                    setPipeNodeState(evt.stage, 'active');

                    setPipeSub(evt.stage, 'Connecting…');

                    document.getElementById('updateBtnLabel').innerHTML =

                        `<span class="spinner-ring"></span> ${stageLabel(evt.stage)} working <span class="dot-loader"><span></span><span></span><span></span></span>`;



                    if (evt.stage === 'plan') {

                        appendLiveLog('planLog', '🧠 Architect AI is analyzing the request and planning the files...', 'log-plan');

                    } else if (evt.stage === 'build') {

                        appendTerminal('⚡ Builder AI is writing the code now — watch the editor →', 'build');

                    } else if (evt.stage === 'test') {

                        appendLiveLog('testLog', '🧪 QA Tester AI is reviewing the generated code...', 'log-test');

                    }

                    break;



                case 'status':

                    if (evt.stage) setPipeSub(evt.stage, evt.text);

                    break;



                case 'chunk':

                    if (evt.stage === 'plan') {

                        planBuffer += evt.text;

                        updateLiveLog('planLog', planBuffer);

                    } else if (evt.stage === 'build') {

                        buildBuffer += evt.text;

                        renderCodeStream(buildBuffer);

                    } else if (evt.stage === 'test') {

                        testBuffer += evt.text;

                        updateLiveLog('testLog', testBuffer);

                    }

                    break;



                case 'stage_done':

                    setPipeNodeState(evt.stage, 'done');

                    setPipeSub(evt.stage, evt.provider ? ('via ' + evt.provider) : 'Done');



                    if (evt.stage === 'plan') {

                        const wrap = document.getElementById('planLog-wrap');

                        if (wrap) wrap.insertAdjacentHTML('beforeend',

                            `<details class="report-toggle" open><summary>Architecture plan ready ✓ (click to collapse)</summary></details>`);

                    } else if (evt.stage === 'build') {

                        stopCodeStream();

                        const stats = updateProjectFilesFromMarkdown(evt.fullText);

                        appendTerminal(`✅ Builder finished. New files: ${stats.newCount}, Updated: ${stats.updatedCount}`, 'sys');

                        if (stats.newCount === 0 && stats.updatedCount === 0) {

                            appendTerminal('No code blocks detected in the response. It may have just sent a message.', 'warn');

                        }

                    } else if (evt.stage === 'test') {

                        lastVerdict = evt.verdict;

                        const cls = evt.verdict === 'PASS' ? 'pass' : 'issues';

                        const icon = evt.verdict === 'PASS' ? '✅' : '⚠️';

                        const wrap = document.getElementById('testLog-wrap');

                        if (wrap) wrap.insertAdjacentHTML('beforeend',

                            `<div><span class="verdict-inline ${cls}">${icon} ${evt.verdict === 'PASS' ? 'PASS' : 'ISSUES FOUND'}</span></div>`);

                        const pill = document.getElementById('navVerdictPill');

                        pill.className = 'verdict-pill ' + cls;

                        pill.innerText = (evt.verdict === 'PASS' ? '✅ QA Passed' : '⚠️ QA Found Issues');

                    }

                    break;



                case 'stage_warning':

                    setPipeNodeState(evt.stage, 'warning');

                    setPipeSub(evt.stage, 'Skipped');

                    appendTerminal('⚠ ' + evt.message, 'warn');

                    break;



                case 'error':

                    setPipeNodeState(evt.stage || 'build', 'error');

                    setPipeSub(evt.stage || 'build', 'Failed');

                    stopCodeStream();

                    appendTerminal('❌ ' + evt.message, 'error');

                    break;



                case 'all_done':

                    appendTerminal('🏁 Pipeline complete.', 'sys');

                    break;

            }

        }



        // --- MAIN PIPELINE TRIGGER ---

        async function sendUpdatePrompt() {

            if (isStreaming || !currentProject) return;

            const promptInput = document.getElementById("updatePrompt");

            const promptText = promptInput.value.trim();

            if (!promptText) return;



            promptInput.value = "";

            appendTerminal("USER: " + promptText, "user");



            const btn = document.getElementById("updateBtn");

            const btnLabel = document.getElementById("updateBtnLabel");

            btn.disabled = true;



            isStreaming = true;

            planBuffer = ""; buildBuffer = ""; testBuffer = "";

            filesTouchedThisRun = new Set();

            document.getElementById('navVerdictPill').className = 'verdict-pill';



            resetPipelineTracker();

            showPipelineTracker();

            setBtnBusy(btn, btnLabel, 'Starting pipeline');



            document.getElementById("codeEditor").innerHTML = '<span class="stream-placeholder">// Waiting for the Architect AI to plan this build…</span>';



            try {

                const response = await fetch("/api/agentic-build-stream", {

                    method: "POST",

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

                    body: JSON.stringify({

                        userPrompt: promptText,

                        projectFiles: currentProject.files

                    })

                });



                if (!response.ok) {

                    let errMsg = "HTTP Error " + response.status;

                    try { const errData = await response.json(); if (errData.error) errMsg = errData.error; } catch (e) {}

                    throw new Error(errMsg);

                }



                const reader = response.body.getReader();

                const decoder = new TextDecoder("utf-8");

                let streamBuf = "";



                while (true) {

                    const { done, value } = await reader.read();

                    if (done) break;



                    streamBuf += decoder.decode(value, { stream: true });

                    const events = streamBuf.split("\n\n");

                    streamBuf = events.pop();



                    for (let i = 0; i < events.length; i++) {

                        const line = events[i].trim();

                        if (!line.startsWith("data:")) continue;

                        const jsonStr = line.replace(/^data:\s*/, "");

                        if (!jsonStr) continue;



                        let evt;

                        try { evt = JSON.parse(jsonStr); } catch (e) { continue; }

                        handlePipelineEvent(evt);

                    }

                }



                appendTerminal("AI: Update finished." + (lastVerdict ? ` QA verdict: ${lastVerdict}.` : ""), "ai");



            } catch (err) {

                appendTerminal("Error: " + err.message, "error");

            } finally {

                isStreaming = false;

                btn.disabled = false;

                btnLabel.innerText = "Send Update";

                stopCodeStream();



                if (!activeFilePath && currentProject.files.length > 0) {

                    const htmlFile = currentProject.files.find(f => f.path.endsWith('.html'));

                    openFileByPath(htmlFile ? htmlFile.path : currentProject.files[0].path);

                } else if (activeFilePath) {

                    openFileByPath(activeFilePath);

                }

            }

        }



        // --- PREVIEW & EXPORT UTILS ---

        function runHtmlPreview() {

            if (!activeFilePath || !activeFilePath.endsWith('.html')) return;

            const file = currentProject.files.find(f => f.path === activeFilePath);

            if (!file) return;



            let finalHtml = file.content;

            appendTerminal("Injecting local CSS and JS dependencies...", "sys");



            const endScript = "<" + "/" + "script>";



            currentProject.files.forEach(f => {

                if (f.path.endsWith('.css')) {

                    let filenameOnly = f.path.split('/').pop();

                    let cssRegex = new RegExp("<link[^>]+href=[\"'].*?" + filenameOnly.replace(/\\./g, "\\.") + "[\"'][^>]*>", "gi");

                    if (cssRegex.test(finalHtml)) {

                        appendTerminal("Injected " + f.path, "sys");

                        finalHtml = finalHtml.replace(cssRegex, "<style>\n" + f.content + "\n</style>");

                    }

                }

                if (f.path.endsWith('.js')) {

                    let filenameOnly = f.path.split('/').pop();

                    let jsRegex = new RegExp("<script[^>]+src=[\"'].*?" + filenameOnly.replace(/\\./g, "\\.") + "[\"'][^>]*>[\\s\\S]*?" + endScript, "gi");

                    if (jsRegex.test(finalHtml)) {

                        appendTerminal("Injected " + f.path, "sys");

                        finalHtml = finalHtml.replace(jsRegex, "<script>\n" + f.content + "\n" + endScript);

                    }

                }

            });



            const frame = document.getElementById('previewFrame');

            frame.srcdoc = finalHtml;

            document.getElementById('previewModal').style.display = 'flex';

        }



        async function copyCurrentCode() {

            if (!activeFilePath) return;

            const file = currentProject.files.find(f => f.path === activeFilePath);

            if (file) {

                await navigator.clipboard.writeText(file.content);

                appendTerminal("Copied to clipboard.", "sys");

            }

        }



        async function downloadAllZip() {

            if (!currentProject || currentProject.files.length === 0) return;

            appendTerminal("Compiling ZIP archive...", "sys");

            const zip = new JSZip();



            currentProject.files.forEach(f => {

                zip.file(f.path, f.content);

            });



            const blob = await zip.generateAsync({ type: "blob" });

            const url = URL.createObjectURL(blob);

            const a = document.createElement("a");

            a.href = url;

            a.download = currentProject.name + ".zip";

            document.body.appendChild(a);

            a.click();

            document.body.removeChild(a);

            appendTerminal("Project ZIP downloaded.", "sys");

        }

    </script>
<script src="nav-sidebar.js" data-pos="bl"></script>
</body>
</html>