File size: 72,795 Bytes
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9d9189
 
 
 
 
 
 
 
 
 
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9d9189
6303ae6
 
c9d9189
6303ae6
 
 
 
c9d9189
 
 
 
 
 
357ee36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9d9189
 
 
 
 
 
 
 
 
 
6303ae6
 
c9d9189
 
6303ae6
 
c9d9189
 
 
 
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9d9189
6303ae6
c9d9189
 
6303ae6
 
 
 
c9d9189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6303ae6
 
c9d9189
 
 
 
 
 
 
 
 
 
 
 
 
 
6303ae6
c9d9189
 
 
6303ae6
c9d9189
 
6303ae6
 
 
 
c9d9189
6303ae6
c9d9189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6303ae6
 
 
 
 
c9d9189
6303ae6
 
 
c9d9189
 
 
6303ae6
 
 
c9d9189
 
 
 
6303ae6
 
357ee36
 
 
 
 
c9d9189
6303ae6
c9d9189
 
6303ae6
 
c9d9189
6303ae6
 
 
c9d9189
6303ae6
 
c9d9189
 
 
6303ae6
 
c9d9189
 
6303ae6
c9d9189
 
6303ae6
c9d9189
6303ae6
c9d9189
 
 
 
 
 
 
6303ae6
c9d9189
 
 
 
6303ae6
c9d9189
6303ae6
c9d9189
 
 
 
6303ae6
 
c9d9189
6303ae6
 
c9d9189
6303ae6
 
 
c9d9189
6303ae6
c9d9189
6303ae6
 
c9d9189
 
 
6303ae6
c9d9189
6303ae6
 
c9d9189
 
 
6303ae6
c9d9189
 
 
6303ae6
c9d9189
 
 
 
6303ae6
c9d9189
 
6303ae6
c9d9189
 
6303ae6
c9d9189
6303ae6
c9d9189
 
 
6303ae6
c9d9189
6303ae6
c9d9189
 
 
 
6303ae6
 
c9d9189
 
 
 
6303ae6
 
c9d9189
 
 
6303ae6
 
 
93411b2
6303ae6
 
c9d9189
 
 
6303ae6
 
 
 
c9d9189
6303ae6
c9d9189
 
 
6303ae6
c9d9189
 
 
 
 
 
 
 
6303ae6
c9d9189
6303ae6
c9d9189
 
6303ae6
c9d9189
 
6303ae6
c9d9189
 
 
6303ae6
c9d9189
 
6303ae6
c9d9189
 
 
 
 
6303ae6
 
 
 
 
c9d9189
6303ae6
 
 
 
 
c9d9189
 
6303ae6
 
 
 
 
c9d9189
 
 
 
6303ae6
 
 
 
 
c9d9189
6303ae6
 
c9d9189
6303ae6
c9d9189
 
6303ae6
 
 
c9d9189
 
 
6303ae6
c9d9189
 
 
 
 
6303ae6
 
c9d9189
 
 
 
 
6303ae6
 
c9d9189
6303ae6
 
 
 
 
c9d9189
 
6303ae6
 
 
 
c9d9189
6303ae6
c9d9189
6303ae6
c9d9189
 
 
 
 
 
 
 
 
6303ae6
 
c9d9189
 
6303ae6
c9d9189
 
 
 
6303ae6
 
c9d9189
6303ae6
c9d9189
6303ae6
 
 
c9d9189
 
 
6303ae6
c9d9189
6303ae6
c9d9189
6303ae6
c9d9189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6303ae6
 
 
c9d9189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93411b2
c9d9189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9d9189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6303ae6
 
 
 
 
 
 
c9d9189
6303ae6
 
 
f9a06ca
 
 
 
 
 
 
 
 
6303ae6
 
 
 
 
f9a06ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6303ae6
 
 
 
 
 
 
 
 
 
c9d9189
 
 
 
 
 
 
 
 
 
 
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9a06ca
 
 
 
 
 
 
 
6303ae6
 
 
357ee36
 
6303ae6
357ee36
 
 
 
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9a06ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6303ae6
f9a06ca
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9d9189
 
6303ae6
c9d9189
6303ae6
 
 
 
 
 
 
 
 
 
 
 
c9d9189
 
 
6303ae6
 
 
 
 
 
 
 
 
 
 
 
 
 
c9d9189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93411b2
c9d9189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93411b2
 
c9d9189
93411b2
 
c9d9189
 
 
 
 
 
 
 
 
 
 
 
93411b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9d9189
 
 
93411b2
 
c9d9189
93411b2
c9d9189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
"""Shared visual theme β€” the "Spectrum" design system.

Loads ``app/assets/design_system.css`` (the full token + component CSS from
the design file), injects it once per render, and provides helper functions
for emitting the correct HTML markup so the CSS classes actually match.

Key architecture: Streamlit generates its own HTML, so Spectrum's component
classes (.card, .screen-head, .verdict, .proposal-doc, etc.) only take effect
when we explicitly emit matching HTML via st.markdown(unsafe_allow_html=True).
Streamlit's functional widgets (buttons, file_uploader, text_input) are kept
for interactivity but restyled via the CSS widget-override section.
"""

from __future__ import annotations

from functools import lru_cache

import streamlit as st
import streamlit.components.v1 as components

from app.paths import resource_path


# Status-chip kinds β†’ CSS class (legacy, used by a few callers).
_CHIP_KINDS = {
    "ready": "ups-chip-ready",
    "info": "ups-chip-info",
    "missing": "ups-chip-missing",
    "neutral": "ups-chip-neutral",
}

# Per-step signature color: (H, C, H2) in oklch. Light default.
STEP_COLORS: dict[str, tuple[float, float, float]] = {
    # Aurora keeps ONE dominant violet, so the six steps sit inside a narrow
    # band: the room warms or cools very slightly as the user moves forward,
    # it never changes colour. At the "setup" values --accent resolves to
    # #8B5CF6 β€” the Aurora primary.
    "setup":        (293.5, 0.213, 304.0),
    "dossier":      (290.0, 0.213, 301.0),
    "screenshot":   (297.0, 0.207, 308.0),
    "confirmation": (287.0, 0.216, 299.0),
    "analysis":     (287.0, 0.216, 299.0),
    "proposal":     (300.0, 0.200, 310.0),
}
_DEFAULT_ACCENT = STEP_COLORS["setup"]

STEP_EYEBROWS = {
    "setup":      "Step 01 β€” Setup",
    "dossier":    "Step 02 β€” Dossier",
    "screenshot": "Step 03 β€” Job Screenshot",
    "analysis":   "Step 04 β€” Analysis",
    "proposal":   "Step 05 β€” Proposal",
}

_FONTS_LINK = (
    '<link rel="preconnect" href="https://fonts.googleapis.com">'
    '<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>'
    '<link href="https://fonts.googleapis.com/css2?'
    'family=Inter:wght@400;500;600&display=swap" rel="stylesheet">'
)


