File size: 49,386 Bytes
f5d79b8
 
 
 
 
c70f857
f5d79b8
 
 
 
c70f857
 
 
 
f5d79b8
 
 
 
c70f857
f5d79b8
c70f857
f5d79b8
 
c70f857
f5d79b8
 
c70f857
f5d79b8
c70f857
 
 
f5d79b8
 
c70f857
 
 
f5d79b8
 
 
c70f857
 
 
 
f5d79b8
c70f857
f5d79b8
c70f857
f5d79b8
c70f857
f5d79b8
c70f857
 
 
 
 
 
 
 
f5d79b8
c70f857
 
 
 
 
 
f5d79b8
 
 
c70f857
 
 
 
 
f5d79b8
c70f857
f5d79b8
c70f857
 
 
f5d79b8
c70f857
 
 
f5d79b8
c70f857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5d79b8
c70f857
 
 
 
 
 
 
 
f5d79b8
c70f857
f5d79b8
c70f857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5d79b8
 
c70f857
 
 
 
 
f5d79b8
c70f857
 
 
f5d79b8
c70f857
 
 
f5d79b8
 
c70f857
 
 
 
 
 
f5d79b8
c70f857
 
 
 
 
 
 
 
 
 
 
 
 
f5d79b8
 
c70f857
 
 
 
 
f5d79b8
c70f857
 
 
 
 
 
 
 
 
 
 
 
 
 
f5d79b8
 
 
 
 
 
c70f857
f5d79b8
c70f857
 
f5d79b8
 
c70f857
 
 
f5d79b8
 
 
 
 
 
c70f857
 
 
 
f5d79b8
c70f857
f5d79b8
c70f857
f5d79b8
c70f857
f5d79b8
c70f857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5d79b8
 
 
 
c70f857
 
f5d79b8
 
 
c70f857
 
 
f5d79b8
 
 
 
 
 
 
 
c70f857
f5d79b8
 
c70f857
f5d79b8
 
 
 
 
c70f857
 
 
f5d79b8
 
 
 
 
 
 
c70f857
f5d79b8
 
 
c70f857
f5d79b8
 
 
c70f857
f5d79b8
 
c70f857
f5d79b8
 
 
 
 
c70f857
f5d79b8
 
 
c70f857
f5d79b8
 
 
 
 
 
 
 
 
 
 
 
 
c70f857
 
 
 
 
 
 
 
 
 
 
 
 
f5d79b8
 
 
 
 
 
 
 
 
 
 
 
 
 
c70f857
f5d79b8
c70f857
f5d79b8
c70f857
f5d79b8
 
c70f857
 
f5d79b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c70f857
f5d79b8
 
c70f857
f5d79b8
 
 
c70f857
f5d79b8
c70f857
 
 
 
f5d79b8
c70f857
 
 
 
 
f5d79b8
 
 
 
 
c70f857
 
 
 
 
 
 
 
 
 
 
f5d79b8
c70f857
f5d79b8
c70f857
 
 
 
 
 
 
 
 
f5d79b8
c70f857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5d79b8
c70f857
 
 
 
f5d79b8
 
c70f857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5d79b8
 
c70f857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5d79b8
c70f857
f5d79b8
c70f857
 
 
f5d79b8
c70f857
 
f5d79b8
c70f857
f5d79b8
c70f857
f5d79b8
c70f857
 
 
 
 
 
f5d79b8
c70f857
f5d79b8
c70f857
 
 
f5d79b8
c70f857
f5d79b8
c70f857
 
 
 
 
 
f5d79b8
c70f857
f5d79b8
c70f857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5d79b8
c70f857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5d79b8
c70f857
f5d79b8
c70f857
f5d79b8
c70f857
 
 
 
 
 
f5d79b8
 
c70f857
 
 
 
 
 
 
 
 
f5d79b8
c70f857
 
 
 
 
 
 
 
 
 
 
 
 
f5d79b8
c70f857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5d79b8
c70f857
 
 
 
 
 
 
f5d79b8
c70f857
f5d79b8
 
c70f857
 
 
 
 
 
 
f5d79b8
 
 
c70f857
f5d79b8
 
 
 
 
 
 
 
 
 
c70f857
f5d79b8
 
 
c70f857
 
f5d79b8
 
c70f857
f5d79b8
 
c70f857
 
 
 
f5d79b8
 
c70f857
f5d79b8
 
 
 
 
c70f857
f5d79b8
 
c70f857
 
f5d79b8
c70f857
 
 
 
 
 
f5d79b8
 
 
c70f857
f5d79b8
 
 
 
 
 
 
c70f857
f5d79b8
 
 
 
c70f857
f5d79b8
 
 
 
 
c70f857
 
f5d79b8
 
c70f857
 
f5d79b8
 
 
 
 
c70f857
 
f5d79b8
c70f857
 
 
 
 
 
f5d79b8
 
 
 
c70f857
 
f5d79b8
c70f857
 
 
 
 
f5d79b8
 
 
 
 
 
c70f857
f5d79b8
 
c70f857
f5d79b8
 
 
c70f857
f5d79b8
 
c70f857
 
 
 
 
f5d79b8
c70f857
 
 
 
 
 
 
 
 
 
 
 
 
f5d79b8
 
 
c70f857
f5d79b8
 
c70f857
f5d79b8
c70f857
f5d79b8
 
 
c70f857
 
 
f5d79b8
 
 
 