# Extra CSS layered on top of design_system.css to bridge Streamlit's DOM
# with the design's component classes.
_BRIDGE_CSS = """
<style>
/* ── Aurora Glass Β· Streamlit bridge ────────────────────────────────────
   Makes Streamlit's own widgets speak the Aurora design language. Every
   value here comes from app/assets/design_system.css tokens, so the two
   layers can never drift. Presentation only β€” no behaviour is changed. */

/* ── Global chrome ──────────────────────────────────────────────────── */
/* Streamlit's menu, deploy button and host toolbar are not part of this
   app. The header itself must stay: it holds the only control that reopens
   a collapsed sidebar, and Streamlit remembers "collapsed" across reloads,
   so hiding it lost the rail, Setup and Dark mode for good. It is
   see-through and click-through β€” only its own buttons take a click, so it
   never sits in the way of the top bar beneath it. */
#MainMenu, footer,
[data-testid="stMainMenu"],
[data-testid="stAppDeployButton"],
[data-testid="stToolbarActions"] { display: none !important; }
[data-testid="stHeader"] { background: transparent !important; }
[data-testid="stHeader"], [data-testid="stToolbar"] { pointer-events: none !important; }
[data-testid="stHeader"] button { pointer-events: auto !important; }
/* The Β» that reopens the rail and the Β« that closes it. Streamlit paints
   them a fixed grey that vanishes on the dark ground. */
[data-testid="stExpandSidebarButton"],
[data-testid="stExpandSidebarButton"] span,
[data-testid="stSidebarCollapseButton"] button,
[data-testid="stSidebarCollapseButton"] span { color: var(--text-muted) !important; }
[data-testid="stExpandSidebarButton"]:hover,
[data-testid="stExpandSidebarButton"]:hover span,
[data-testid="stSidebarCollapseButton"] button:hover,
[data-testid="stSidebarCollapseButton"] button:hover span { color: var(--text) !important; }
[data-testid="stAppViewContainer"] {
  background:
    radial-gradient(circle at 63% 18%, var(--aura-1), transparent 30%),
    radial-gradient(circle at 82% 42%, var(--aura-2), transparent 34%),
    radial-gradient(circle at 35% 72%, var(--aura-3), transparent 28%),
    var(--bg) !important;
  background-attachment: fixed !important;
  background-size: 150% 150%, 165% 165%, 140% 140%, auto !important;
  background-position: 24% 20%, 58% 42%, 30% 70%, 0 0 !important;
}
[data-testid="stMain"] { background: transparent !important; }
.block-container {
  padding: 32px 32px 80px !important;
  max-width: 960px !important;
}

/* ── All text follows the theme (critical for dark-mode contrast) ──────
   Streamlit paints text a fixed colour; on a dark ground that vanishes.
   Force every text surface onto the tokens so contrast is correct in
   BOTH themes. */
[data-testid="stAppViewContainer"],
[data-testid="stSidebar"],
.stApp, .stMarkdown, .stText,
[data-testid="stMarkdownContainer"],
[data-testid="stMarkdownContainer"] p,
[data-testid="stMarkdownContainer"] li,
[data-testid="stMarkdownContainer"] ul,
[data-testid="stMarkdownContainer"] ol,
[data-testid="stMarkdownContainer"] strong,
[data-testid="stMarkdownContainer"] em,
[data-testid="stMarkdownContainer"] span,
[data-testid="stMarkdownContainer"] td,
[data-testid="stMarkdownContainer"] th,
[data-testid="stHeadingWithActionElements"],
[data-testid="stWidgetLabel"],
[data-testid="stWidgetLabel"] p,
[data-testid="stWidgetLabel"] label,
label, p, li {
  color: var(--text) !important;
  font-family: var(--ff-body) !important;
}
[data-testid="stMarkdownContainer"] p,
[data-testid="stMarkdownContainer"] li { font-size: 14px !important; line-height: 1.5 !important; }
[data-testid="stCaptionContainer"],
[data-testid="stCaptionContainer"] p,
small, .stCaption {
  color: var(--text-muted) !important;
  font-size: 12px !important;
  line-height: 1.4 !important;
}
[data-testid="stWidgetLabel"] p, [data-testid="stWidgetLabel"] label {
  font-size: 13px !important; font-weight: 500 !important;
}
[data-testid="stMarkdownContainer"] code {
  background: var(--surface-2) !important;
  border: 1px solid var(--border-soft) !important;
  border-radius: var(--radius-xs) !important;
  color: var(--accent-light) !important;
  padding: 1px 6px !important;
  font-size: 12.5px !important;
}
[data-testid="stMetricValue"] {
  color: var(--text) !important;
  font-family: var(--ff-display) !important;
  font-size: 26px !important;
  font-weight: 600 !important;
  letter-spacing: -0.02em !important;
  font-variant-numeric: tabular-nums !important;
}
[data-testid="stMetricLabel"], [data-testid="stMetricLabel"] p {
  color: var(--text-muted) !important; font-size: 12px !important;
}

/* ── Visible focus on everything interactive (WCAG AA) ─────────────── */
button:focus-visible,
[role="button"]:focus-visible,
a:focus-visible,
input:focus-visible,
textarea:focus-visible,
select:focus-visible,
summary:focus-visible,
[data-baseweb="select"]:focus-within {
  outline: 2px solid var(--focus-ring) !important;
  outline-offset: 2px !important;
}

/* ── Select boxes and their menus ───────────────────────────────────── */
[data-baseweb="select"] > div {
  background: var(--surface) !important;
  border: 1px solid var(--input-border) !important;
  border-radius: var(--radius-input) !important;
  color: var(--text) !important;
  min-height: 42px !important;
  transition: border-color var(--t-fast) var(--ease), box-shadow var(--t-fast) var(--ease) !important;
}
[data-baseweb="select"] div, [data-baseweb="select"] span, [data-baseweb="select"] input {
  color: var(--text) !important;
}
[data-baseweb="select"] svg { color: var(--text-muted) !important; }
[data-baseweb="popover"], [data-baseweb="menu"], [role="listbox"] {
  background: var(--menu-bg) !important;
  backdrop-filter: blur(24px) !important;
  -webkit-backdrop-filter: blur(24px) !important;
  border: 1px solid var(--menu-border) !important;
  border-radius: var(--radius-btn) !important;
  box-shadow: var(--menu-shadow) !important;
}
[role="option"] { background: transparent !important; color: var(--text-muted) !important; font-size: 13.5px !important; }
[role="option"]:hover { background: var(--surface-hover) !important; color: var(--text) !important; }
[role="option"][aria-selected="true"] { background: var(--accent-soft) !important; color: var(--text) !important; }

/* ── Tooltips ───────────────────────────────────────────────────────────
   Every `help=` string lands here: the locked step rows, the settings
   button, the disabled Continue button, the dossier path field. Streamlit
   paints the tooltip on its own light surface and does not theme it, while
   the text rule above puts near-white type on top β€” so the help text was
   invisible in dark mode. Both surface and text are set here, and the inner
   markdown container is overridden explicitly because the global rule
   targets it by test id and would otherwise win. */
/* The surface. Painted on the two elements that own it, never on the ones
   in between. */
[data-testid="stTooltipContent"],
div[data-baseweb="tooltip"],
[role="tooltip"] {
  background: var(--menu-bg) !important;
  border: 1px solid var(--menu-border) !important;
  border-radius: var(--radius-input) !important;
  box-shadow: var(--menu-shadow) !important;
  color: var(--text) !important;
  font-family: var(--ff-body) !important;
  max-width: 320px !important;
}
[data-testid="stTooltipContent"] { padding: 10px 12px !important; }
/* When one is nested inside the other, only the inner one keeps the chrome,
   so the border and shadow are never drawn twice. */
div[data-baseweb="tooltip"]:has([data-testid="stTooltipContent"]),
[role="tooltip"]:has([data-testid="stTooltipContent"]) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
  padding: 0 !important;
}
/* Nothing inside may repaint the surface β€” baseweb's own wrappers are what
   put a white plate under near-white text. `code` restores its own fill
   below, because it comes after this. */
div[data-baseweb="tooltip"] *,
[role="tooltip"] *,
[data-testid="stTooltipContent"] * {
  background: transparent !important;
  background-color: transparent !important;
  border-color: transparent !important;
  box-shadow: none !important;
}
/* The text. The global "all text follows the theme" rule above targets
   [data-testid="stMarkdownContainer"] p by test id, so each of these is
   named explicitly to out-specify it. */
[data-testid="stTooltipContent"],
[data-testid="stTooltipContent"] *,
div[data-baseweb="tooltip"] *,
[role="tooltip"] *,
[data-testid="stTooltipContent"] [data-testid="stMarkdownContainer"],
[data-testid="stTooltipContent"] [data-testid="stMarkdownContainer"] p,
[data-testid="stTooltipContent"] [data-testid="stMarkdownContainer"] li,
[data-testid="stTooltipContent"] [data-testid="stMarkdownContainer"] strong,
[data-testid="stTooltipContent"] [data-testid="stMarkdownContainer"] code {
  color: var(--text) !important;
  -webkit-text-fill-color: var(--text) !important;
  font-size: 13px !important;
  line-height: 1.45 !important;
}
[data-testid="stTooltipContent"] [data-testid="stMarkdownContainer"] code {
  background: var(--surface-2) !important;
  background-color: var(--surface-2) !important;
  border: 1px solid var(--border-soft) !important;
}
/* The little "?" affordance beside a labelled widget. */
[data-testid="stTooltipHoverTarget"],
[data-testid="stTooltipIcon"] { color: var(--text-faint) !important; }
[data-testid="stTooltipHoverTarget"]:hover,
[data-testid="stTooltipIcon"]:hover { color: var(--text-muted) !important; }

/* ── Expander ───────────────────────────────────────────────────────── */
[data-testid="stExpander"] details {
  background: var(--card-grad) !important;
  border: 1px solid var(--border) !important;
  border-radius: var(--radius) !important;
}
[data-testid="stExpander"] summary,
[data-testid="stExpander"] summary span,
[data-testid="stExpander"] p { color: var(--text) !important; }

/* ── Radio / checkbox ───────────────────────────────────────────────── */
[data-baseweb="radio"] div, [data-testid="stCheckbox"] label, [data-testid="stRadio"] label {
  color: var(--text) !important;
}
[data-baseweb="radio"] [aria-checked="true"] div:first-child {
  border-color: var(--accent) !important; background: var(--accent) !important;
}

/* ── Sidebar ────────────────────────────────────────────────────────── */
section[data-testid="stSidebar"] {
  background: var(--sidebar-bg) !important;
  border-right: 1px solid var(--border-soft) !important;
  backdrop-filter: blur(20px) !important;
  -webkit-backdrop-filter: blur(20px) !important;
  min-width: 240px !important; max-width: 260px !important;
}
/* Collapsed, the rail gives its width back. Streamlit collapses it by
   zeroing these two; the clamp above would otherwise leave a blank column. */
section[data-testid="stSidebar"][aria-expanded="false"] {
  min-width: 0 !important; max-width: 0 !important;
}
section[data-testid="stSidebar"] .block-container { padding: 22px 16px 24px !important; }

/* ── Sidebar navigation β€” the step rail ─────────────────────────────── */
section[data-testid="stSidebar"] .stButton button {
  background: none !important;
  border: 1px solid transparent !important;
  border-radius: var(--radius-btn) !important;
  text-align: left !important;
  justify-content: flex-start !important;
  font-family: var(--ff-body) !important;
  font-size: 14px !important;
  font-weight: 500 !important;
  color: var(--text-muted) !important;
  padding: 0 13px !important;
  height: 44px !important;
  min-height: 44px !important;
  width: 100% !important;
  box-shadow: none !important;
  transition: background var(--t-base) var(--ease), color var(--t-base) var(--ease),
              border-color var(--t-base) var(--ease), transform var(--t-base) var(--ease) !important;
}
section[data-testid="stSidebar"] .stButton button:hover {
  background: var(--nav-hover) !important;
  color: var(--text) !important;
  transform: translateX(2px) !important;
}
section[data-testid="stSidebar"] .stButton button[kind="primary"] {
  background: linear-gradient(90deg, rgba(139, 92, 246, 0.25), rgba(139, 92, 246, 0.085)) !important;
  border: 1px solid rgba(167, 139, 250, 0.22) !important;
  color: var(--nav-active-text) !important;
  font-weight: 500 !important;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.06) !important;
  transform: none !important;
}
section[data-testid="stSidebar"] .stButton button[kind="secondary"],
section[data-testid="stSidebar"] [data-testid="stBaseButton-secondary"] {
  background: var(--surface) !important;
  border: 1px solid var(--border) !important;
  color: var(--text) !important;
  font-weight: 500 !important;
}
section[data-testid="stSidebar"] .stButton button[kind="secondary"]:hover,
section[data-testid="stSidebar"] [data-testid="stBaseButton-secondary"]:hover {
  background: var(--surface-hover) !important;
  border-color: var(--border-2) !important;
  color: var(--text) !important;
}
section[data-testid="stSidebar"] .stButton button:disabled {
  opacity: 0.45 !important;
  cursor: not-allowed !important;
  transform: none !important;
}

/* ── Main action buttons ────────────────────────────────────────────── */
.stButton button {
  font-family: var(--ff-body) !important;
  font-weight: 500 !important;
  font-size: 14px !important;
  height: 44px !important;
  border-radius: var(--radius-btn) !important;
  transition: transform var(--t-fast) var(--ease), box-shadow var(--t-fast) var(--ease),
              background var(--t-fast) var(--ease), border-color var(--t-fast) var(--ease) !important;
}
.stButton button[kind="primary"], [data-testid="stBaseButton-primary"] {
  color: var(--accent-fg) !important;
  border: none !important;
  background: var(--accent-grad) !important;
  box-shadow: 0 8px 24px var(--accent-glow) !important;
  padding: 0 18px !important;
}
.stButton button[kind="primary"]:hover, [data-testid="stBaseButton-primary"]:hover {
  transform: translateY(-1px) !important;
  box-shadow: 0 10px 28px var(--accent-glow) !important;
}
.stButton button[kind="primary"]:active, [data-testid="stBaseButton-primary"]:active {
  transform: scale(0.98) !important;
}
.stButton button[kind="secondary"],
[data-testid="stBaseButton-secondary"],
.stDownloadButton button {
  background: var(--surface) !important;
  color: var(--text) !important;
  border: 1px solid var(--border) !important;
  box-shadow: none !important;
}
.stButton button[kind="secondary"]:hover,
[data-testid="stBaseButton-secondary"]:hover,
.stDownloadButton button:hover {
  background: var(--surface-hover) !important;
  border-color: var(--border-2) !important;
  color: var(--text) !important;
  transform: translateY(-1px) !important;
}
.stButton button:active, .stDownloadButton button:active { transform: scale(0.98) !important; }
/* No button may lose its label colour on hover. Primary keeps its own. */
.stButton button:not([kind="primary"]):hover,
.stButton button:not([kind="primary"]):hover *,
[data-testid="stBaseButton-secondary"]:hover,
[data-testid="stBaseButton-secondary"]:hover *,
.stDownloadButton button:hover,
.stDownloadButton button:hover * { color: var(--text) !important; }
.stButton button:disabled, .stDownloadButton button:disabled {
  opacity: 0.45 !important; box-shadow: none !important; transform: none !important;
}

/* ── Inputs ─────────────────────────────────────────────────────────────
   The baseweb WRAPPER carries the background, so it must be targeted too
   or the field shows as a pale box on the dark ground. */
.stTextInput input, .stTextArea textarea, .stNumberInput input,
.stTextInput div[data-baseweb="input"],
.stTextInput div[data-baseweb="base-input"],
.stTextArea div[data-baseweb="textarea"],
.stNumberInput div[data-baseweb="input"],
.stNumberInput div[data-baseweb="base-input"] {
  background: var(--surface) !important;
  border-color: var(--input-border) !important;
  border-radius: var(--radius-input) !important;
  color: var(--text) !important;
  font-family: var(--ff-body) !important;
  font-size: 14px !important;
  -webkit-text-fill-color: var(--text) !important;
  transition: border-color var(--t-fast) var(--ease), box-shadow var(--t-fast) var(--ease) !important;
}
.stTextInput input, .stNumberInput input { min-height: 42px !important; }
.stTextInput input::placeholder, .stTextArea textarea::placeholder {
  color: var(--text-faint) !important; -webkit-text-fill-color: var(--text-faint) !important;
}
.stTextInput input:focus, .stTextArea textarea:focus,
.stTextInput div[data-baseweb="base-input"]:focus-within,
.stNumberInput div[data-baseweb="base-input"]:focus-within {
  border-color: var(--input-focus) !important;
  box-shadow: 0 0 0 3px var(--ring) !important;
}
.stTextInput button { background: transparent !important; color: var(--text-muted) !important; }
.stTextInput button:hover { color: var(--text) !important; }

/* ── File uploader β†’ glass dropzone ─────────────────────────────────── */
[data-testid="stFileUploaderDropzone"] {
  background: var(--dropzone-bg) !important;
  border: 1.5px dashed var(--dropzone-border) !important;
  border-radius: var(--radius) !important;
  transition: border-color var(--t-base) var(--ease), background var(--t-base) var(--ease),
              box-shadow var(--t-base) var(--ease) !important;
}
/* Drag-over / hover / keyboard focus all give the same unmistakable state. */
[data-testid="stFileUploaderDropzone"]:hover,
[data-testid="stFileUploaderDropzone"]:focus-within {
  border-color: var(--accent) !important;
  background: var(--dropzone-bg-hover) !important;
  box-shadow: 0 0 0 3px var(--ring) !important;
}
/* Nothing decorative may ever swallow a drop. */
[data-testid="stFileUploader"],
[data-testid="stFileUploader"] *,
[data-testid="stFileUploaderDropzone"],
[data-testid="stFileUploaderDropzone"] * { pointer-events: auto !important; }
[data-testid="stFileUploaderDropzone"],
[data-testid="stFileUploaderDropzone"] span,
[data-testid="stFileUploaderDropzone"] div,
[data-testid="stFileUploaderDropzoneInstructions"],
[data-testid="stFileUploaderDropzoneInstructions"] span,
[data-testid="stFileUploaderDropzoneInstructions"] div { color: var(--text) !important; }
[data-testid="stFileUploaderDropzoneInstructions"] small,
[data-testid="stFileUploader"] small { color: var(--text-muted) !important; }
[data-testid="stFileUploaderDropzone"] button {
  background: var(--surface-2) !important;
  color: var(--text) !important;
  border: 1px solid var(--border) !important;
  border-radius: var(--radius-btn) !important;
}
[data-testid="stFileUploaderDropzone"] svg { color: var(--text-muted) !important; }
[data-testid="stFileUploaderFile"], [data-testid="stFileUploaderFile"] *,
[data-testid="stFileUploaderFileName"] { color: var(--text) !important; }

/* ── Paste-screenshot component iframe ──────────────────────────────────
   Its inner document belongs to a third-party component, so it cannot be
   styled across the frame β€” shrink it to hug its button so no pale bar
   shows on the dark ground. */
iframe[title*="paste_button"], iframe[title*="streamlit_paste_button"] {
  background: transparent !important;
  color-scheme: light dark;
  width: 252px !important;
  max-width: 252px !important;
  border-radius: var(--radius-btn);
  overflow: hidden;
}
[data-testid="stCustomComponentV1"] { background: transparent !important; width: 252px !important; }

/* ── Bordered containers β†’ glass cards ──────────────────────────────── */
[data-testid="stVerticalBlock"][class*="st-key-ups_panel"] {
  background: var(--card-grad) !important;
  border: 1px solid var(--border) !important;
  border-radius: var(--radius) !important;
  box-shadow: var(--shadow), var(--inset-hi) !important;
  padding: 20px !important;
  transition: border-color var(--t-base) var(--ease), background var(--t-base) var(--ease) !important;
}
/* Border and surface only β€” never a lift, so a panel you are typing in
   does not move under the cursor. */
[data-testid="stVerticalBlock"][class*="st-key-ups_panel"]:hover {
  border-color: var(--border-2) !important;
  background: var(--card-grad-hi) !important;
}

/* ── Progress ───────────────────────────────────────────────────────── */
.stProgress > div > div > div {
  background: var(--surface-3) !important;
  border-radius: var(--radius-pill) !important;
}
.stProgress > div > div > div > div {
  background: linear-gradient(90deg, var(--accent), var(--accent-2)) !important;
  border-radius: var(--radius-pill) !important;
}

/* ── Headings ───────────────────────────────────────────────────────── */
h1, h2, h3 {
  font-family: var(--ff-display) !important;
  font-weight: 600 !important;
  letter-spacing: -0.025em !important;
  color: var(--text) !important;
}

/* ── Dividers ───────────────────────────────────────────────────────── */
hr { border-color: var(--border-soft) !important; margin: 16px 0 !important; }

/* ── Chips and micro-labels (emitted by theme.py) ───────────────────── */
.ups-chip {
  display: inline-flex; align-items: center;
  padding: 5px 12px; border-radius: var(--radius-pill);
  font-family: var(--ff-mono); font-size: 12px; font-weight: 500;
  letter-spacing: 0.02em; white-space: nowrap;
}
.ups-chip-ready   { background: var(--go-soft);     color: var(--go-ink);   border: 1px solid rgba(34, 197, 94, 0.28); }
.ups-chip-ready::before {
  content: ""; display: inline-block; width: 6px; height: 6px; border-radius: 50%;
  background: currentColor; margin-right: 7px; flex: none;
}
.ups-chip-info    { background: var(--accent-soft); color: var(--on-soft);  border: 1px solid var(--accent-line); }
.ups-chip-missing { background: var(--stop-soft);   color: var(--stop-ink); border: 1px solid rgba(239, 68, 68, 0.28); }
.ups-chip-neutral { background: var(--warn-soft);   color: var(--warn-ink); border: 1px solid rgba(245, 158, 11, 0.28); }
.ups-section {
  font-family: var(--ff-display) !important; font-size: 18px !important;
  font-weight: 600 !important; letter-spacing: -0.008em !important;
  line-height: 1.3 !important; text-transform: none !important;
  color: var(--text) !important; margin: 0 0 18px !important;
}
.ups-side-title {
  font-family: var(--ff-mono); font-size: 12px; font-weight: 500;
  letter-spacing: 0.14em; text-transform: uppercase;
  color: var(--text-faint); margin: 0 0 8px;
}

/* ── Toggle ─────────────────────────────────────────────────────────── */
.stToggle label, [data-testid="stWidgetLabel"] label {
  font-family: var(--ff-body) !important; font-size: 13px !important; color: var(--text-muted) !important;
}

/* ── Alerts β€” one design system, semantic tint kept ─────────────────── */
[data-testid="stAlert"] {
  background: var(--card-grad) !important;
  border: 1px solid var(--border) !important;
  border-radius: var(--radius) !important;
  box-shadow: var(--shadow-sm) !important;
  backdrop-filter: blur(20px) !important;
  -webkit-backdrop-filter: blur(20px) !important;
}
[data-testid="stAlert"] p, [data-testid="stAlert"] span, [data-testid="stAlert"] div {
  color: var(--text) !important;
}
[data-testid="stAlert"]:has([data-testid="stAlertContentSuccess"]) {
  border-color: rgba(34, 197, 94, 0.28) !important;
  background: linear-gradient(145deg, rgba(34, 197, 94, 0.10), rgba(34, 197, 94, 0.035)) !important;
}
[data-testid="stAlert"]:has([data-testid="stAlertContentWarning"]) {
  border-color: rgba(245, 158, 11, 0.28) !important;
  background: linear-gradient(145deg, rgba(245, 158, 11, 0.10), rgba(245, 158, 11, 0.035)) !important;
}
[data-testid="stAlert"]:has([data-testid="stAlertContentError"]) {
  border-color: rgba(239, 68, 68, 0.28) !important;
  background: linear-gradient(145deg, rgba(239, 68, 68, 0.10), rgba(239, 68, 68, 0.035)) !important;
}
[data-testid="stAlert"]:has([data-testid="stAlertContentInfo"]) {
  border-color: var(--accent-line) !important;
  background: linear-gradient(145deg, rgba(139, 92, 246, 0.10), rgba(139, 92, 246, 0.035)) !important;
}

/* ── Tabs ───────────────────────────────────────────────────────────── */
.stTabs [aria-selected="true"] {
  color: var(--accent-light) !important;
  border-bottom-color: var(--accent) !important;
}

/* ── Spinner ────────────────────────────────────────────────────────── */
[data-testid="stSpinner"] i, .stSpinner > div { border-top-color: var(--accent) !important; }
[data-testid="stSpinner"] p { color: var(--text-muted) !important; }

/* ── Artboard parity ────────────────────────────────────────────────────
   Pulls each Streamlit control onto the exact geometry of its counterpart on
   the design canvas: same height, radius, stroke, fill and glow. Controls
   stay controls β€” this is geometry and fill only. Nothing here puts a
   containing-block property (transform / filter / backdrop-filter / contain)
   on an ancestor of the file uploader. */

/* The canvas stage: 32px page padding on a column the width of a 1440 shell
   minus its 240px rail. */
.block-container { padding: 24px 32px 80px !important; max-width: 1120px !important; }

/* Panels β€” st.container(border=True) is the canvas's .panel.glass. */
[data-testid="stVerticalBlock"][class*="st-key-ups_panel"] { padding: 24px !important; }

/* Primary action = .cta β€” 44px, 10px radius, violet gradient, violet glow. */
.stButton button[kind="primary"],
[data-testid="stBaseButton-primary"] {
  height: 44px !important; min-height: 44px !important;
  padding: 0 20px !important;
  border-radius: var(--radius-input) !important;
  font-weight: 600 !important;
  box-shadow: var(--gl-glow), inset 0 1px 0 rgba(255, 255, 255, 0.24) !important;
}
.stButton button[kind="primary"]:hover,
[data-testid="stBaseButton-primary"]:hover {
  transform: translateY(-2px) !important;
  filter: brightness(1.08) !important;
  box-shadow: 0 0 28px var(--accent-glow), 0 10px 26px rgba(0, 0, 0, 0.40),
              inset 0 1px 0 rgba(255, 255, 255, 0.26) !important;
}

/* Secondary action = .btn β€” glass fill, canvas stroke, inner highlight. */
.stButton button[kind="secondary"],
[data-testid="stBaseButton-secondary"],
.stDownloadButton button {
  height: 44px !important; min-height: 44px !important;
  padding: 0 18px !important;
  border-radius: var(--radius-input) !important;
  background: var(--gl-glass) !important;
  border: 1px solid var(--gl-stroke) !important;
  box-shadow: var(--gl-inner) !important;
  font-weight: 500 !important;
}
.stButton button[kind="secondary"]:hover,
[data-testid="stBaseButton-secondary"]:hover,
.stDownloadButton button:hover {
  background: var(--gl-glass-hi) !important;
  border-color: var(--gl-stroke) !important;
  transform: translateY(-1px) !important;
}

/* Text entry = .field β€” 44px, 16px radius, glass-lo, violet focus + glow. */
.stTextInput div[data-baseweb="base-input"],
.stTextInput div[data-baseweb="input"],
.stNumberInput div[data-baseweb="base-input"],
.stNumberInput div[data-baseweb="input"],
.stTextArea div[data-baseweb="base-input"],
.stTextArea div[data-baseweb="textarea"],
.stTextArea textarea,
div[data-baseweb="select"] > div {
  background: var(--gl-glass-lo) !important;
  border-color: var(--gl-stroke-soft) !important;
  border-radius: var(--radius) !important;
}
.stTextInput input, .stNumberInput input {
  height: 42px !important; min-height: 42px !important;
  background: transparent !important;
}
div[data-baseweb="select"] > div { min-height: 44px !important; }
.stTextInput div[data-baseweb="base-input"]:hover,
.stNumberInput div[data-baseweb="base-input"]:hover,
div[data-baseweb="select"] > div:hover { background: var(--gl-glass-hi) !important; }
.stTextInput div[data-baseweb="base-input"]:focus-within,
.stNumberInput div[data-baseweb="base-input"]:focus-within,
.stTextArea div[data-baseweb="base-input"]:focus-within,
div[data-baseweb="select"] > div:focus-within {
  border-color: oklch(0.627 var(--accent-c) var(--accent-h) / 0.5) !important;
  box-shadow: var(--gl-glow) !important;
  background: var(--gl-glass) !important;
}

/* Tabs = .seg β€” a padded track with a lit pill, not an underline. */
.stTabs [data-baseweb="tab-list"] {
  display: inline-flex !important; gap: 3px !important; padding: 4px !important;
  border-radius: var(--radius-input) !important;
  background: var(--gl-glass-lo) !important;
  border: 1px solid var(--gl-stroke-soft) !important;
  border-bottom: 1px solid var(--gl-stroke-soft) !important;
}
.stTabs [data-baseweb="tab"] {
  height: 32px !important; padding: 0 14px !important;
  border-radius: 7px !important; border: none !important;
  font-size: 13px !important; font-weight: 500 !important;
  color: var(--text-muted) !important;
  transition: background var(--t-fast) var(--ease), color var(--t-fast) var(--ease) !important;
}
.stTabs [data-baseweb="tab"]:hover { background: var(--gl-glass-hi) !important; color: var(--text) !important; }
.stTabs [aria-selected="true"] {
  background: var(--gl-glass-hi) !important;
  color: var(--text) !important;
  box-shadow: var(--gl-inner) !important;
  border-bottom-color: transparent !important;
}
.stTabs [data-baseweb="tab-highlight"], .stTabs [data-baseweb="tab-border"] { display: none !important; }

/* Progress = .meter β€” 6px track, violet gradient fill, violet glow. */
.stProgress > div > div > div {
  height: 6px !important; border-radius: 3px !important;
  background: var(--gl-track) !important;
}
.stProgress > div > div > div > div { border-radius: 3px !important; box-shadow: var(--gl-glow) !important; }

/* Drop target = .dz β€” the canvas radius and padding. Fill and stroke keep the
   stronger values the drop target needs to stay unmistakable; the canvas's
   own 1px hairline disappears on this ground. */
[data-testid="stFileUploaderDropzone"] { border-radius: var(--radius) !important; padding: 26px !important; }

/* ── The rail's rows = .nav ──────────────────────────────────────────────
   Each row is still a real st.button. Streamlit stamps the element key onto
   the wrapper as `st-key-<key>`, which is what lets each step carry its own
   icon: the SVG rides as a mask so it takes the row's colour and changes with
   its state. `type="primary"` is the current step, `disabled` is a locked one. */
/* Both kinds are named so these out-rank the generic sidebar button rules
   above, which paint a secondary button as a filled surface β€” a nav row is
   transparent until you are on it or over it. */
section[data-testid="stSidebar"] [class*="st-key-nav_btn_"] .stButton button,
section[data-testid="stSidebar"] [class*="st-key-nav_btn_"] .stButton button[kind="secondary"],
section[data-testid="stSidebar"] [class*="st-key-nav_btn_"] [data-testid="stBaseButton-secondary"] {
  background: none !important;
  border: 1px solid transparent !important;
  border-radius: var(--radius-input) !important;
  height: 44px !important; min-height: 44px !important;
  padding: 0 12px !important;
  gap: 12px !important;
  justify-content: flex-start !important;
  color: var(--text-muted) !important;
  font-size: 14px !important; font-weight: 500 !important;
  box-shadow: none !important;
  transform: none !important;
}
section[data-testid="stSidebar"] [class*="st-key-nav_btn_"] .stButton button::before {
  content: ""; flex: none; width: 18px; height: 18px;
  background: currentColor;
  -webkit-mask: var(--nav-ico) center / 18px 18px no-repeat;
  mask: var(--nav-ico) center / 18px 18px no-repeat;
  transition: background var(--t-fast) var(--ease);
}
section[data-testid="stSidebar"] [class*="st-key-nav_btn_"] .stButton button:hover,
section[data-testid="stSidebar"] [class*="st-key-nav_btn_"] .stButton button[kind="secondary"]:hover {
  background: var(--gl-glass-hi) !important;
  color: var(--text) !important;
  transform: none !important;
}
section[data-testid="stSidebar"] [class*="st-key-nav_btn_"] .stButton button[kind="primary"] {
  background: var(--gl-glass) !important;
  border-color: oklch(0.627 var(--accent-c) var(--accent-h) / 0.45) !important;
  color: var(--text) !important;
  box-shadow: var(--gl-glow), var(--gl-inner) !important;
}
section[data-testid="stSidebar"] [class*="st-key-nav_btn_"] .stButton button[kind="primary"]::before {
  background: var(--accent) !important;
}
/* the chevron that marks the row you are on */
section[data-testid="stSidebar"] [class*="st-key-nav_btn_"] .stButton button[kind="primary"]::after {
  content: ""; margin-left: auto; flex: none; width: 14px; height: 14px; opacity: 0.5;
  background: currentColor;
  -webkit-mask: var(--ico-arrow) center / 14px 14px no-repeat;
  mask: var(--ico-arrow) center / 14px 14px no-repeat;
}
section[data-testid="stSidebar"] [class*="st-key-nav_btn_"] .stButton button:disabled {
  opacity: 0.4 !important; background: none !important; border-color: transparent !important;
}

/* ── Motion ─────────────────────────────────────────────────────────────
   What makes this feel alive: light that moves slowly behind the glass, a
   specular pass across the one primary action, the fit score flowing while
   it is on screen, and the step rail drawing itself in. Nothing here is
   position/z-index/backdrop-filter on an interactive element, so none of it
   can affect clicking, typing or dropping a file. */
@media (prefers-reduced-motion: no-preference) {
  @keyframes auroraDrift {
    0%   { background-position: 20% 14%, 62% 38%, 26% 74%, 0 0; }
    50%  { background-position: 38% 30%, 46% 54%, 44% 58%, 0 0; }
    100% { background-position: 20% 14%, 62% 38%, 26% 74%, 0 0; }
  }
  /* Dust in the light. One repeating tile scrolled by exactly its own
     height, so the loop has no seam. Fixed, click-through, and painted
     under the grain β€” it can never take a click or swallow a dropped file. */
  @keyframes upsMotes  { from { background-position: 0 0; }
                         to   { background-position: 0 -480px; } }
  @keyframes upsGlint  { 0%   { transform: translateX(-190%) skewX(-16deg); }
                         38%  { transform: translateX(430%)  skewX(-16deg); }
                         100% { transform: translateX(430%)  skewX(-16deg); } }
  @keyframes upsSheen  { 0%   { background-position: -45% 0, 0 0; }
                         58%  { background-position: 155% 0, 0 0; }
                         100% { background-position: 155% 0, 0 0; } }
  @keyframes upsBarLit { 0%, 100% { opacity: 0.65; }
                         50%      { opacity: 1; } }
  @keyframes stRise    { from { opacity: 0; transform: translateY(10px); } }
  @keyframes stSweep   { 0%   { transform: translateX(-130%) skewX(-14deg); }
                         100% { transform: translateX(260%)  skewX(-14deg); } }
  @keyframes stFlow    { 0%   { background-position: 0% 50%; }
                         100% { background-position: 200% 50%; } }
  @keyframes stGrow    { from { transform: scaleX(0); } }
  @keyframes stBarDraw { from { transform: scaleY(0); } }
  @keyframes stPulse   { 0%, 100% { opacity: 0.45; transform: scale(1); }
                         50%      { opacity: 1;    transform: scale(1.3); } }

  /* The room breathes. One slow loop, behind everything, click-through by
     nature because it is a background, not an element. */
  [data-testid="stAppViewContainer"] {
    animation: auroraDrift 34s ease-in-out infinite !important;
  }

  /* Panels arrive. Delays stay short so a stalled animation can never leave
     a card stranded at opacity 0. */
  [data-testid="stVerticalBlock"][class*="st-key-ups_panel"],
  [data-testid="stAlert"],
  [data-testid="stExpander"],
  [data-testid="stMetric"] { animation: stRise 420ms var(--ease) backwards !important; }
  [data-testid="stVerticalBlock"][class*="st-key-ups_panel"]:nth-of-type(2) { animation-delay: 70ms !important; }
  [data-testid="stVerticalBlock"][class*="st-key-ups_panel"]:nth-of-type(3) { animation-delay: 130ms !important; }
  /* A transformed element is a containing block for fixed descendants, even
     for the 420ms an entrance lasts. The card holding a file uploader fades
     only β€” never transforms β€” so a drop can never be affected by chrome. */
  @keyframes stFade { from { opacity: 0; } }
  [data-testid="stVerticalBlock"][class*="st-key-ups_panel"]:has([data-testid="stFileUploader"]) {
    animation: stFade 420ms var(--ease) backwards !important;
  }

  /* One pass of light across the primary action when the cursor arrives. */
  .stButton button[kind="primary"],
  [data-testid="stBaseButton-primary"] { position: relative !important; overflow: hidden !important; }
  .stButton button[kind="primary"]::after,
  [data-testid="stBaseButton-primary"]::after {
    content: ""; position: absolute; top: 0; bottom: 0; left: 0; width: 45%;
    pointer-events: none;
    background: linear-gradient(100deg, transparent, rgba(255, 255, 255, 0.22) 50%, transparent);
    transform: translateX(-130%) skewX(-14deg);
  }
  .stButton button[kind="primary"]:hover::after,
  [data-testid="stBaseButton-primary"]:hover::after { animation: stSweep 820ms var(--ease); }

  /* The fit score fills in, then keeps flowing while it is on screen β€” the
     one number this product is built to produce. No fill-mode, so if the
     animation never runs the bar still rests at its correct width. */
  .stProgress > div > div > div { overflow: hidden !important; }
  .stProgress > div > div > div > div {
    background: linear-gradient(90deg, var(--accent), var(--accent-2), var(--accent)) !important;
    background-size: 200% 100% !important;
    transform-origin: left center;
    animation: stFlow 3.4s linear infinite, stGrow 900ms var(--ease) !important;
  }

  /* The rail's own ::before carries the step icon (see "Artboard parity"),
     so the old accent bar that used to live here is gone: it claimed the same
     pseudo-element and squeezed the icon to 2px. The active row is already
     unmistakable without it β€” glass fill, violet border, violet icon, glow
     and a chevron. */

  /* Dust drifting up through the room, on every screen. */
  body::before {
    content: ""; position: fixed; inset: 0; z-index: 9998;
    pointer-events: none;
    background-image:
      radial-gradient(circle 1.6px at 11% 14%, var(--mote), transparent),
      radial-gradient(circle 1.3px at 38% 61%, var(--mote), transparent),
      radial-gradient(circle 1.8px at 62% 26%, var(--mote), transparent),
      radial-gradient(circle 1.2px at 82% 78%, var(--mote), transparent),
      radial-gradient(circle 1.5px at 24% 88%, var(--mote), transparent),
      radial-gradient(circle 1.3px at 91% 42%, var(--mote), transparent);
    background-size: 380px 480px;
    background-repeat: repeat;
    animation: upsMotes 26s linear infinite;
    opacity: 0.7;
  }

  /* Every panel catches a slow sheen. Paint only: no position, no z-index,
     no filter β€” the card holding the file uploader is styled by exactly the
     same rule and stays a plain, undisturbed drop target. */
  [data-testid="stVerticalBlock"][class*="st-key-ups_panel"] {
    background-image:
      linear-gradient(100deg, transparent 36%, rgba(255, 255, 255, 0.055) 50%, transparent 64%),
      var(--card-grad) !important;
    background-size: 44% 100%, 100% 100% !important;
    background-repeat: no-repeat, no-repeat !important;
    background-position: -45% 0, 0 0 !important;
    animation: stRise 420ms var(--ease) backwards,
               upsSheen 11s var(--ease) 700ms infinite !important;
  }
  /* The hover rule above is a `background` shorthand and outranks the layered
     background this sheen needs, so the hover state restates both layers. */
  [data-testid="stVerticalBlock"][class*="st-key-ups_panel"]:hover {
    background-image:
      linear-gradient(100deg, transparent 36%, rgba(255, 255, 255, 0.055) 50%, transparent 64%),
      var(--card-grad-hi) !important;
    background-size: 44% 100%, 100% 100% !important;
    background-repeat: no-repeat, no-repeat !important;
  }
  [data-testid="stVerticalBlock"][class*="st-key-ups_panel"]:nth-of-type(2) { animation-delay: 70ms, 3.4s !important; }
  [data-testid="stVerticalBlock"][class*="st-key-ups_panel"]:nth-of-type(3) { animation-delay: 130ms, 6.1s !important; }
  [data-testid="stVerticalBlock"][class*="st-key-ups_panel"]:has([data-testid="stFileUploader"]) {
    animation: stFade 420ms var(--ease) backwards,
               upsSheen 11s var(--ease) 900ms infinite !important;
  }

  /* The primary action is never asleep: a glint crosses it on a slow loop,
     and the hover sweep above still fires on top of it. */
  .stButton button[kind="primary"]::before,
  [data-testid="stBaseButton-primary"]::before {
    content: ""; position: absolute; top: -25%; bottom: -25%; left: 0; width: 32%;
    pointer-events: none;
    background: linear-gradient(100deg, transparent, rgba(255, 255, 255, 0.30), transparent);
    transform: translateX(-190%) skewX(-16deg);
    animation: upsGlint 6.4s var(--ease) infinite;
  }

  /* Ready means ready. */
  .ups-chip-ready::before { animation: stPulse 3s var(--ease) infinite; }

  /* Waiting on the model should look expensive, not broken. */
  [data-testid="stSpinner"] i, [data-testid="stSpinner"] svg,
  .stSpinner i, .stSpinner svg {
    filter: drop-shadow(0 0 8px var(--accent-glow)) !important;
  }
}

/* ── The rail wins its own pseudo-elements ───────────────────────────────
   The main area decorates a primary button with ::before (the looping glint)
   and ::after (the hover sweep). Those selectors are not area-scoped, so on
   the rail β€” where the current step is also a primary button β€” they were
   landing on the two pseudo-elements the nav row uses for its icon and its
   chevron. Restated here, last, so the rail keeps them. */
section[data-testid="stSidebar"] [class*="st-key-nav_btn_"] .stButton button::before {
  position: static !important;
  top: auto !important; bottom: auto !important; left: auto !important;
  width: 18px !important; height: 18px !important;
  transform: none !important; animation: none !important;
  background: currentColor !important;
  -webkit-mask: var(--nav-ico) center / 18px 18px no-repeat !important;
  mask: var(--nav-ico) center / 18px 18px no-repeat !important;
}
section[data-testid="stSidebar"] [class*="st-key-nav_btn_"] .stButton button[kind="primary"]::before {
  background: var(--accent) !important;
}
section[data-testid="stSidebar"] [class*="st-key-nav_btn_"] .stButton button::after {
  content: none !important;
}
section[data-testid="stSidebar"] [class*="st-key-nav_btn_"] .stButton button[kind="primary"]::after {
  content: "" !important;
  position: static !important; margin-left: auto !important;
  width: 14px !important; height: 14px !important; opacity: 0.5 !important;
  transform: none !important; animation: none !important;
  background: currentColor !important;
  -webkit-mask: var(--ico-arrow) center / 14px 14px no-repeat !important;
  mask: var(--ico-arrow) center / 14px 14px no-repeat !important;
}

/* ── Motion respects the user's setting ─────────────────────────────── */
@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after {
    animation-duration: 0.001ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.001ms !important;
  }
}
</style>
"""


@lru_cache(maxsize=1)
def _design_css() -> str:
    """Read the Spectrum design system CSS once (cached), stripping stray style tags."""
    try:
        path = resource_path("app", "assets", "design_system.css")
        css = path.read_text(encoding="utf-8")
    except Exception:
        return ""
    return css.replace("</style>", "").replace("<style>", "")


# Which canvas icon marks each step in the rail. Keys match main.py's STEPS.
_NAV_ICONS = {
    "setup": "key",
    "dossier": "folder",
    "screenshot": "image",
    "confirmation": "edit",
    "analysis": "target",
    "proposal": "doc",
}


def _mask_url(icon_name: str) -> str:
    """One icon as a CSS mask URL.

    A mask takes its colour from whatever paints through it, so an icon set
    this way follows the row's own colour into every state β€” muted when
    idle, violet on the step you are on, dimmed when the step is locked.
    """
    from urllib.parse import quote

    from app.ui.icons import ICONS

    svg = ICONS.get(icon_name, "")
    if not svg:
        return "none"
    # A mask needs an opaque paint; currentColor would resolve to nothing here.
    svg = svg.replace('stroke="currentColor"', 'stroke="#000"')
    svg = svg.replace('fill="currentColor"', 'fill="#000"')
    if "xmlns=" not in svg:
        svg = svg.replace("<svg ", '<svg xmlns="http://www.w3.org/2000/svg" ', 1)
    return 'url("data:image/svg+xml,%s")' % quote(svg, safe="")