c70f857
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>OpenEnv — Multi-Domain AI Agent Environment</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&family=Syne:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
  :root {
    --bg: #07070f;
    --surface: #0f0f1a;
    --surface2: #181826;
    --border: #252538;
    --accent: #6c63ff;
    --accent2: #ff6584;
    --accent3: #43e97b;
    --accent4: #f7971e;
    --accent5: #00d2ff;
    --text: #e8e8f0;
    --text-dim: #6868a0;
    --mono: 'Space Mono', monospace;
    --sans: 'Syne', sans-serif;
    --radius: 10px;
  }
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body { background: var(--bg); color: var(--text); font-family: var(--sans); min-height: 100vh; overflow-x: hidden; }
  body::before {
    content: ''; position: fixed; inset: 0;
    background-image: linear-gradient(rgba(108,99,255,0.03) 1px, transparent 1px), linear-gradient(90deg, rgba(108,99,255,0.03) 1px, transparent 1px);
    background-size: 40px 40px; pointer-events: none; z-index: 0;
  }

  /* ── Layout ── */
  .layout { position: relative; z-index: 1; display: grid; grid-template-rows: auto 1fr; min-height: 100vh; }
  .main { display: grid; grid-template-columns: 260px 1fr 300px; height: calc(100vh - 72px); overflow: hidden; }

  /* ── Header ── */
  header {
    display: flex; align-items: center; justify-content: space-between;
    padding: 16px 28px; border-bottom: 1px solid var(--border);
    background: rgba(7,7,15,0.9); backdrop-filter: blur(12px);
    position: sticky; top: 0; z-index: 100;
  }
  .logo { display: flex; align-items: center; gap: 12px; }
  .logo-icon {
    width: 36px; height: 36px; border-radius: 8px;
    background: linear-gradient(135deg, var(--accent), var(--accent2));
    display: flex; align-items: center; justify-content: center; font-size: 18px;
  }
  .logo-name { font-size: 15px; font-weight: 800; letter-spacing: -0.3px; }
  .logo-sub { font-family: var(--mono); font-size: 10px; color: var(--text-dim); letter-spacing: 1.5px; margin-top: 2px; }
  .header-right { display: flex; align-items: center; gap: 16px; }
  .status-pill {
    display: flex; align-items: center; gap: 6px;
    font-family: var(--mono); font-size: 11px; color: var(--accent3);
    background: rgba(67,233,123,0.08); border: 1px solid rgba(67,233,123,0.2);
    padding: 4px 12px; border-radius: 20px;
  }
  .pulse { width: 7px; height: 7px; background: var(--accent3); border-radius: 50%; animation: pulse 2s infinite; }
  @keyframes pulse { 0%,100%{opacity:1;transform:scale(1)} 50%{opacity:0.4;transform:scale(0.7)} }
  .overall-badge {
    font-family: var(--mono); font-size: 12px; font-weight: 700;
    color: var(--accent); background: rgba(108,99,255,0.1);
    border: 1px solid rgba(108,99,255,0.3); padding: 4px 12px; border-radius: 20px;
  }

  /* ── Sidebar ── */
  .sidebar { border-right: 1px solid var(--border); padding: 16px 14px; overflow-y: auto; display: flex; flex-direction: column; gap: 16px; }
  .domain-label {
    font-family: var(--mono); font-size: 9px; color: var(--text-dim);
    letter-spacing: 2px; text-transform: uppercase; margin-bottom: 6px;
    display: flex; align-items: center; gap: 6px;
  }
  .domain-label::after { content: ''; flex: 1; height: 1px; background: var(--border); }
  .task-card {
    background: var(--surface); border: 1px solid var(--border);
    border-radius: var(--radius); padding: 10px 12px; cursor: pointer;
    transition: all 0.15s; position: relative; overflow: hidden; margin-bottom: 4px;
  }
  .task-card::before { content: ''; position: absolute; left: 0; top: 0; bottom: 0; width: 3px; opacity: 0; transition: opacity 0.15s; }
  .task-card:hover { border-color: rgba(108,99,255,0.4); background: var(--surface2); }
  .task-card.active { border-color: var(--accent); background: var(--surface2); }
  .task-card.active::before { opacity: 1; }
  .task-name { font-size: 12px; font-weight: 700; margin-bottom: 4px; }
  .task-meta { display: flex; align-items: center; gap: 6px; }
  .badge { font-family: var(--mono); font-size: 9px; padding: 2px 6px; border-radius: 4px; font-weight: 700; letter-spacing: 0.5px; }
  .badge-easy { background: rgba(67,233,123,0.12); color: var(--accent3); }
  .badge-medium { background: rgba(247,151,30,0.12); color: var(--accent4); }
  .badge-hard { background: rgba(255,101,132,0.12); color: var(--accent2); }
  .badge-veryhard { background: rgba(108,99,255,0.15); color: var(--accent); }
  .task-score { font-family: var(--mono); font-size: 10px; color: var(--text-dim); margin-left: auto; }

  /* Domain colors for left bar */
  .domain-support .task-card::before { background: var(--accent); }
  .domain-legal .task-card::before { background: var(--accent4); }
  .domain-clinical .task-card::before { background: var(--accent2); }
  .domain-engineering .task-card::before { background: var(--accent5); }

  /* ── Center ── */
  .center { display: flex; flex-direction: column; overflow: hidden; }
  .center-header {
    padding: 16px 24px; border-bottom: 1px solid var(--border);
    display: flex; align-items: center; justify-content: space-between; flex-shrink: 0;
  }
  .center-title { font-size: 18px; font-weight: 800; }
  .center-sub { font-family: var(--mono); font-size: 11px; color: var(--text-dim); margin-top: 3px; }
  .action-bar { display: flex; gap: 8px; }
  .btn { font-family: var(--mono); font-size: 11px; padding: 7px 16px; border-radius: 8px; border: none; cursor: pointer; transition: all 0.15s; font-weight: 700; letter-spacing: 0.5px; }
  .btn-primary { background: var(--accent); color: #fff; }
  .btn-primary:hover { background: #7c74ff; transform: translateY(-1px); }
  .btn-secondary { background: var(--surface2); color: var(--text); border: 1px solid var(--border); }
  .btn-secondary:hover { border-color: var(--accent); }
  .center-body { flex: 1; overflow-y: auto; padding: 20px 24px; }

  /* ── Ticket card ── */
  .ticket-card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 20px; margin-bottom: 14px; animation: slideIn 0.25s ease; }
  @keyframes slideIn { from{opacity:0;transform:translateY(10px)} to{opacity:1;transform:translateY(0)} }
  .ticket-id { font-family: var(--mono); font-size: 10px; color: var(--accent); margin-bottom: 4px; }
  .ticket-subject { font-size: 16px; font-weight: 700; line-height: 1.3; margin-bottom: 12px; }
  .ticket-body { font-size: 13px; line-height: 1.7; color: #b0b0cc; padding: 14px; background: var(--surface2); border-radius: 8px; border-left: 3px solid var(--border); margin-bottom: 14px; }
  .ticket-meta { display: flex; gap: 10px; flex-wrap: wrap; }
  .meta-chip { font-family: var(--mono); font-size: 10px; color: var(--text-dim); background: var(--surface2); padding: 3px 8px; border-radius: 5px; border: 1px solid var(--border); }
  .tier-enterprise { color: var(--accent); border-color: rgba(108,99,255,0.3); }
  .tier-pro { color: var(--accent4); border-color: rgba(247,151,30,0.3); }

  /* ── Domain cards (legal/clinical/pr) ── */
  .domain-card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 20px; margin-bottom: 14px; animation: slideIn 0.25s ease; }
  .domain-card-label { font-family: var(--mono); font-size: 10px; color: var(--text-dim); letter-spacing: 1.5px; text-transform: uppercase; margin-bottom: 6px; }
  .domain-card-title { font-size: 15px; font-weight: 700; margin-bottom: 12px; line-height: 1.4; }
  .domain-card-body { font-size: 13px; line-height: 1.7; color: #b0b0cc; padding: 14px; background: var(--surface2); border-radius: 8px; border-left: 3px solid var(--border); }
  .code-diff { font-family: var(--mono); font-size: 11px; background: #0a0a14; border: 1px solid var(--border); border-radius: 8px; padding: 14px; overflow-x: auto; line-height: 1.6; white-space: pre; }
  .diff-add { color: var(--accent3); }
  .diff-remove { color: var(--accent2); }
  .diff-header { color: var(--text-dim); }

  /* ── Action form ── */
  .action-form { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 20px; margin-top: 14px; }
  .form-title { font-weight: 700; font-size: 14px; margin-bottom: 14px; }
  .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 10px; }
  .form-group { display: flex; flex-direction: column; gap: 5px; }
  .form-label { font-family: var(--mono); font-size: 9px; color: var(--text-dim); letter-spacing: 1px; text-transform: uppercase; }
  .form-select, .form-textarea, .form-input {
    background: var(--surface2); border: 1px solid var(--border); border-radius: 7px;
    color: var(--text); font-family: var(--mono); font-size: 12px; padding: 8px 10px;
    transition: border-color 0.15s; width: 100%;
  }
  .form-select:focus, .form-textarea:focus, .form-input:focus { outline: none; border-color: var(--accent); }
  .form-textarea { font-family: var(--sans); font-size: 13px; resize: vertical; min-height: 100px; line-height: 1.6; }
  .submit-row { display: flex; justify-content: flex-end; margin-top: 14px; }

  /* ── Right panel ── */
  .right-panel { border-left: 1px solid var(--border); padding: 16px 14px; overflow-y: auto; display: flex; flex-direction: column; gap: 16px; }
  .panel-label { font-family: var(--mono); font-size: 9px; color: var(--text-dim); letter-spacing: 2px; text-transform: uppercase; margin-bottom: 10px; }
  .score-card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 16px; }
  .big-score { font-family: var(--mono); font-size: 42px; font-weight: 700; line-height: 1; }
  .score-label { font-family: var(--mono); font-size: 10px; color: var(--text-dim); margin-top: 4px; }
  .breakdown-row { display: flex; justify-content: space-between; align-items: center; padding: 6px 0; border-bottom: 1px solid rgba(37,37,56,0.5); }
  .breakdown-row:last-child { border-bottom: none; }
  .breakdown-label { font-family: var(--mono); font-size: 10px; color: var(--text-dim); }
  .breakdown-val { font-family: var(--mono); font-size: 11px; font-weight: 700; }
  .val-good { color: var(--accent3); } .val-mid { color: var(--accent4); } .val-bad { color: var(--accent2); }
  .mini-chart { height: 50px; display: flex; align-items: flex-end; gap: 2px; }
  .bar { flex: 1; border-radius: 2px 2px 0 0; min-height: 3px; transition: height 0.3s ease; }
  .log-entry { font-family: var(--mono); font-size: 10px; color: var(--text-dim); padding: 5px 8px; border-radius: 4px; margin-bottom: 3px; background: var(--surface); }
  .log-pos { color: var(--accent3); } .log-neg { color: var(--accent2); }

  /* ── Queue ── */
  .queue-item { display: flex; align-items: center; gap: 8px; padding: 8px 10px; background: var(--surface); border: 1px solid var(--border); border-radius: 7px; margin-bottom: 5px; font-size: 11px; }
  .priority-dot { width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0; }
  .p1 { background: var(--accent2); box-shadow: 0 0 5px var(--accent2); } .p2 { background: var(--accent4); } .p3 { background: var(--accent3); } .p4 { background: var(--text-dim); }
  .queue-subject { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

  /* ── Episode done ── */
  .episode-done { background: linear-gradient(135deg, var(--surface2), rgba(108,99,255,0.06)); border: 1px solid rgba(108,99,255,0.25); border-radius: var(--radius); padding: 28px; text-align: center; animation: slideIn 0.35s ease; }
  .done-score { font-family: var(--mono); font-size: 56px; font-weight: 700; color: var(--accent); }
  .done-title { font-size: 20px; font-weight: 800; margin-bottom: 6px; }
  .empty-state { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 280px; color: var(--text-dim); text-align: center; gap: 10px; }
  .empty-icon { font-size: 44px; opacity: 0.25; }

  /* ── Agent cards ── */
  .agent-card { background: var(--surface); border: 1px solid var(--border); border-radius: 8px; padding: 10px; margin-bottom: 6px; }
  .agent-name { font-size: 12px; font-weight: 700; margin-bottom: 6px; }
  .load-bar-track { height: 5px; background: var(--surface2); border-radius: 3px; overflow: hidden; margin-top: 5px; }
  .load-bar-fill { height: 100%; border-radius: 3px; background: linear-gradient(90deg, var(--accent3), var(--accent)); transition: width 0.4s; }
  .load-bar-fill.over { background: linear-gradient(90deg, var(--accent4), var(--accent2)); }

  /* ── Stats bar ── */
  .stats-bar { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-bottom: 14px; }
  .stat-box { background: var(--surface); border: 1px solid var(--border); border-radius: 8px; padding: 12px; text-align: center; }
  .stat-num { font-family: var(--mono); font-size: 26px; font-weight: 700; }
  .stat-label { font-family: var(--mono); font-size: 9px; color: var(--text-dim); letter-spacing: 1px; margin-top: 3px; }

  ::-webkit-scrollbar { width: 4px; } ::-webkit-scrollbar-track { background: transparent; } ::-webkit-scrollbar-thumb { background: var(--border); border-radius: 2px; }
</style>
</head>
<body>
<div class="layout">
  <header>
    <div class="logo">
      <div class="logo-icon">🌐</div>
      <div>
        <div class="logo-name">OpenEnv — Multi-Domain</div>
        <div class="logo-sub">AI AGENT EVALUATION ENVIRONMENT</div>
      </div>
    </div>
    <div class="header-right">
      <div class="overall-badge">OVERALL: <span id="overall-score"></span></div>
      <div class="status-pill"><div class="pulse"></div><span id="server-status">CONNECTING...</span></div>
    </div>
  </header>

  <div class="main">
    <!-- Sidebar -->
    <aside class="sidebar">

      <div class="domain-support">
        <div class="domain-label">🎫 Customer Support</div>
        <div class="task-card active" id="tc-card" onclick="selectTask('ticket_classification')">
          <div class="task-name">Ticket Classification</div>
          <div class="task-meta"><span class="badge badge-easy">EASY</span><span class="task-score" id="score-ticket_classification"></span></div>
        </div>
        <div class="task-card" id="rd-card" onclick="selectTask('response_drafting')">
          <div class="task-name">Response Drafting</div>
          <div class="task-meta"><span class="badge badge-medium">MEDIUM</span><span class="task-score" id="score-response_drafting"></span></div>
        </div>
        <div class="task-card" id="qm-card" onclick="selectTask('queue_management')">
          <div class="task-name">SLA Queue Management</div>
          <div class="task-meta"><span class="badge badge-hard">HARD</span><span class="task-score" id="score-queue_management"></span></div>
        </div>
        <div class="task-card" id="mt-card" onclick="selectTask('multi_turn_conversation')">
          <div class="task-name">Multi-Turn De-escalation</div>
          <div class="task-meta"><span class="badge badge-veryhard">VERY HARD</span><span class="task-score" id="score-multi_turn_conversation"></span></div>
        </div>
      </div>

      <div class="domain-legal">
        <div class="domain-label">⚖️ Legal Review</div>
        <div class="task-card" id="lci-card" onclick="selectTask('legal_clause_identification')">
          <div class="task-name">Clause Identification</div>
          <div class="task-meta"><span class="badge badge-easy">EASY</span><span class="task-score" id="score-legal_clause_identification"></span></div>
        </div>
        <div class="task-card" id="lrf-card" onclick="selectTask('legal_risk_flagging')">
          <div class="task-name">Risk Flagging</div>
          <div class="task-meta"><span class="badge badge-medium">MEDIUM</span><span class="task-score" id="score-legal_risk_flagging"></span></div>
        </div>
        <div class="task-card" id="lcr-card" onclick="selectTask('legal_clause_redlining')">
          <div class="task-name">Clause Redlining</div>
          <div class="task-meta"><span class="badge badge-hard">HARD</span><span class="task-score" id="score-legal_clause_redlining"></span></div>
        </div>
      </div>

      <div class="domain-clinical">
        <div class="domain-label">🏥 Clinical Triage</div>
        <div class="task-card" id="ctc-card" onclick="selectTask('clinical_triage_classification')">
          <div class="task-name">Body System Classification</div>
          <div class="task-meta"><span class="badge badge-easy">EASY</span><span class="task-score" id="score-clinical_triage_classification"></span></div>
        </div>
        <div class="task-card" id="esi-card" onclick="selectTask('clinical_esi_assignment')">
          <div class="task-name">ESI Level Assignment</div>
          <div class="task-meta"><span class="badge badge-medium">MEDIUM</span><span class="task-score" id="score-clinical_esi_assignment"></span></div>
        </div>
        <div class="task-card" id="ctn-card" onclick="selectTask('clinical_triage_note')">
          <div class="task-name">Triage Note Generation</div>
          <div class="task-meta"><span class="badge badge-hard">HARD</span><span class="task-score" id="score-clinical_triage_note"></span></div>
        </div>
      </div>

      <div class="domain-engineering">
        <div class="domain-label">💻 PR Review</div>
        <div class="task-card" id="ptc-card" onclick="selectTask('pr_type_classification')">
          <div class="task-name">PR Type Classification</div>
          <div class="task-meta"><span class="badge badge-easy">EASY</span><span class="task-score" id="score-pr_type_classification"></span></div>
        </div>
        <div class="task-card" id="pbi-card" onclick="selectTask('pr_bug_identification')">
          <div class="task-name">Bug Identification</div>
          <div class="task-meta"><span class="badge badge-medium">MEDIUM</span><span class="task-score" id="score-pr_bug_identification"></span></div>
        </div>
        <div class="task-card" id="prc-card" onclick="selectTask('pr_review_comment')">
          <div class="task-name">Code Review Comment</div>
          <div class="task-meta"><span class="badge badge-hard">HARD</span><span class="task-score" id="score-pr_review_comment"></span></div>
        </div>
      </div>

      <div>
        <div class="domain-label">Episode Log</div>
        <div id="log-container" style="max-height:200px;overflow-y:auto;"></div>
      </div>

      <div>
        <div class="domain-label">API Links</div>
        <a href="/docs" target="_blank" style="display:flex;align-items:center;gap:8px;color:var(--accent);font-size:12px;text-decoration:none;padding:8px;background:var(--surface);border-radius:8px;border:1px solid var(--border);margin-bottom:5px;">📖 Swagger API Docs</a>
        <a href="/tasks" target="_blank" style="display:flex;align-items:center;gap:8px;color:var(--text-dim);font-size:12px;text-decoration:none;padding:8px;background:var(--surface);border-radius:8px;border:1px solid var(--border);">📋 /tasks endpoint</a>
      </div>
    </aside>

    <!-- Center -->
    <main class="center">
      <div class="center-header">
        <div>
          <div class="center-title" id="center-title">Ticket Classification</div>
          <div class="center-sub">Step <span id="step-counter">0</span> / <span id="max-steps">10</span> &nbsp;|&nbsp; <span id="domain-label">Customer Support</span></div>
        </div>
        <div class="action-bar">
          <button class="btn btn-secondary" onclick="runBaseline()">▶ Run Heuristic Baseline</button>
          <button class="btn btn-primary" onclick="resetEpisode()">↺ Reset Episode</button>
        </div>
      </div>
      <div class="center-body" id="center-body">
        <div class="empty-state">
          <div class="empty-icon">🌐</div>
          <div style="font-size:14px;font-weight:700;">Multi-Domain AI Agent Environment</div>
          <div style="font-size:12px;max-width:300px;line-height:1.6;">13 tasks across 4 professional domains. Select a task from the sidebar and click Reset Episode to begin.</div>
        </div>
      </div>
    </main>

    <!-- Right panel -->
    <aside class="right-panel">
      <div>
        <div class="panel-label">Episode Score</div>
        <div class="score-card">
          <div class="big-score" id="current-score" style="color:var(--accent)"></div>
          <div class="score-label" id="score-status">No active episode</div>
          <div style="margin-top:12px;" id="score-breakdown"></div>
        </div>
      </div>
      <div>
        <div class="panel-label">Reward History</div>
        <div class="score-card">
          <div class="mini-chart" id="reward-chart"></div>
          <div style="display:flex;justify-content:space-between;margin-top:5px;font-family:var(--mono);font-size:9px;color:var(--text-dim);">
            <span>+1.0</span><span>avg: <span id="avg-reward"></span></span><span>-1.0</span>
          </div>
        </div>
      </div>
      <div id="agents-section" style="display:none;">
        <div class="panel-label">Agent Status</div>
        <div id="agents-container"></div>
      </div>
      <div id="queue-section" style="display:none;">
        <div class="panel-label">Ticket Queue</div>
        <div id="queue-container"></div>
      </div>
    </aside>
  </div>
</div>

<script>
const API = '';
let currentTaskId = 'ticket_classification';
let currentObs = null;
let rewardHistory = [];

const TASK_CONFIG = {
  ticket_classification:          { title: 'Ticket Classification', domain: 'Customer Support', maxSteps: 10, cardId: 'tc-card' },
  response_drafting:              { title: 'Response Drafting', domain: 'Customer Support', maxSteps: 6, cardId: 'rd-card' },
  queue_management:               { title: 'SLA Queue Management', domain: 'Customer Support', maxSteps: 40, cardId: 'qm-card' },
  multi_turn_conversation:        { title: 'Multi-Turn De-escalation', domain: 'Customer Support', maxSteps: 8, cardId: 'mt-card' },
  legal_clause_identification:    { title: 'Legal Clause Identification', domain: 'Legal Review', maxSteps: 10, cardId: 'lci-card' },
  legal_risk_flagging:            { title: 'Legal Risk Flagging', domain: 'Legal Review', maxSteps: 10, cardId: 'lrf-card' },
  legal_clause_redlining:         { title: 'Legal Clause Redlining', domain: 'Legal Review', maxSteps: 5, cardId: 'lcr-card' },
  clinical_triage_classification: { title: 'Clinical Triage Classification', domain: 'Clinical Triage', maxSteps: 10, cardId: 'ctc-card' },
  clinical_esi_assignment:        { title: 'ESI Level Assignment', domain: 'Clinical Triage', maxSteps: 10, cardId: 'esi-card' },
  clinical_triage_note:           { title: 'Triage Note Generation', domain: 'Clinical Triage', maxSteps: 5, cardId: 'ctn-card' },
  pr_type_classification:         { title: 'PR Type Classification', domain: 'PR Review', maxSteps: 10, cardId: 'ptc-card' },
  pr_bug_identification:          { title: 'PR Bug Identification', domain: 'PR Review', maxSteps: 5, cardId: 'pbi-card' },
  pr_review_comment:              { title: 'PR Code Review', domain: 'PR Review', maxSteps: 5, cardId: 'prc-card' },
};

async function api(method, path, body) {
  const opts = { method, headers: { 'Content-Type': 'application/json' } };
  if (body) opts.body = JSON.stringify(body);
  const r = await fetch(API + path, opts);
  if (!r.ok) throw new Error(await r.text());
  return r.json();
}

function selectTask(taskId) {
  currentTaskId = taskId;
  document.querySelectorAll('.task-card').forEach(c => c.classList.remove('active'));
  const cfg = TASK_CONFIG[taskId];
  document.getElementById(cfg.cardId).classList.add('active');
  document.getElementById('center-title').textContent = cfg.title;
  document.getElementById('domain-label').textContent = cfg.domain;
  document.getElementById('max-steps').textContent = cfg.maxSteps;
  document.getElementById('step-counter').textContent = 0;
  document.getElementById('center-body').innerHTML = `
    <div class="empty-state">
      <div class="empty-icon"></div>
      <div style="font-size:13px;">Click "Reset Episode" to start this task</div>
    </div>`;
  rewardHistory = [];
  updateRewardChart();
  document.getElementById('current-score').textContent = '—';
  document.getElementById('score-status').textContent = 'No active episode';
  document.getElementById('score-breakdown').innerHTML = '';
  document.getElementById('agents-section').style.display = 'none';
  document.getElementById('queue-section').style.display = 'none';
}

async function resetEpisode() {
  rewardHistory = [];
  document.getElementById('log-container').innerHTML = '';
  try {
    const data = await api('POST', `/reset?task_id=${currentTaskId}`);
    currentObs = data.observation;
    document.getElementById('step-counter').textContent = currentObs.step || 0;
    renderObservation(currentObs);
    addLog(`↺ Reset — ${currentTaskId}`);
    updateAgents(currentObs.agents);
    updateQueue(currentObs.ticket_queue, currentObs.sla_status);
  } catch(e) { addLog(`❌ ${e.message}`, 'neg'); }
}

function renderObservation(obs) {
  if (obs.episode_done) { fetchGrader(); return; }
  const body = document.getElementById('center-body');
  const ticket = obs.current_ticket;
  const clause = obs.current_clause;
  const patient = obs.current_patient;
  const pr = obs.current_pr;

  if (ticket) renderTicketView(obs, body);
  else if (clause) renderLegalView(obs, body);
  else if (patient) renderClinicalView(obs, body);
  else if (pr) renderPRView(obs, body);
  else body.innerHTML = `<div class="empty-state"><div class="empty-icon"></div><div>Step complete</div></div>`;

  updateAgents(obs.agents);
  updateQueue(obs.ticket_queue, obs.sla_status);
}

function renderTicketView(obs, body) {
  const t = obs.current_ticket;
  const isQueue = currentTaskId === 'queue_management';
  const isMT = currentTaskId === 'multi_turn_conversation';
  const history = t.previous_interactions || [];

  let historyHTML = '';
  if (history.length > 0) {
    historyHTML = `<div style="margin-bottom:12px;"><div style="font-family:var(--mono);font-size:10px;color:var(--text-dim);margin-bottom:8px;">CONVERSATION HISTORY</div>` +
      history.map(m => `<div style="padding:8px;margin-bottom:6px;border-radius:6px;background:${m.role==='customer'?'var(--surface2)':'rgba(108,99,255,0.08)'};border:1px solid var(--border);font-size:12px;"><span style="font-family:var(--mono);font-size:9px;color:var(--text-dim);text-transform:uppercase;">${m.role}:</span> ${m.content}</div>`).join('') + `</div>`;
  }

  body.innerHTML = `
    <div class="ticket-card">
      <div class="ticket-id">${t.ticket_id}</div>
      <div class="ticket-subject">${t.subject}</div>
      ${historyHTML}
      <div class="ticket-body">${t.body}</div>
      <div class="ticket-meta">
        <span class="meta-chip tier-${t.customer_tier}">${t.customer_tier?.toUpperCase()}</span>
        ${t.category ? `<span class="meta-chip">📁 ${t.category}</span>` : ''}
        ${t.priority ? `<span class="meta-chip">🔺 ${t.priority}</span>` : ''}
        <span class="meta-chip">😶 Sentiment: ${(t.sentiment_score||0).toFixed(2)}</span>
      </div>
    </div>
    ${obs.knowledge_base?.length ? renderKB(obs.knowledge_base) : ''}
    ${renderActionForm(obs)}`;
}

function renderLegalView(obs, body) {
  const c = obs.current_clause;
  body.innerHTML = `
    <div class="domain-card">
      <div class="domain-card-label">${c.contract_type} — ${c.counterparty}</div>
      <div class="domain-card-title">Clause ${c.clause_id}</div>
      <div class="domain-card-body">${c.text}</div>
      ${c.true_risk_level ? `<div style="margin-top:10px;font-family:var(--mono);font-size:11px;color:var(--accent4);">Known Risk Level: ${c.true_risk_level}</div>` : ''}
    </div>
    ${renderActionForm(obs)}`;
}

function renderClinicalView(obs, body) {
  const p = obs.current_patient;
  const vitals = p.vitals || {};
  body.innerHTML = `
    <div class="domain-card">
      <div class="domain-card-label">Patient ${p.patient_id} — Age ${p.age} ${p.gender}</div>
      <div class="domain-card-title">${p.chief_complaint}</div>
      <div style="display:grid;grid-template-columns:repeat(5,1fr);gap:8px;margin:12px 0;">
        ${Object.entries(vitals).map(([k,v]) => `<div style="background:var(--surface2);border:1px solid var(--border);border-radius:6px;padding:8px;text-align:center;"><div style="font-family:var(--mono);font-size:14px;font-weight:700;">${v}</div><div style="font-family:var(--mono);font-size:9px;color:var(--text-dim);margin-top:2px;">${k}</div></div>`).join('')}
      </div>
      <div class="domain-card-body"><strong>History:</strong> ${p.history}</div>
      ${p.true_esi_level ? `<div style="margin-top:10px;font-family:var(--mono);font-size:11px;color:var(--accent4);">Known ESI Level: ${p.true_esi_level}</div>` : ''}
    </div>
    ${renderActionForm(obs)}`;
}

function renderPRView(obs, body) {
  const pr = obs.current_pr;
  const diffLines = (pr.diff||'').split('\n').map(line => {
    if (line.startsWith('+')) return `<span class="diff-add">${escHtml(line)}</span>`;
    if (line.startsWith('-')) return `<span class="diff-remove">${escHtml(line)}</span>`;
    if (line.startsWith('@@')) return `<span class="diff-header">${escHtml(line)}</span>`;
    return escHtml(line);
  }).join('\n');
  body.innerHTML = `
    <div class="domain-card">
      <div class="domain-card-label">PR ${pr.pr_id} — by ${pr.author}</div>
      <div class="domain-card-title">${pr.title}</div>
      <div class="domain-card-body" style="margin-bottom:12px;">${pr.description}</div>
      <div class="code-diff">${diffLines}</div>
      ${pr.true_bug_description ? `<div style="margin-top:10px;font-family:var(--mono);font-size:11px;color:var(--accent4);">Known Bug: ${pr.true_bug_description}</div>` : ''}
    </div>
    ${renderActionForm(obs)}`;
}

function escHtml(s) { return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }

function renderKB(articles) {
  return `<div style="margin-bottom:14px;">
    <div style="font-family:var(--mono);font-size:9px;color:var(--text-dim);letter-spacing:2px;text-transform:uppercase;margin-bottom:8px;">Knowledge Base</div>
    ${articles.slice(0,2).map(a => `
      <div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:12px;margin-bottom:6px;">
        <div style="font-size:12px;font-weight:700;margin-bottom:4px;"><span style="font-family:var(--mono);font-size:10px;color:var(--accent);margin-right:8px;">${a.article_id}</span>${a.title}</div>
        <div style="font-size:11px;color:var(--text-dim);line-height:1.5;">${a.content?.substring(0,200)}...</div>
      </div>`).join('')}
  </div>`;
}

function renderActionForm(obs) {
  const tid = currentTaskId;
  const actions = obs.valid_actions || [];

  if (tid === 'ticket_classification') {
    const t = obs.current_ticket;
    return `<div class="action-form"><div class="form-title">⚡ Classify Ticket</div>
      <div class="form-row">
        <div class="form-group"><label class="form-label">Category</label>
          <select class="form-select" id="f-category">
            ${['billing','technical','account','feature_request','abuse','unknown'].map(c => `<option value="${c}">${c.replace('_',' ').toUpperCase()}</option>`).join('')}
          </select></div>
        <div class="form-group"><label class="form-label">Priority</label>
          <select class="form-select" id="f-priority">
            ${['P1','P2','P3','P4'].map(p => `<option value="${p}">${p}</option>`).join('')}
          </select></div>
      </div>
      <div class="submit-row"><button class="btn btn-primary" onclick="submitAction({action_type:'classify',ticket_id:'${t?.ticket_id}',category:document.getElementById('f-category').value,priority:document.getElementById('f-priority').value})">Submit →</button></div>
    </div>`;
  }

  if (tid === 'response_drafting') {
    const t = obs.current_ticket;
    return `<div class="action-form"><div class="form-title">✍️ Draft Response</div>
      <div class="form-group" style="margin-bottom:10px;"><label class="form-label">Response Text</label>
        <textarea class="form-textarea" id="f-response" placeholder="Write a professional customer response..."></textarea></div>
      <div class="submit-row"><button class="btn btn-primary" onclick="submitAction({action_type:'draft_response',ticket_id:'${t?.ticket_id}',response_text:document.getElementById('f-response').value})">Send →</button></div>
    </div>`;
  }

  if (tid === 'queue_management') {
    const queue = obs.ticket_queue || [];
    return `<div class="action-form"><div class="form-title">⚙️ Queue Action</div>
      <div class="form-row">
        <div class="form-group"><label class="form-label">Ticket</label>
          <select class="form-select" id="f-ticket-id">
            ${queue.map(t => `<option value="${t.ticket_id}">${t.ticket_id} | ${t.priority||'?'} | ${t.subject?.substring(0,30)}</option>`).join('')}
          </select></div>
        <div class="form-group"><label class="form-label">Action</label>
          <select class="form-select" id="f-action-type" onchange="toggleAgentRow()">
            ${['assign_ticket','resolve','escalate','close','no_op'].map(a => `<option value="${a}">${a.replace('_',' ').toUpperCase()}</option>`).join('')}
          </select></div>
      </div>
      <div id="agent-row" class="form-group" style="margin-bottom:10px;"><label class="form-label">Assign To</label>
        <select class="form-select" id="f-agent-id">
          <option value="agent_billing">agent_billing — Billing Specialist</option>
          <option value="agent_tech">agent_tech — Technical Support</option>
          <option value="agent_general">agent_general — General Support</option>
        </select></div>
      <div class="submit-row"><button class="btn btn-primary" onclick="submitQueueAction()">Execute →</button></div>
    </div>`;
  }

  if (tid === 'multi_turn_conversation') {
    const t = obs.current_ticket;
    return `<div class="action-form"><div class="form-title">💬 Respond or Escalate</div>
      <div class="form-group" style="margin-bottom:10px;"><label class="form-label">Response</label>
        <textarea class="form-textarea" id="f-mt-response" placeholder="Write your response to the customer..."></textarea></div>
      <div class="submit-row" style="gap:8px;">
        <button class="btn btn-secondary" onclick="submitAction({action_type:'escalate',ticket_id:'${t?.ticket_id}'})">↑ Escalate</button>
        <button class="btn btn-secondary" onclick="submitAction({action_type:'resolve',ticket_id:'${t?.ticket_id}'})">✓ Resolve</button>
        <button class="btn btn-primary" onclick="submitAction({action_type:'draft_response',ticket_id:'${t?.ticket_id}',response_text:document.getElementById('f-mt-response').value})">Send →</button>
      </div>
    </div>`;
  }

  if (tid === 'legal_clause_identification') {
    return `<div class="action-form"><div class="form-title">⚖️ Identify Clause Type</div>
      <div class="form-group" style="margin-bottom:10px;"><label class="form-label">Clause Type</label>
        <select class="form-select" id="f-clause-type">
          ${['indemnity','liability','ip','termination','unknown'].map(c => `<option value="${c}">${c.toUpperCase()}</option>`).join('')}
        </select></div>
      <div class="submit-row"><button class="btn btn-primary" onclick="submitAction({action_type:'identify_clause',clause_type:document.getElementById('f-clause-type').value})">Submit →</button></div>
    </div>`;
  }

  if (tid === 'legal_risk_flagging') {
    return `<div class="action-form"><div class="form-title">🚩 Flag Risk Level</div>
      <div class="form-row">
        <div class="form-group"><label class="form-label">Risk Level</label>
          <select class="form-select" id="f-risk-level">
            ${['low','medium','high','critical'].map(r => `<option value="${r}">${r.toUpperCase()}</option>`).join('')}
          </select></div>
        <div class="form-group"><label class="form-label">Reasoning</label>
          <input class="form-input" id="f-risk-reason" placeholder="Brief justification..."/></div>
      </div>
      <div class="submit-row"><button class="btn btn-primary" onclick="submitAction({action_type:'flag_risk',risk_level:document.getElementById('f-risk-level').value,reasoning:document.getElementById('f-risk-reason').value})">Submit →</button></div>
    </div>`;
  }

  if (tid === 'legal_clause_redlining') {
    return `<div class="action-form"><div class="form-title">✏️ Redline Clause</div>
      <div class="form-group" style="margin-bottom:10px;"><label class="form-label">Improved Clause Text</label>
        <textarea class="form-textarea" id="f-redline" placeholder="Write the improved, lower-risk version of this clause..."></textarea></div>
      <div class="submit-row"><button class="btn btn-primary" onclick="submitAction({action_type:'redline',redline_text:document.getElementById('f-redline').value})">Submit →</button></div>
    </div>`;
  }

  if (tid === 'clinical_triage_classification') {
    return `<div class="action-form"><div class="form-title">🏥 Classify Body System</div>
      <div class="form-group" style="margin-bottom:10px;"><label class="form-label">Body System</label>
        <select class="form-select" id="f-body-system">
          ${['cardiac','respiratory','neurologic','gi','musculoskeletal','other'].map(s => `<option value="${s}">${s.toUpperCase()}</option>`).join('')}
        </select></div>
      <div class="submit-row"><button class="btn btn-primary" onclick="submitAction({action_type:'classify_triage',body_system:document.getElementById('f-body-system').value})">Submit →</button></div>
    </div>`;
  }

  if (tid === 'clinical_esi_assignment') {
    return `<div class="action-form"><div class="form-title">🔢 Assign ESI Level</div>
      <div class="form-row">
        <div class="form-group"><label class="form-label">ESI Level (1=Critical, 5=Non-urgent)</label>
          <select class="form-select" id="f-esi">
            ${[1,2,3,4,5].map(n => `<option value="${n}">ESI ${n}</option>`).join('')}
          </select></div>
        <div class="form-group"><label class="form-label">Reasoning</label>
          <input class="form-input" id="f-esi-reason" placeholder="Clinical justification..."/></div>
      </div>
      <div class="submit-row"><button class="btn btn-primary" onclick="submitAction({action_type:'assign_esi',esi_level:parseInt(document.getElementById('f-esi').value),reasoning:document.getElementById('f-esi-reason').value})">Submit →</button></div>
    </div>`;
  }

  if (tid === 'clinical_triage_note') {
    return `<div class="action-form"><div class="form-title">📋 Write Triage Note</div>
      <div class="form-group" style="margin-bottom:10px;"><label class="form-label">Clinical Triage Note</label>
        <textarea class="form-textarea" id="f-note" placeholder="Patient presents with... Immediate actions: stat IV access, oxygen, continuous monitor..."></textarea></div>
      <div class="submit-row"><button class="btn btn-primary" onclick="submitAction({action_type:'write_triage_note',triage_note:document.getElementById('f-note').value})">Submit →</button></div>
    </div>`;
  }

  if (tid === 'pr_type_classification') {
    return `<div class="action-form"><div class="form-title">🔍 Classify PR Type</div>
      <div class="form-group" style="margin-bottom:10px;"><label class="form-label">PR Type</label>
        <select class="form-select" id="f-pr-type">
          ${['bug_fix','feature','refactor','security'].map(t => `<option value="${t}">${t.replace('_',' ').toUpperCase()}</option>`).join('')}
        </select></div>
      <div class="submit-row"><button class="btn btn-primary" onclick="submitAction({action_type:'classify_pr',pr_type:document.getElementById('f-pr-type').value})">Submit →</button></div>
    </div>`;
  }

  if (tid === 'pr_bug_identification') {
    return `<div class="action-form"><div class="form-title">🐛 Identify Bug</div>
      <div class="form-group" style="margin-bottom:10px;"><label class="form-label">Bug Description</label>
        <textarea class="form-textarea" id="f-bug" placeholder="Describe the specific vulnerability or bug found in this diff..."></textarea></div>
      <div class="submit-row"><button class="btn btn-primary" onclick="submitAction({action_type:'identify_bug',bug_description:document.getElementById('f-bug').value})">Submit →</button></div>
    </div>`;
  }

  if (tid === 'pr_review_comment') {
    return `<div class="action-form"><div class="form-title">💬 Write Review Comment</div>
      <div class="form-group" style="margin-bottom:10px;"><label class="form-label">Review Comment</label>
        <textarea class="form-textarea" id="f-review" placeholder="Approve or block this PR with your code review comment..."></textarea></div>
      <div class="submit-row"><button class="btn btn-primary" onclick="submitAction({action_type:'review_pr',review_comment:document.getElementById('f-review').value})">Submit →</button></div>
    </div>`;
  }

  return '';
}

function toggleAgentRow() {
  const action = document.getElementById('f-action-type')?.value;
  const row = document.getElementById('agent-row');
  if (row) row.style.display = action === 'assign_ticket' ? 'flex' : 'none';
}

function submitQueueAction() {
  const action_type = document.getElementById('f-action-type').value;
  const ticket_id = document.getElementById('f-ticket-id')?.value;
  const target_agent_id = document.getElementById('f-agent-id')?.value;
  submitAction({ action_type, ticket_id, target_agent_id });
}

async function submitAction(actionBody) {
  try {
    const data = await api('POST', `/step?task_id=${currentTaskId}`, actionBody);
    currentObs = data.observation;
    const reward = data.reward;
    rewardHistory.push(reward.total);
    document.getElementById('step-counter').textContent = currentObs.step || rewardHistory.length;
    const sign = reward.total >= 0 ? '+' : '';
    addLog(`Step ${rewardHistory.length}: ${sign}${reward.total.toFixed(3)}`, reward.total >= 0 ? 'pos' : 'neg');
    updateRewardChart();
    updateScoreDisplay(reward);
    renderObservation(currentObs);
    if (data.done) fetchGrader();
  } catch(e) { addLog(`❌ ${e.message}`, 'neg'); }
}

async function fetchGrader() {
  try {
    const result = await api('POST', `/grader?task_id=${currentTaskId}`);
    showDone(result);
    document.getElementById(`score-${currentTaskId}`).textContent = result.final_score.toFixed(3);
    updateOverallScore();
  } catch(e) { console.error(e); }
}

function showDone(result) {
  const score = result.final_score;
  const color = score >= 0.7 ? 'var(--accent3)' : score >= 0.4 ? 'var(--accent4)' : 'var(--accent2)';
  const emoji = score >= 0.7 ? '🏆' : score >= 0.4 ? '📊' : '📉';
  document.getElementById('center-body').innerHTML = `
    <div class="episode-done">
      <div style="font-size:36px;margin-bottom:12px;">${emoji}</div>
      <div class="done-title">Episode Complete</div>
      <div class="done-score" style="color:${color}">${score.toFixed(4)}</div>
      <div style="font-family:var(--mono);font-size:12px;color:var(--text-dim);margin:8px 0 20px">
        ${result.passed ? '✓ PASSED' : '✗ DID NOT PASS'} &nbsp;|&nbsp; ${rewardHistory.length} steps
      </div>
      ${Object.entries(result.metrics||{}).filter(([k,v])=>typeof v==='number').map(([k,v])=>`
        <div class="breakdown-row">
          <span class="breakdown-label">${k.replace(/_/g,' ')}</span>
          <span class="breakdown-val ${v>=0.7?'val-good':v>=0.4?'val-mid':'val-bad'}">${v.toFixed(4)}</span>
        </div>`).join('')}
      <button class="btn btn-primary" style="margin-top:20px;" onclick="resetEpisode()">↺ New Episode</button>
    </div>`;
  document.getElementById('current-score').textContent = score.toFixed(4);
  document.getElementById('current-score').style.color = color;
  document.getElementById('score-status').textContent = result.passed ? '✓ Passed' : '✗ Did not pass';
}

function updateScoreDisplay(reward) {
  const total = reward.total;
  const color = total >= 0.6 ? 'var(--accent3)' : total >= 0.2 ? 'var(--accent4)' : 'var(--accent2)';
  document.getElementById('current-score').textContent = total.toFixed(4);
  document.getElementById('current-score').style.color = color;
  document.getElementById('score-status').textContent = 'Step reward';
  const bd = reward.breakdown || {};
  document.getElementById('score-breakdown').innerHTML = Object.entries(bd).map(([k,v]) => `
    <div class="breakdown-row">
      <span class="breakdown-label">${k.replace(/_/g,' ')}</span>
      <span class="breakdown-val ${v>=0.6?'val-good':v<0?'val-bad':'val-mid'}">${typeof v==='number'?v.toFixed(3):v}</span>
    </div>`).join('');
}

function updateRewardChart() {
  const container = document.getElementById('reward-chart');
  if (!rewardHistory.length) { container.innerHTML=''; return; }
  const avg = (rewardHistory.reduce((a,b)=>a+b,0)/rewardHistory.length).toFixed(3);
  document.getElementById('avg-reward').textContent = avg;
  container.innerHTML = rewardHistory.map(r => {
    const pct = ((r+1)/2*100).toFixed(1);
    const color = r>=0.3?'var(--accent3)':r>=0?'var(--accent4)':'var(--accent2)';
    return `<div class="bar" style="height:${pct}%;background:${color};opacity:0.8;"></div>`;
  }).join('');
}

function updateAgents(agents) {
  if (!agents?.length) { document.getElementById('agents-section').style.display='none'; return; }
  document.getElementById('agents-section').style.display='block';
  document.getElementById('agents-container').innerHTML = agents.map(a => {
    const pct = (a.current_load/a.max_load*100).toFixed(0);
    return `<div class="agent-card">
      <div class="agent-name">${a.name}</div>
      <div style="font-family:var(--mono);font-size:9px;color:var(--text-dim);">Load: ${a.current_load}/${a.max_load}</div>
      <div class="load-bar-track"><div class="load-bar-fill ${a.current_load>=a.max_load?'over':''}" style="width:${pct}%"></div></div>
    </div>`;
  }).join('');
}

function updateQueue(queue, slaStatus) {
  if (!queue?.length) { document.getElementById('queue-section').style.display='none'; return; }
  document.getElementById('queue-section').style.display='block';
  document.getElementById('queue-container').innerHTML = queue.slice(0,8).map(t => {
    const p = (t.priority||'P3').replace('_CRITICAL','').replace('_HIGH','').replace('_MEDIUM','').replace('_LOW','').toLowerCase();
    return `<div class="queue-item">
      <div class="priority-dot ${p}"></div>
      <span class="queue-subject">${t.subject||t.ticket_id}</span>
    </div>`;
  }).join('');
}

function addLog(message, type) {
  const container = document.getElementById('log-container');
  const div = document.createElement('div');
  div.className = `log-entry ${type==='pos'?'log-pos':type==='neg'?'log-neg':''}`;
  div.textContent = message;
  container.insertBefore(div, container.firstChild);
  if (container.children.length > 40) container.removeChild(container.lastChild);
}

async function runBaseline() {
  addLog('⚡ Running heuristic baseline...');
  try {
    const data = await api('POST', '/baseline');
    Object.entries(data.tasks||{}).forEach(([tid, result]) => {
      const el = document.getElementById(`score-${tid}`);
      if (el) el.textContent = result.final_score.toFixed(3);
      addLog(`${tid.replace(/_/g,' ')}: ${result.final_score.toFixed(3)} ${result.passed?'✓':'✗'}`,
             result.final_score >= 0.5 ? 'pos' : 'neg');
    });
    document.getElementById('overall-score').textContent = data.overall_score.toFixed(3);
    addLog(`Overall: ${data.overall_score.toFixed(3)}`, data.overall_score > 0.6 ? 'pos' : 'neg');
  } catch(e) { addLog(`Baseline error: ${e.message}`, 'neg'); }
}

function updateOverallScore() {
  const scores = Object.keys(TASK_CONFIG).map(tid => {
    const el = document.getElementById(`score-${tid}`);
    return el && el.textContent !== '—' ? parseFloat(el.textContent) : null;
  }).filter(s => s !== null);
  if (scores.length > 0) {
    const avg = scores.reduce((a,b)=>a+b,0)/scores.length;
    document.getElementById('overall-score').textContent = avg.toFixed(3);
  }
}

// Health check on load
(async () => {
  try {
    const h = await api('GET', '/health');
    document.getElementById('server-status').textContent = 'LIVE';
    addLog(`✓ Server online — ${h.tasks?.length||0} tasks`);
  } catch(e) {
    document.getElementById('server-status').textContent = 'OFFLINE';
    document.getElementById('server-status').style.color = 'var(--accent2)';
    document.querySelector('.status-pill').style.color = 'var(--accent2)';
    document.querySelector('.status-pill').style.borderColor = 'rgba(255,101,132,0.3)';
    document.querySelector('.pulse').style.background = 'var(--accent2)';
  }
})();
</script>
</body>
</html>