@lru_cache(maxsize=1)
def _nav_icon_css() -> str:
    """Per-step icon variables for the rail, plus the current-row chevron."""
    rows = "".join(
        'section[data-testid="stSidebar"] [class*="st-key-nav_btn_%s"] '
        "{ --nav-ico: %s; }\n" % (key, _mask_url(name))
        for key, name in _NAV_ICONS.items()
    )
    return "<style>\n%ssection[data-testid=\"stSidebar\"] { --ico-arrow: %s; }\n</style>" % (
        rows,
        _mask_url("arrow"),
    )


def inject_css() -> None:
    """Inject fonts + the Spectrum design system + Streamlit bridge CSS."""
    st.markdown(_FONTS_LINK, unsafe_allow_html=True)
    css = _design_css()
    if css:
        st.markdown(f"<style>{css}</style>", unsafe_allow_html=True)
    st.markdown(_BRIDGE_CSS, unsafe_allow_html=True)
    st.markdown(_nav_icon_css(), unsafe_allow_html=True)


def apply_step_accent(step_key: str, *, dark: bool = False) -> None:
    """Re-tint the whole screen to the current step's signature hue + theme.

    The design tokens live under ``[data-theme]`` on the parent ``<html>``, so
    this bridges from the component iframe to set it. It is hardened against the
    two things that made dark mode feel flaky: the parent DOM not being ready
    when the iframe first runs (so it retries briefly), and a write throwing in
    some embedding contexts (so it is wrapped in try/catch). It also sets
    ``color-scheme`` so native widgets (uploader, inputs) adopt the dark look.
    """
    h, c, h2 = STEP_COLORS.get(step_key, _DEFAULT_ACCENT)
    theme_val = "dark" if dark else "light"
    components.html(
        f"""<script>
        (function(){{
          var theme = '{theme_val}';
          function apply(){{
            try {{
              var r = window.parent.document.documentElement;
              if (!r) return false;
              r.setAttribute('data-theme', theme);
              r.style.setProperty('color-scheme', theme);
              r.style.setProperty('--accent-h', '{h}');
              r.style.setProperty('--accent-c', '{c}');
              r.style.setProperty('--accent2-h', '{h2}');
              try {{ window.parent.document.body.style.colorScheme = theme; }} catch (e) {{}}
              return true;
            }} catch (e) {{ return false; }}
          }}
          if (!apply()) {{
            // Parent not ready yet β€” retry a few times, then give up quietly.
            var n = 0;
            var t = setInterval(function(){{
              if (apply() || ++n > 20) clearInterval(t);
            }}, 50);
          }}
        }})();
        </script>""",
        height=0,
    )


# ── Screen header ──────────────────────────────────────────────────────────


def screen_head(step_key: str, title: str, subtitle: str) -> None:
    """Render the screen's title and standfirst, as on the design canvas.

    The artboards put the step indicator in the top bar rather than above the
    headline, so this no longer emits the eyebrow pill β€” ``top_bar`` carries
    the breadcrumb, the segmented rail and "Step N of M". ``step_key`` stays in
    the signature (every screen passes it) and still selects the eyebrow text
    for callers that want it via :data:`STEP_EYEBROWS`.

    ``subtitle`` is trusted markup written in the screen modules β€” it carries
    <b> emphasis. Never pass model output or file contents through it.
    """
    st.markdown(
        f"""<div class="screen-head">
          <h1 class="screen-title">{title}</h1>
          <p class="screen-sub">{subtitle}</p>
        </div>""",
        unsafe_allow_html=True,
    )


# ── Verdict banner ─────────────────────────────────────────────────────────

_VERDICT_TONE = {
    "Apply Confidently":  ("go",   "Apply confidently"),
    "Proceed With Caution": ("warn", "Proceed with caution"),
    "Do Not Proceed":     ("stop",  "Do not proceed"),
}

def verdict_banner(beginner_result: str, headline: str, body: str) -> None:
    """Render the full-bleed coloured verdict banner from the prototype."""
    tone, badge_label = _VERDICT_TONE.get(beginner_result, ("warn", beginner_result))
    st.markdown(
        f"""<div class="verdict {tone}">
          <div>
            <span class="verdict-badge">
              <span class="dot"></span>{badge_label}
            </span>
            <h2>{headline}</h2>
            <p>{body}</p>
          </div>
        </div>""",
        unsafe_allow_html=True,
    )


# ── Proposal document ──────────────────────────────────────────────────────


def _proposal_doc_html(text: str, word_count: int, file_count: int = 0) -> str:
    """Build the proposal card HTML as a single line (see :func:`proposal_doc`).

    Returned as one line with no leading indentation and no whitespace-only
    gaps so Streamlit's markdown parser renders it as pure HTML β€” a blank line
    (e.g. when ``grounded`` is empty) would otherwise terminate the HTML block
    and turn the trailing ``</div>`` into a literal code block.
    """
    import html as _html
    import re as _re

    from app.services.proposal_generator import strip_stray_html

    # 1. Strip any stray HTML tags the model may have emitted (e.g. a trailing
    #    </div>) so leaked markup never shows as text. Only real layout tags
    #    go: code such as "<Suspense>" or "Map<K, V>" is content, and the
    #    escaping below shows it as written.
    text = strip_stray_html(text or "")

    # 2. Put each "Step N:" / "Step N -" marker on its own paragraph so numbered
    #    steps always render on separate lines. We ONLY split on the explicit
    #    "Step N" marker β€” never on bare numbers like "Day 2" or "$2.5".
    text = _re.sub(r"\s*(?<!\n)(?<!^)(Step\s+\d+\s*[:\-β€”])", r"\n\n\1", text)

    # Split on double newlines to get paragraphs.
    paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
    if not paragraphs:
        paragraphs = [text.strip()]

    # HTML-escape every paragraph (defence-in-depth) so anything tag-like that
    # survived shows as literal text rather than rendering. Single newlines
    # within a paragraph become <br> for readable line breaks.
    def _para_html(p: str) -> str:
        escaped = _html.escape(p)
        escaped = escaped.replace("\n", "<br>")
        return f"<p>{escaped}</p>"

    paras_html = "".join(_para_html(p) for p in paragraphs)
    grounded = (
        f'<div class="evidence-note">'
        f'Grounded in {file_count} file{"s" if file_count != 1 else ""} from your dossier'
        f"</div>"
        if file_count
        else ""
    )
    wc_label = f"{word_count} words" if word_count else ""
    # Build as ONE line with no leading indentation and no whitespace-only
    # gaps. Streamlit runs this through a markdown parser: a blank/whitespace
    # line (e.g. when ``grounded`` is empty) would terminate the HTML block and
    # the next indented ``</div>`` would render as a literal code block. Keeping
    # it single-line avoids that entirely.
    return (
        f'<div class="doc-toolbar">'
        f'<span class="wordcount">{wc_label}</span>'
        f'<div class="toolbar-spacer"></div>'
        f"</div>"
        f'<div class="proposal-doc">{paras_html}{grounded}</div>'
    )


def proposal_doc(text: str, word_count: int, file_count: int = 0) -> None:
    """Render the styled proposal document card from the prototype."""
    st.markdown(
        _proposal_doc_html(text, word_count, file_count),
        unsafe_allow_html=True,
    )


# ── Legacy helpers (kept for backward compat with existing screen code) ────


def status_chip(label: str, kind: str = "neutral") -> str:
    css_class = _CHIP_KINDS.get(kind, _CHIP_KINDS["neutral"])
    return f'<span class="ups-chip {css_class}">{label}</span>'


def render_app_header(
    title: str,
    subtitle: str,
    *,
    chip_label: str | None = None,
    chip_kind: str = "neutral",
    step_label: str | None = None,
) -> None:
    """Minimal top-of-page header (app title line only β€” screens use screen_head)."""
    right_bits = []
    if step_label:
        right_bits.append(
            f'<span style="font-family:var(--ff-mono);font-size:12px;'
            f'letter-spacing:.14em;text-transform:uppercase;color:var(--accent-light);'
            f'border:1px solid var(--accent-line);background:var(--accent-soft);'
            f'padding:5px 12px;border-radius:999px;">{step_label}</span>'
        )
    if chip_label:
        right_bits.append(status_chip(chip_label, chip_kind))
    right_html = (
        '<div style="display:flex;gap:.5rem;align-items:center;flex-wrap:wrap">'
        + "".join(right_bits) + "</div>"
        if right_bits else ""
    )
    st.markdown(
        f"""<div style="display:flex;align-items:flex-start;justify-content:space-between;
          gap:1rem;flex-wrap:wrap;margin-bottom:.3rem;">
          <div>
            <p style="font-family:var(--ff-display);font-size:22px;font-weight:600;
              color:var(--text);margin:0;letter-spacing:-.025em;">{title}</p>
            <p style="color:var(--text-muted);font-size:13px;line-height:1.4;margin:.35rem 0 0;">{subtitle}</p>
          </div>
          {right_html}
        </div>""",
        unsafe_allow_html=True,
    )
    st.divider()


def section_label(text: str) -> None:
    st.markdown(f'<p class="ups-section">{text}</p>', unsafe_allow_html=True)


def sidebar_title(text: str) -> None:
    st.markdown(f'<p class="ups-side-title">{text}</p>', unsafe_allow_html=True)


# ══════════════════════════════════════════════════════════════════════════
# Aurora components
#
# One Python helper per component on the design canvas, emitting exactly the
# markup the artboards use (classes defined under "Aurora components" in
# design_system.css). Everything is escaped on the way in β€” these render app
# data, and none of them accept markup from a model or a file.
#
# Every helper here is presentational. None of them wrap, replace or stand in
# for a Streamlit control: real controls stay real controls and are matched to
# this same language by the widget layer in _BRIDGE_CSS.
# ══════════════════════════════════════════════════════════════════════════

import html as _html_mod

from app.ui.icons import ICONS, icon  # noqa: F401  (re-exported for screens)


def _e(value: object) -> str:
    """Escape anything on its way into markup."""
    return _html_mod.escape("" if value is None else str(value))


def _ico(name: str | None, size: int | None = None) -> str:
    return icon(name, size=size) if name else ""


# ── chrome ────────────────────────────────────────────────────────────────


def top_bar(
    *,
    crumb_a: str,
    crumb_b: str,
    step_index: int | None,
    step_total: int,
    right_html: str = "",
) -> None:
    """The artboard's top bar: breadcrumb, segmented step rail, step caption.

    ``step_index`` is 1-based; ``None`` draws the rail with nothing lit (used
    when the current screen is not one of the numbered steps).
    """
    now = step_index or 0
    segs = "".join(
        f'<span class="ups-seg-i {"is-done" if i < now - 1 else "is-now" if i == now - 1 else ""}"></span>'
        for i in range(step_total)
    )
    cap = (
        f'<span class="ups-cap">Step {now} of {step_total}</span>'
        if step_index
        else ""
    )
    st.markdown(
        f'<div class="ups-top">'
        f'<span class="ups-crumb">{_e(crumb_a)} <b>/ {_e(crumb_b)}</b></span>'
        f'<span class="ups-steps">{segs}</span>'
        f"{cap}"
        f'<span class="ups-sp"></span>'
        f"{right_html}"
        f"</div>",
        unsafe_allow_html=True,
    )


def sidebar_brand(title: str, tagline: str = "") -> None:
    """Brand lockup at the head of the rail: mark, wordmark, and the tagline.

    The canvas puts a short tracked descriptor under the wordmark. This app's
    descriptor is a real two-sentence tagline, so it is set as wrapping copy
    below the lockup rather than squeezed onto one tracked line β€” the words
    are the product's own and none of them are dropped.
    """
    tag_html = (
        f'<p class="ups-brand-tag">{_e(tagline)}</p>' if tagline else ""
    )
    st.markdown(
        f'<div class="ups-brand">'
        f'<span class="ups-brand-mark">{_ico("compass")}</span>'
        f'<span class="ups-brand-t">{_e(title)}</span>'
        f"</div>{tag_html}",
        unsafe_allow_html=True,
    )


def rail_cap(text: str) -> None:
    """The small uppercase caption that labels a group in the rail."""
    st.markdown(f'<p class="ups-rail-cap">{_e(text)}</p>', unsafe_allow_html=True)


def engine_card(label: str, value: str, status: str, kind: str = "ok") -> None:
    """The rail's footer card β€” which AI service this session is running on."""
    dot = "ups-dot" if kind == "ok" else f"ups-dot {_e(kind)}"
    st.markdown(
        f'<div class="ups-engine">'
        f'<div class="k">{_e(label)}</div>'
        f'<div class="v">{_e(value)}</div>'
        f'<div class="s"><span class="{dot}"></span>{_e(status)}</div>'
        f"</div>",
        unsafe_allow_html=True,
    )


# ── surfaces ──────────────────────────────────────────────────────────────


def panel(body_html: str, *, title: str = "", right_html: str = "") -> None:
    """A glass panel built from markup only.

    For a panel that must CONTAIN Streamlit widgets, use
    ``st.container(border=True)`` instead β€” the widget layer styles it to
    match this exactly. Wrapping widgets in raw HTML does not work.
    """
    head = (
        f'<div class="ups-panel-h"><span class="ups-ct">{_e(title)}</span>'
        f'<span class="ups-sp"></span>{right_html}</div>'
        if title or right_html
        else ""
    )
    st.markdown(
        f'<div class="ups-panel ups-glass">{head}{body_html}</div>',
        unsafe_allow_html=True,
    )


def panel_header(title: str, right_html: str = "") -> None:
    """The panel head on its own, for use inside a st.container(border=True)."""
    st.markdown(
        f'<div class="ups-panel-h"><span class="ups-ct">{_e(title)}</span>'
        f'<span class="ups-sp"></span>{right_html}</div>',
        unsafe_allow_html=True,
    )


def kpis(items: list[dict], *, columns: int | None = None) -> None:
    """A row of KPI tiles.

    Each item: ``{"lab", "val", "icon" | "initial", "delta", "delta_kind"}``.
    Only ever call this with numbers the app actually has β€” a KPI that has to
    be invented is a KPI that should not be on the screen.
    """
    if not items:
        return
    n = columns or len(items)
    cls = {1: "ups-kpis one", 2: "ups-kpis two", 3: "ups-kpis three"}.get(n, "ups-kpis")
    tiles = []
    for it in items:
        badge = _ico(it["icon"]) if it.get("icon") else _e(it.get("initial", ""))
        delta = (
            f'<span class="delta {_e(it.get("delta_kind", "t2"))}">{_e(it["delta"])}</span>'
            if it.get("delta")
            else ""
        )
        tiles.append(
            f'<div class="ups-kpi ups-glass{" on" if it.get("on") else ""}">'
            f'<span class="ups-kpi-t"><span>'
            f'<span class="lab">{_e(it["lab"])}</span>'
            f'<span class="val">{_e(it["val"])}</span></span>'
            f'<span class="ic">{badge}</span></span>'
            f"{delta}</div>"
        )
    st.markdown(f'<div class="{cls}">{"".join(tiles)}</div>', unsafe_allow_html=True)


def rows_table(columns: list[str], widths: str, rows: list[list[str]]) -> None:
    """A header row plus data rows on the artboard's grid.

    ``widths`` is a ``grid-template-columns`` value; every row uses it, so the
    header and the body always line up. Cells are pre-built HTML fragments
    from the caller (use ``cell`` / ``tile`` / ``tag`` below) β€” escape any raw
    text with the helpers rather than passing it through.
    """
    head = "".join(f"<span>{_e(c)}</span>" for c in columns)
    body = "".join(
        f'<div class="ups-row" style="grid-template-columns:{widths}">'
        + "".join(cells)
        + "</div>"
        for cells in rows
    )
    st.markdown(
        f'<div class="ups-thead" style="grid-template-columns:{widths}">{head}</div>'
        f"{body}",
        unsafe_allow_html=True,
    )


def cell(main: str, sub: str = "") -> str:
    """One two-line row cell: a bold primary line over a muted second line."""
    sub_html = f'<span class="sub">{_e(sub)}</span>' if sub else ""
    return f"<span><b>{_e(main)}</b>{sub_html}</span>"


def plain(text: str, cls: str = "ups-cap") -> str:
    """One single-line row cell."""
    return f'<span class="{_e(cls)}">{_e(text)}</span>'


def tile(label: str = "", icon_name: str | None = None) -> str:
    """The small square badge at the head of a row."""
    return f'<span class="ups-tile">{_ico(icon_name) if icon_name else _e(label)}</span>'


def kv_grid(pairs: list[tuple[str, str]], *, columns: int = 4) -> None:
    """The extracted-facts grid: a label over a value, in equal cells."""
    if not pairs:
        return
    # Values are often the user's own words: "$10 or $20" must not turn
    # into maths, so they get the Markdown-safe escaping, not just HTML's.
    cells = "".join(
        f'<div class="ups-kvc"><div class="k">{_text_block(k)}</div>'
        f'<div class="v{"" if v else " dim"}">{_text_block(v) if v else "not stated"}</div></div>'
        for k, v in pairs
    )
    cls = "ups-kv two" if columns == 2 else "ups-kv"
    st.markdown(f'<div class="{cls}">{cells}</div>', unsafe_allow_html=True)


def log_block(lines: list[tuple[str, str]]) -> None:
    """A console transcript: ``(text, kind)`` where kind is ``""``/``ac``/``ok``."""
    body = "".join(f'<div class="{_e(k)}">{_e(t)}</div>' for t, k in lines)
    st.markdown(f'<div class="ups-log">{body}</div>', unsafe_allow_html=True)


# Characters Markdown would act on even inside an HTML block: "$" starts
# maths, "*" and "_" emphasis, a backtick code. As entities they display as
# themselves. Newlines become <br>, because a blank line would end the HTML
# block and turn an indented line into a code box.
_MD_ENTITIES = {
    "$": "&#36;", "*": "&#42;", "_": "&#95;", "`": "&#96;", "~": "&#126;",
    "\\": "&#92;", "[": "&#91;", "]": "&#93;", "#": "&#35;", "|": "&#124;",
}


_HTML_ENTITIES = {"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"}


def _text_block(value: object) -> str:
    """Escape free text for an HTML block rendered through Markdown.

    One pass, one entity per character: escaping HTML first and Markdown
    after would rewrite the "#" inside the apostrophe's own entity.
    """
    text = "" if value is None else str(value)
    escaped = "".join(_HTML_ENTITIES.get(ch) or _MD_ENTITIES.get(ch, ch) for ch in text)
    return "<br>".join(line.strip() for line in escaped.splitlines())


def evidence_list(items: list[dict]) -> None:
    """Evidence entries: a claim, the sentence behind it, and its source file."""
    body = "".join(
        f'<div class="ups-ev"><b>{_text_block(it["title"])}</b>'
        f'<p>{_text_block(it["body"])}</p>'
        + (
            f'<span class="ups-cite">{_ico("doc")}{_text_block(it["source"])}</span>'
            if it.get("source")
            else ""
        )
        + "</div>"
        for it in items
    )
    st.markdown(body, unsafe_allow_html=True)


# ── inline fragments ──────────────────────────────────────────────────────


_TAG_KINDS = {"ok", "warn", "stop", "violet"}


def tag(label: str, kind: str = "", icon_name: str | None = None) -> str:
    """A pill. Returns markup β€” compose several inside a ``ups-flow`` row."""
    cls = f"ups-tag {kind}" if kind in _TAG_KINDS else "ups-tag"
    return f'<span class="{cls}">{_ico(icon_name)}{_e(label)}</span>'


def field(text: str, *, icon_name: str | None = None, mono: bool = False,
          on: bool = False, right_html: str = "") -> str:
    """A read-only value shown in the same shape as an input.

    Read-only only: anything the user types stays a real Streamlit widget.
    """
    body = f'<span class="{"mono" if mono else ""}">{_e(text)}</span>'
    return (
        f'<div class="ups-field{" on" if on else ""}">'
        f'{_ico(icon_name)}{body}<span class="ups-sp"></span>{right_html}</div>'
    )


def meter(pct: float, band: str = "") -> str:
    """A progress meter. ``band`` is ``""``/``ok``/``warn``/``stop``."""
    width = max(0.0, min(100.0, float(pct)))
    cls = f"ups-meter {band}" if band in {"ok", "warn", "stop"} else "ups-meter"
    return f'<div class="{cls}"><i style="width:{width:.4g}%"></i></div>'


_RING_BANDS = {
    "ok":   ("#22C55E", "#4ADE80"),
    "warn": ("#E0A34A", "#F0C078"),
    "stop": ("#F1566E", "#FB7A8E"),
}
_RING_CIRCUMFERENCE = 433.5  # 2 * pi * r, r = 69 β€” the artboard's geometry


def score_ring(score: float, *, band: str = "", label: str = "Fit score",
               out_of: float = 100.0) -> str:
    """The fit-score ring: track, gradient arc, comet head and centred value."""
    pct = 0.0 if out_of <= 0 else max(0.0, min(1.0, float(score) / float(out_of)))
    c1, c2 = _RING_BANDS.get(band, ("#8B5CF6", "#A78BFA"))
    offset = _RING_CIRCUMFERENCE * (1 - pct)
    deg = 360 * pct
    uid = f"rg{abs(hash((c1, c2, round(pct, 4)))) % 100000}"
    return (
        f'<div class="ups-ring"><svg viewBox="0 0 168 168" aria-hidden="true">'
        f'<defs><linearGradient id="{uid}" x1="0" y1="0" x2="1" y2="1">'
        f'<stop offset="0" stop-color="{c1}"/><stop offset="1" stop-color="{c2}"/>'
        f"</linearGradient></defs>"
        f'<circle class="tr" cx="84" cy="84" r="69"></circle>'
        f'<circle class="bar" cx="84" cy="84" r="69" stroke="url(#{uid})" '
        f'stroke-dasharray="{_RING_CIRCUMFERENCE}" stroke-dashoffset="{offset:.2f}"></circle>'
        f'<g class="comet" style="transform:rotate({deg:.2f}deg)">'
        f'<circle cx="153" cy="84" r="4.5" fill="#FFFFFF"></circle></g>'
        f"</svg>"
        f'<div class="val"><b>{_e(round(score))}</b><span>{_e(label)}</span></div></div>'
    )


def flow(*fragments: str, gap: int = 12, top: int = 0) -> None:
    """Lay inline fragments (tags, captions) out in a row."""
    style = f"gap:{gap}px" + (f";margin-top:{top}px" if top else "")
    st.markdown(
        f'<div class="ups-flow" style="{style}">{"".join(f for f in fragments if f)}</div>',
        unsafe_allow_html=True,
    )


def html(markup: str) -> None:
    """Emit a composed fragment. The caller owns escaping."""
    st.markdown(markup, unsafe_allow_html=True)