claude-code-mux 0.6.2

High-performance, intelligent Claude Code router built in Rust
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
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Admin</title>

        <!-- htmx 2.0.8 -->
        <script src="https://unpkg.com/htmx.org@2.0.8"></script>

        <!-- Franken UI -->
        <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/franken-ui@2.1.1/dist/css/core.min.css"
        />

        <!-- Fonts -->
        <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=Pretendard:wght@400;500;600;700;800&display=swap"
            rel="stylesheet"
        />

        <!-- Tailwind CSS -->
        <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
        <style type="text/tailwindcss">
            * {
                font-family:
                    "Pretendard",
                    -apple-system,
                    BlinkMacSystemFont,
                    system-ui,
                    Roboto,
                    sans-serif;
            }

            body {
                background: #f9fafb;
                color: #191f28;
            }

            .tab-active {
                color: #3182f6;
                font-weight: 600;
            }

            .btn-primary {
                background: #3182f6;
                color: white;
                padding: 16px 24px;
                border-radius: 12px;
                font-weight: 600;
                font-size: 17px;
                border: none;
                cursor: pointer;
                transition: all 0.2s;
            }

            .btn-primary:hover {
                background: #1b64da;
            }

            .btn-secondary {
                background: #f2f4f6;
                color: #4e5968;
                padding: 16px 24px;
                border-radius: 12px;
                font-weight: 600;
                font-size: 17px;
                border: none;
                cursor: pointer;
                transition: all 0.2s;
            }

            .btn-secondary:hover {
                background: #e5e8eb;
            }

            .card {
                background: white;
                border-radius: 16px;
                padding: 32px;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
            }

            .input-field {
                width: 100%;
                padding: 16px 20px;
                border: 1.5px solid #e5e8eb;
                border-radius: 12px;
                font-size: 16px;
                transition: all 0.2s;
            }

            .input-field:focus {
                outline: none;
                border-color: #3182f6;
            }

            .label {
                font-size: 15px;
                font-weight: 600;
                color: #333d4b;
                margin-bottom: 8px;
                display: block;
            }

            .helper-text {
                font-size: 14px;
                color: #6b7684;
                margin-top: 6px;
            }

            /* Fade out animation for deletions */
            @keyframes fadeOut {
                from {
                    opacity: 1;
                    transform: translateX(0);
                }
                to {
                    opacity: 0;
                    transform: translateX(-20px);
                }
            }

            .fade-out {
                animation: fadeOut 0.3s ease-out forwards;
            }

            /* Fade in animation for new items */
            @keyframes fadeIn {
                from {
                    opacity: 0;
                    transform: translateY(-10px);
                }
                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }

            .fade-in {
                animation: fadeIn 0.3s ease-out;
            }
        </style>
    </head>
    <body>
        <div class="flex min-h-screen">
            <!-- Sidebar Navigation -->
            <aside
                class="w-64 bg-white border-r border-gray-200 flex flex-col h-screen sticky top-0"
            >
                <div class="px-6 py-8">
                    <div class="mb-12">
                        <h1 class="text-2xl font-bold">Claude Code Mux</h1>
                        <p class="text-sm text-gray-500 mt-1">Admin</p>
                    </div>

                    <nav class="space-y-2">
                        <button
                            onclick="showTab('overview')"
                            id="tab-overview"
                            class="tab-active w-full text-left px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors text-[15px]"
                        >
                            Overview
                        </button>
                        <button
                            onclick="showTab('models')"
                            id="tab-models"
                            class="w-full text-left px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors text-[15px] text-gray-600"
                        >
                            Models
                        </button>
                        <button
                            onclick="showTab('providers')"
                            id="tab-providers"
                            class="w-full text-left px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors text-[15px] text-gray-600"
                        >
                            Providers
                        </button>
                        <button
                            onclick="showTab('router')"
                            id="tab-router"
                            class="w-full text-left px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors text-[15px] text-gray-600"
                        >
                            Router
                        </button>
                        <button
                            onclick="showTab('settings')"
                            id="tab-settings"
                            class="w-full text-left px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors text-[15px] text-gray-600"
                        >
                            Settings
                        </button>
                        <button
                            onclick="showTab('test')"
                            id="tab-test"
                            class="w-full text-left px-4 py-3 rounded-lg hover:bg-gray-50 transition-colors text-[15px] text-gray-600"
                        >
                            Test
                        </button>
                    </nav>
                </div>

                <!-- Action Buttons -->
                <div class="mt-auto border-t border-gray-200 p-6 space-y-3">
                    <button
                        onclick="saveAllConfig()"
                        class="w-full btn-primary text-sm py-3"
                    >
                        💾 Save to Server
                    </button>
                    <button
                        onclick="saveAndRestart()"
                        class="w-full btn-secondary text-sm py-3 flex items-center justify-center gap-2"
                    >
                        <svg
                            class="w-4 h-4"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                        >
                            <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                            />
                        </svg>
                        <span>Save & Restart</span>
                    </button>
                    <div class="text-xs text-gray-500 text-center pt-2">
                        Last saved: <span id="last-saved">-</span>
                    </div>
                </div>
            </aside>

            <!-- Main Content -->
            <main class="flex-1 p-12 max-w-5xl">
                <!-- Overview Tab -->
                <div id="content-overview" class="tab-content">
                    <h1 class="text-4xl font-bold mb-3">Routing Status</h1>
                    <p class="text-gray-600 text-lg mb-12">
                        Monitor your AI routing configuration
                    </p>

                    <div class="grid grid-cols-3 gap-6 mb-12">
                        <div class="card">
                            <div class="text-gray-600 text-sm mb-2">
                                Providers
                            </div>
                            <div class="text-4xl font-bold" id="provider-count">
                                0
                            </div>
                        </div>
                        <div class="card">
                            <div class="text-gray-600 text-sm mb-2">Models</div>
                            <div
                                class="text-4xl font-bold"
                                id="model-count-overview"
                            >
                                0
                            </div>
                        </div>
                        <div class="card">
                            <div class="text-gray-600 text-sm mb-2">Status</div>
                            <div class="text-4xl font-bold text-blue-600">
                                Active
                            </div>
                        </div>
                    </div>

                    <div class="card mb-6">
                        <h2 class="text-2xl font-bold mb-6">
                            Router Configuration
                        </h2>
                        <div class="space-y-4" id="router-status">
                            <div
                                class="flex justify-between items-center py-3 border-b"
                            >
                                <span class="text-gray-600">Default Model</span>
                                <span class="font-semibold" id="current-default"
                                    >-</span
                                >
                            </div>
                            <div
                                class="flex justify-between items-center py-3 border-b"
                            >
                                <span class="text-gray-600">Think Model</span>
                                <span class="font-semibold" id="current-think"
                                    >-</span
                                >
                            </div>
                            <div
                                class="flex justify-between items-center py-3 border-b"
                            >
                                <span class="text-gray-600"
                                    >Background Model</span
                                >
                                <span
                                    class="font-semibold"
                                    id="current-background"
                                    >-</span
                                >
                            </div>
                            <div class="flex justify-between items-center py-3">
                                <span class="text-gray-600"
                                    >WebSearch Model</span
                                >
                                <span
                                    class="font-semibold"
                                    id="current-websearch"
                                    >-</span
                                >
                            </div>
                        </div>
                    </div>

                    <div class="card">
                        <h2 class="text-2xl font-bold mb-6">Server Info</h2>
                        <div class="space-y-4">
                            <div class="flex justify-between items-center py-3">
                                <span class="text-gray-600">Address</span>
                                <code
                                    class="font-mono text-sm"
                                    id="server-address"
                                    >-</code
                                >
                            </div>
                        </div>
                    </div>

                    <div class="card mt-6">
                        <h2 class="text-2xl font-bold mb-6">API Endpoints</h2>
                        <div class="space-y-3">
                            <div
                                class="p-4 rounded-lg bg-gray-50 border border-gray-200"
                            >
                                <div class="flex items-center gap-2 mb-2">
                                    <span
                                        class="px-2 py-1 rounded bg-blue-100 text-blue-700 text-xs font-bold"
                                        >POST</span
                                    >
                                    <code class="text-sm font-mono"
                                        >/v1/messages</code
                                    >
                                </div>
                                <p class="text-xs text-gray-600">
                                    Send messages with automatic model routing
                                </p>
                            </div>

                            <div
                                class="p-4 rounded-lg bg-gray-50 border border-gray-200"
                            >
                                <div class="flex items-center gap-2 mb-2">
                                    <span
                                        class="px-2 py-1 rounded bg-blue-100 text-blue-700 text-xs font-bold"
                                        >POST</span
                                    >
                                    <code class="text-sm font-mono"
                                        >/v1/messages/count_tokens</code
                                    >
                                </div>
                                <p class="text-xs text-gray-600">
                                    Count tokens for messages
                                </p>
                            </div>

                            <div
                                class="p-4 rounded-lg bg-gray-50 border border-gray-200"
                            >
                                <div class="flex items-center gap-2 mb-2">
                                    <span
                                        class="px-2 py-1 rounded bg-green-100 text-green-700 text-xs font-bold"
                                        >GET</span
                                    >
                                    <code class="text-sm font-mono"
                                        >/api/models-config</code
                                    >
                                </div>
                                <p class="text-xs text-gray-600">
                                    Get models configuration (name, provider
                                    mappings)
                                </p>
                            </div>

                            <div
                                class="p-4 rounded-lg bg-gray-50 border border-gray-200"
                            >
                                <div class="flex items-center gap-2 mb-2">
                                    <span
                                        class="px-2 py-1 rounded bg-green-100 text-green-700 text-xs font-bold"
                                        >GET</span
                                    >
                                    <code class="text-sm font-mono"
                                        >/api/providers</code
                                    >
                                </div>
                                <p class="text-xs text-gray-600">
                                    Get providers configuration (name, type, API
                                    keys)
                                </p>
                            </div>

                            <div
                                class="p-4 rounded-lg bg-gray-50 border border-gray-200"
                            >
                                <div class="flex items-center gap-2 mb-2">
                                    <span
                                        class="px-2 py-1 rounded bg-green-100 text-green-700 text-xs font-bold"
                                        >GET</span
                                    >
                                    <code class="text-sm font-mono"
                                        >/api/config</code
                                    >
                                </div>
                                <p class="text-xs text-gray-600">
                                    Get router configuration (default, think,
                                    background models)
                                </p>
                            </div>

                            <div
                                class="p-4 rounded-lg bg-gray-50 border border-gray-200"
                            >
                                <div class="flex items-center gap-2 mb-2">
                                    <span
                                        class="px-2 py-1 rounded bg-green-100 text-green-700 text-xs font-bold"
                                        >GET</span
                                    >
                                    <code class="text-sm font-mono"
                                        >/api/config/json</code
                                    >
                                </div>
                                <p class="text-xs text-gray-600">
                                    Get full configuration (JSON format)
                                </p>
                            </div>

                            <div
                                class="p-4 rounded-lg bg-gray-50 border border-gray-200"
                            >
                                <div class="flex items-center gap-2 mb-2">
                                    <span
                                        class="px-2 py-1 rounded bg-purple-100 text-purple-700 text-xs font-bold"
                                        >POST</span
                                    >
                                    <code class="text-sm font-mono"
                                        >/api/config/json</code
                                    >
                                </div>
                                <p class="text-xs text-gray-600">
                                    Update full configuration (JSON format)
                                </p>
                            </div>

                            <div
                                class="p-4 rounded-lg bg-gray-50 border border-gray-200"
                            >
                                <div class="flex items-center gap-2 mb-2">
                                    <span
                                        class="px-2 py-1 rounded bg-red-100 text-red-700 text-xs font-bold"
                                        >POST</span
                                    >
                                    <code class="text-sm font-mono"
                                        >/api/restart</code
                                    >
                                </div>
                                <p class="text-xs text-gray-600">
                                    Restart the server to apply configuration
                                    changes
                                </p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Providers Tab -->
                <div id="content-providers" class="tab-content hidden">
                    <div id="providers-list-view">
                        <h1 class="text-4xl font-bold mb-3">Providers</h1>
                        <p class="text-gray-600 text-lg mb-12">
                            Connect and manage AI providers
                        </p>

                        <button
                            onclick="showAddProvider()"
                            class="btn-primary mb-8"
                        >
                            Add Provider
                        </button>

                        <div id="providers-list" class="space-y-4">
                            <!-- Example Provider Card -->
                            <div class="card hidden" id="provider-card-example">
                                <div class="flex items-start justify-between">
                                    <div class="flex-1">
                                        <div
                                            class="flex items-center gap-3 mb-2"
                                        >
                                            <h3 class="text-xl font-bold">
                                                Anthropic
                                            </h3>
                                            <span
                                                class="px-3 py-1 bg-blue-50 text-blue-600 rounded-full text-sm font-semibold"
                                                >Active</span
                                            >
                                        </div>
                                        <p class="text-gray-600 mb-4">
                                            anthropic-native
                                        </p>
                                        <div class="text-sm text-gray-500">
                                            3 models • API key configured
                                        </div>
                                    </div>
                                    <div class="flex gap-2">
                                        <button class="btn-secondary">
                                            Edit
                                        </button>
                                        <button
                                            class="btn-secondary text-red-600"
                                        >
                                            Delete
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- Empty State -->
                            <div
                                class="card text-center py-16"
                                id="empty-providers"
                            >
                                <div class="text-6xl mb-4">🔌</div>
                                <h3 class="text-2xl font-bold mb-2">
                                    No providers configured
                                </h3>
                                <p class="text-gray-600 mb-6">
                                    Add a provider to use more AI models
                                </p>
                                <button
                                    onclick="showAddProvider()"
                                    class="btn-primary"
                                >
                                    Add your first Provider
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Add Provider View -->
                    <div id="providers-add-view" class="hidden">
                        <button
                            onclick="showProvidersList()"
                            class="text-blue-600 font-semibold mb-8 hover:underline"
                        >
                            ← Back to Providers
                        </button>

                        <h1 class="text-4xl font-bold mb-3">Provider Add</h1>
                        <p class="text-gray-600 text-lg mb-12">
                            Enter your API key to start using
                        </p>

                        <form id="add-provider-form" class="space-y-8">
                            <!-- Step 1: Provider Type -->
                            <div class="card">
                                <h2 class="text-2xl font-bold mb-8">
                                    Which provider do you want to add?
                                </h2>
                                <div class="grid grid-cols-3 gap-4">
                                    <!-- Anthropic-compatible -->
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="anthropic"
                                            class="peer sr-only"
                                            required
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                Anthropic
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                Claude models
                                            </div>
                                        </div>
                                    </label>
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="z.ai"
                                            class="peer sr-only"
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                z.ai
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                GLM models
                                            </div>
                                        </div>
                                    </label>
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="zenmux"
                                            class="peer sr-only"
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                ZenMux
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                Unified API gateway
                                            </div>
                                        </div>
                                    </label>
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="minimax"
                                            class="peer sr-only"
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                Minimax
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                MiniMax models
                                            </div>
                                        </div>
                                    </label>
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="kimi-coding"
                                            class="peer sr-only"
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                Kimi For Coding
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                Premium membership for Kimi
                                            </div>
                                        </div>
                                    </label>

                                    <!-- OpenAI-compatible -->
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="openai"
                                            class="peer sr-only"
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                OpenAI
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                GPT models
                                            </div>
                                        </div>
                                    </label>
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="gemini"
                                            class="peer sr-only"
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                Google Gemini
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                Gemini models (AI Studio)
                                            </div>
                                        </div>
                                    </label>
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="vertex-ai"
                                            class="peer sr-only"
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                Vertex AI
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                Gemini, Claude, Llama on GCP
                                            </div>
                                        </div>
                                    </label>
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="openrouter"
                                            class="peer sr-only"
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                OpenRouter
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                500+ models
                                            </div>
                                        </div>
                                    </label>
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="groq"
                                            class="peer sr-only"
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                Groq
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                Ultra-fast ⚡
                                            </div>
                                        </div>
                                    </label>
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="together"
                                            class="peer sr-only"
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                Together AI
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                Open source
                                            </div>
                                        </div>
                                    </label>
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="fireworks"
                                            class="peer sr-only"
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                Fireworks AI
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                Fast inference
                                            </div>
                                        </div>
                                    </label>
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="deepinfra"
                                            class="peer sr-only"
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                Deepinfra
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                Cost-effective
                                            </div>
                                        </div>
                                    </label>
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="cerebras"
                                            class="peer sr-only"
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                Cerebras
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                Ultra-fast ⚡
                                            </div>
                                        </div>
                                    </label>
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="nebius"
                                            class="peer sr-only"
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                Nebius
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                AI platform
                                            </div>
                                        </div>
                                    </label>
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="moonshot"
                                            class="peer sr-only"
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                Moonshot AI
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                Kimi models
                                            </div>
                                        </div>
                                    </label>
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="novita"
                                            class="peer sr-only"
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                NovitaAI
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                GPU cloud
                                            </div>
                                        </div>
                                    </label>
                                    <label class="cursor-pointer">
                                        <input
                                            type="radio"
                                            name="provider_type"
                                            value="baseten"
                                            class="peer sr-only"
                                        />
                                        <div
                                            class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                        >
                                            <div class="text-xl font-bold mb-1">
                                                Baseten
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                ML deployment
                                            </div>
                                        </div>
                                    </label>
                                </div>
                            </div>

                            <!-- Step 2: Basic Info -->
                            <div class="card">
                                <h2 class="text-2xl font-bold mb-8">
                                    Choose a name for this provider
                                </h2>
                                <div>
                                    <label class="label">Name</label>
                                    <input
                                        type="text"
                                        name="provider_name"
                                        class="input-field"
                                        placeholder="e.g., anthropic-main"
                                        required
                                    />
                                    <div class="helper-text">
                                        A name to identify this provider
                                    </div>
                                </div>
                            </div>

                            <!-- Step 3: Authentication -->
                            <div class="card" id="auth-card">
                                <h2
                                    class="text-2xl font-bold mb-8"
                                    id="auth-card-title"
                                >
                                    Choose authentication method
                                </h2>

                                <!-- Vertex AI Configuration (shown only for vertex-ai provider) -->
                                <div id="vertex-ai-config" class="hidden">
                                    <div
                                        class="bg-blue-50 border-2 border-blue-200 rounded-xl p-6 mb-4"
                                    >
                                        <div class="flex items-start gap-4">
                                            <div class="text-3xl">☁️</div>
                                            <div class="flex-1">
                                                <h3
                                                    class="font-bold text-lg mb-4"
                                                >
                                                    Google Cloud Vertex AI
                                                    Configuration
                                                </h3>

                                                <div class="space-y-4">
                                                    <div>
                                                        <label class="label"
                                                            >Project ID</label
                                                        >
                                                        <input
                                                            type="text"
                                                            id="vertex-project-id"
                                                            name="vertex_project_id"
                                                            class="input-field font-mono"
                                                            placeholder="my-gcp-project"
                                                        />
                                                        <div
                                                            class="helper-text"
                                                        >
                                                            Your Google Cloud
                                                            Project ID
                                                        </div>
                                                    </div>

                                                    <div>
                                                        <label class="label"
                                                            >Location</label
                                                        >
                                                        <select
                                                            id="vertex-location"
                                                            name="vertex_location"
                                                            class="input-field"
                                                        >
                                                            <option
                                                                value="us-central1"
                                                            >
                                                                us-central1
                                                            </option>
                                                            <option
                                                                value="us-east1"
                                                            >
                                                                us-east1
                                                            </option>
                                                            <option
                                                                value="us-east4"
                                                            >
                                                                us-east4
                                                            </option>
                                                            <option
                                                                value="us-west1"
                                                            >
                                                                us-west1
                                                            </option>
                                                            <option
                                                                value="us-west4"
                                                            >
                                                                us-west4
                                                            </option>
                                                            <option
                                                                value="europe-west1"
                                                            >
                                                                europe-west1
                                                            </option>
                                                            <option
                                                                value="europe-west2"
                                                            >
                                                                europe-west2
                                                            </option>
                                                            <option
                                                                value="europe-west4"
                                                            >
                                                                europe-west4
                                                            </option>
                                                            <option
                                                                value="asia-east1"
                                                            >
                                                                asia-east1
                                                            </option>
                                                            <option
                                                                value="asia-northeast1"
                                                            >
                                                                asia-northeast1
                                                            </option>
                                                            <option
                                                                value="asia-southeast1"
                                                            >
                                                                asia-southeast1
                                                            </option>
                                                        </select>
                                                        <div
                                                            class="helper-text"
                                                        >
                                                            Region where Vertex
                                                            AI is enabled
                                                        </div>
                                                    </div>

                                                    <div
                                                        class="bg-yellow-50 border-l-4 border-yellow-400 p-3"
                                                    >
                                                        <p
                                                            class="text-sm text-yellow-800"
                                                        >
                                                            <strong
                                                                >ℹ️
                                                                Authentication:</strong
                                                            ><br />
                                                            Vertex AI uses
                                                            Application Default
                                                            Credentials (ADC).
                                                            Before starting the
                                                            server, run:<br />
                                                            <code
                                                                class="bg-yellow-100 px-1 mt-1 block"
                                                                >gcloud auth
                                                                application-default
                                                                login</code
                                                            >
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Auth Type Selector (hidden for vertex-ai) -->
                                <div class="mb-8" id="auth-type-selector">
                                    <div class="grid grid-cols-2 gap-4">
                                        <label class="cursor-pointer">
                                            <input
                                                type="radio"
                                                name="auth_type"
                                                value="apikey"
                                                class="peer sr-only"
                                                checked
                                                onchange="toggleAuthMethod()"
                                            />
                                            <div
                                                class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                            >
                                                <div
                                                    class="text-lg font-bold mb-1"
                                                >
                                                    API Key
                                                </div>
                                                <div
                                                    class="text-sm text-gray-600"
                                                >
                                                    Use your API key for
                                                    authentication
                                                </div>
                                            </div>
                                        </label>
                                        <label class="cursor-pointer">
                                            <input
                                                type="radio"
                                                name="auth_type"
                                                value="oauth"
                                                class="peer sr-only"
                                                onchange="toggleAuthMethod()"
                                            />
                                            <div
                                                class="p-6 border-2 border-gray-200 rounded-xl peer-checked:border-blue-600 peer-checked:bg-blue-50 hover:border-gray-300 transition-all"
                                            >
                                                <div
                                                    id="oauth-label-title"
                                                    class="text-lg font-bold mb-1"
                                                >
                                                    OAuth (Claude Pro/Max)
                                                </div>
                                                <div
                                                    id="oauth-label-description"
                                                    class="text-sm text-gray-600"
                                                >
                                                    Free for Claude Max
                                                    subscribers
                                                </div>
                                            </div>
                                        </label>
                                    </div>
                                </div>

                                <!-- API Key Input (shown by default) -->
                                <div id="api-key-section">
                                    <label class="label">API Key</label>
                                    <input
                                        type="password"
                                        id="api-key-input"
                                        name="api_key"
                                        class="input-field font-mono"
                                        placeholder="sk-ant-..."
                                    />
                                    <div class="helper-text">
                                        Your API key will be stored securely
                                    </div>
                                </div>

                                <!-- OAuth Section (hidden by default) -->
                                <div id="oauth-section" class="hidden">
                                    <div
                                        class="bg-purple-50 border-2 border-purple-200 rounded-xl p-6 mb-4"
                                    >
                                        <div class="flex items-start gap-4">
                                            <div class="text-3xl">🔐</div>
                                            <div class="flex-1">
                                                <h3
                                                    class="font-bold text-lg mb-2"
                                                >
                                                    OAuth Authentication
                                                </h3>

                                                <!-- Step 1: Initial state -->
                                                <div id="oauth-step-1">
                                                    <p
                                                        id="oauth-step1-instruction"
                                                        class="text-sm text-gray-700 mb-4"
                                                    >
                                                        Click the button below
                                                        to authenticate with
                                                        your Claude Pro/Max
                                                        account.
                                                    </p>
                                                    <button
                                                        type="button"
                                                        onclick="startOAuthFlow()"
                                                        class="btn-primary"
                                                    >
                                                        🔐 Start OAuth Login
                                                    </button>
                                                </div>

                                                <!-- Step 2: Waiting for code -->
                                                <div
                                                    id="oauth-step-2"
                                                    class="hidden"
                                                >
                                                    <div
                                                        class="bg-blue-50 border-2 border-blue-200 rounded-lg p-4 mb-4"
                                                    >
                                                        <p
                                                            class="text-sm text-blue-900 mb-2 font-semibold"
                                                        >
                                                            ✓ Authorization
                                                            window opened
                                                        </p>
                                                        <ol
                                                            id="oauth-step2-instructions"
                                                            class="text-sm text-blue-800 space-y-1 ml-4 list-decimal"
                                                        >
                                                            <li>
                                                                Log in to your
                                                                Claude Pro/Max
                                                                account
                                                            </li>
                                                            <li>
                                                                Click "Allow" to
                                                                authorize
                                                            </li>
                                                            <li>
                                                                Copy the
                                                                authorization
                                                                code
                                                            </li>
                                                            <li>
                                                                Paste it in the
                                                                field below
                                                            </li>
                                                        </ol>
                                                    </div>
                                                    <label class="label"
                                                        >Authorization
                                                        Code</label
                                                    >
                                                    <input
                                                        type="text"
                                                        id="oauth-code-input"
                                                        class="input-field font-mono"
                                                        placeholder="Paste the code here..."
                                                    />
                                                    <div
                                                        class="flex gap-2 mt-4"
                                                    >
                                                        <button
                                                            type="button"
                                                            onclick="completeOAuthFlow()"
                                                            class="btn-primary flex-1"
                                                        >
                                                            Complete
                                                            Authentication
                                                        </button>
                                                        <button
                                                            type="button"
                                                            onclick="cancelOAuthFlow()"
                                                            class="btn-secondary"
                                                        >
                                                            Cancel
                                                        </button>
                                                    </div>
                                                </div>

                                                <!-- Step 3: Success -->
                                                <div
                                                    id="oauth-step-3"
                                                    class="hidden"
                                                >
                                                    <div
                                                        class="flex items-center gap-2 text-green-600"
                                                    >
                                                        <svg
                                                            class="w-5 h-5"
                                                            fill="currentColor"
                                                            viewBox="0 0 20 20"
                                                        >
                                                            <path
                                                                fill-rule="evenodd"
                                                                d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
                                                                clip-rule="evenodd"
                                                            />
                                                        </svg>
                                                        <span
                                                            class="font-semibold"
                                                            >OAuth token
                                                            saved!</span
                                                        >
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="helper-text">
                                        For Claude Pro/Max subscribers only.
                                        Requires active subscription.
                                    </div>
                                </div>
                            </div>

                            <!-- Step 4: Optional -->
                            <div class="card">
                                <h2 class="text-2xl font-bold mb-4">
                                    Add Settings
                                </h2>
                                <p class="text-gray-600 mb-8">
                                    Optional - only if needed
                                </p>
                                <div>
                                    <label class="label"
                                        >Custom Endpoint (Optional)</label
                                    >
                                    <input
                                        type="url"
                                        name="base_url"
                                        class="input-field font-mono"
                                        placeholder="https://api.anthropic.com"
                                    />
                                    <div class="helper-text">
                                        Only enter if you want to use a
                                        different URL than the default endpoint
                                    </div>
                                </div>
                            </div>

                            <div class="flex gap-4">
                                <button
                                    type="button"
                                    onclick="showProvidersList()"
                                    class="btn-secondary flex-1"
                                >
                                    Cancel
                                </button>
                                <button
                                    type="submit"
                                    class="btn-primary flex-1"
                                >
                                    Add Provider
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Models Tab -->
                <div id="content-models" class="tab-content hidden">
                    <div id="models-list-view">
                        <h1 class="text-4xl font-bold mb-3">Models</h1>
                        <p class="text-gray-600 text-lg mb-12">
                            Improve stability with multiple providers
                        </p>

                        <button
                            onclick="showAddModel()"
                            class="btn-primary mb-8"
                        >
                            Add Model
                        </button>

                        <div id="models-list" class="space-y-4">
                            <!-- Example Model Card -->
                            <div class="card hidden" id="model-card-example">
                                <div class="flex items-start justify-between">
                                    <div class="flex-1">
                                        <h3 class="text-xl font-bold mb-4">
                                            claude-sonnet-4-5
                                        </h3>
                                        <div class="space-y-2">
                                            <div
                                                class="flex items-center gap-2 text-sm"
                                            >
                                                <span
                                                    class="px-2 py-1 bg-blue-50 text-blue-600 rounded-lg font-semibold"
                                                    >Priority 1</span
                                                >
                                                <span class="text-gray-600"
                                                    >anthropic/claude-sonnet-4-5</span
                                                >
                                            </div>
                                            <div
                                                class="flex items-center gap-2 text-sm"
                                            >
                                                <span
                                                    class="px-2 py-1 bg-gray-100 text-gray-600 rounded-lg font-semibold"
                                                    >Priority 2</span
                                                >
                                                <span class="text-gray-500"
                                                    >openrouter/anthropic/claude-sonnet-4-5</span
                                                >
                                            </div>
                                        </div>
                                    </div>
                                    <div class="flex gap-2">
                                        <button class="btn-secondary">
                                            Edit
                                        </button>
                                        <button
                                            class="btn-secondary text-red-600"
                                        >
                                            Delete
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- Empty State -->
                            <div
                                class="card text-center py-16"
                                id="empty-models"
                            >
                                <div class="text-6xl mb-4">🎯</div>
                                <h3 class="text-2xl font-bold mb-2">
                                    No models configured
                                </h3>
                                <p class="text-gray-600 mb-6">
                                    Add a model to make it available via API
                                </p>
                                <button
                                    onclick="showAddModel()"
                                    class="btn-primary"
                                >
                                    Add First Model
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Add Model View -->
                    <div id="models-add-view" class="hidden">
                        <button
                            onclick="showModelsList()"
                            class="text-blue-600 font-semibold mb-8 hover:underline"
                        >
                            ← Back to Models
                        </button>

                        <h1 class="text-4xl font-bold mb-3">Add Model</h1>
                        <p class="text-gray-600 text-lg mb-12">
                            Configure multiple providers to increase reliability
                        </p>

                        <form id="add-model-form" class="space-y-8">
                            <!-- Step 1: Model Name -->
                            <div class="card">
                                <h2 class="text-2xl font-bold mb-8">
                                    Choose a name for this model
                                </h2>
                                <div>
                                    <label class="label">Model Name</label>
                                    <input
                                        type="text"
                                        name="model_name"
                                        class="input-field font-mono"
                                        placeholder="e.g., claude-sonnet-4-5"
                                        required
                                    />
                                    <div class="helper-text">
                                        This name will be used in API requests
                                    </div>
                                </div>
                            </div>

                            <!-- Step 2: Provider Mappings -->
                            <div class="card">
                                <h2 class="text-2xl font-bold mb-4">
                                    Map providers to actual models
                                </h2>
                                <p class="text-gray-600 mb-8">
                                    Tries providers in order, automatically
                                    fails over to the next one Auto-switching
                                    enabled
                                </p>

                                <div id="provider-mappings" class="space-y-4">
                                    <!-- Mapping 1 -->
                                    <div
                                        class="provider-mapping border-2 border-blue-200 bg-blue-50 rounded-xl p-6"
                                    >
                                        <div
                                            class="flex items-center justify-between mb-4"
                                        >
                                            <div
                                                class="flex items-center gap-3"
                                            >
                                                <span
                                                    class="px-3 py-1 bg-blue-600 text-white rounded-lg font-bold text-sm"
                                                    >Priority 1</span
                                                >
                                                <span
                                                    class="text-blue-600 font-semibold"
                                                    >Primary</span
                                                >
                                            </div>
                                        </div>
                                        <div class="space-y-4">
                                            <div>
                                                <label class="label"
                                                    >Select Provider</label
                                                >
                                                <select
                                                    name="mappings[0][provider]"
                                                    class="input-field"
                                                    required
                                                >
                                                    <option value="">
                                                        Choose a provider
                                                    </option>
                                                    <option value="anthropic">
                                                        Anthropic
                                                    </option>
                                                    <option value="openrouter">
                                                        OpenRouter
                                                    </option>
                                                    <option value="openai">
                                                        OpenAI
                                                    </option>
                                                </select>
                                            </div>
                                            <div>
                                                <label class="label"
                                                    >Model Name</label
                                                >
                                                <input
                                                    type="text"
                                                    name="mappings[0][actual_model]"
                                                    class="input-field font-mono"
                                                    placeholder="e.g., claude-sonnet-4-5 or anthropic/claude-sonnet-4-5"
                                                    required
                                                />
                                                <div class="helper-text">
                                                    Actual model name used by
                                                    the provider Model ID
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <button
                                    type="button"
                                    onclick="addProviderMapping()"
                                    class="mt-4 w-full py-3 border-2 border-dashed border-gray-300 rounded-xl text-gray-600 font-semibold hover:border-blue-400 hover:text-blue-600 transition-colors"
                                >
                                    + Fallback Provider Add
                                </button>
                            </div>

                            <div class="flex gap-4">
                                <button
                                    type="button"
                                    onclick="showModelsList()"
                                    class="btn-secondary flex-1"
                                >
                                    Cancel
                                </button>
                                <button
                                    type="submit"
                                    class="btn-primary flex-1"
                                >
                                    Add Model
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Router Tab -->
                <div id="content-router" class="tab-content hidden">
                    <h1 class="text-4xl font-bold mb-3">
                        Router Configuration
                    </h1>
                    <p class="text-gray-600 text-lg mb-12">
                        Configure different models for different scenarios
                    </p>

                    <form id="router-form" class="space-y-6">
                        <div class="card">
                            <h2 class="text-xl font-bold mb-6">
                                Default Model
                            </h2>
                            <p class="text-gray-600 mb-6">
                                Model used for most requests
                            </p>
                            <select
                                name="default_model"
                                class="input-field"
                                required
                            >
                                <option value="">Select a model</option>
                            </select>
                        </div>

                        <div class="card">
                            <h2 class="text-xl font-bold mb-6">Think Model</h2>
                            <p class="text-gray-600 mb-6">
                                Model used for complex reasoning tasks
                            </p>
                            <select name="think_model" class="input-field">
                                <option value="">Not configured</option>
                            </select>
                        </div>

                        <div class="card">
                            <h2 class="text-xl font-bold mb-6">
                                Background Model
                            </h2>
                            <p class="text-gray-600 mb-6">
                                Fast model used for simple tasks
                            </p>
                            <select name="background_model" class="input-field">
                                <option value="">Not configured</option>
                            </select>
                        </div>

                        <div class="card">
                            <h2 class="text-xl font-bold mb-6">
                                WebSearch Model
                            </h2>
                            <p class="text-gray-600 mb-6">
                                Model used when web search is needed
                            </p>
                            <select name="websearch_model" class="input-field">
                                <option value="">Not configured</option>
                            </select>
                        </div>
                    </form>
                </div>

                <!-- Settings Tab -->
                <div id="content-settings" class="tab-content hidden">
                    <h1 class="text-4xl font-bold mb-3">Settings</h1>
                    <p class="text-gray-600 text-lg mb-12">
                        Manage router regex patterns and server settings
                    </p>

                    <form id="settings-form" class="space-y-6">
                        <!-- Auto-mapping Regex -->
                        <div class="card">
                            <h2 class="text-xl font-bold mb-4">
                                Auto-mapping Pattern
                            </h2>
                            <div class="space-y-4">
                                <div>
                                    <label
                                        class="block text-sm font-semibold text-gray-700 mb-3"
                                    >
                                        Auto-map Regex
                                        <span class="text-gray-500 font-normal"
                                            >(e.g., ^claude- to match all Claude
                                            models)</span
                                        >
                                    </label>
                                    <input
                                        type="text"
                                        id="auto-map-regex"
                                        class="input-field font-mono"
                                        placeholder="^claude-"
                                    />
                                    <p class="text-sm text-gray-500 mt-2">
                                        Models matching this regex will be
                                        routed through
                                        WebSearch/Think/Background logic. Leave
                                        empty to use default (^claude-).
                                    </p>
                                </div>
                            </div>
                        </div>

                        <!-- Background Task Regex -->
                        <div class="card">
                            <h2 class="text-xl font-bold mb-4">
                                Background Task Pattern
                            </h2>
                            <div class="space-y-4">
                                <div>
                                    <label
                                        class="block text-sm font-semibold text-gray-700 mb-3"
                                    >
                                        Background Regex
                                        <span class="text-gray-500 font-normal"
                                            >(e.g., (?i)claude.*haiku for Haiku
                                            models)</span
                                        >
                                    </label>
                                    <input
                                        type="text"
                                        id="background-regex"
                                        class="input-field font-mono"
                                        placeholder="(?i)claude.*haiku"
                                    />
                                    <p class="text-sm text-gray-500 mt-2">
                                        Models matching this regex will use the
                                        background model. Leave empty to use
                                        default ((?i)claude.*haiku).
                                    </p>
                                </div>
                            </div>
                        </div>

                        <!-- OAuth Tokens Management -->
                        <div class="card">
                            <h2 class="text-xl font-bold mb-4">OAuth Tokens</h2>
                            <p class="text-gray-600 mb-6">
                                Manage your Claude Pro/Max OAuth authentication
                                tokens
                            </p>
                            <div id="oauth-tokens-container">
                                <div
                                    id="oauth-tokens-loading"
                                    class="text-center py-8"
                                >
                                    <div class="text-gray-500">
                                        Loading OAuth tokens...
                                    </div>
                                </div>
                                <div
                                    id="oauth-tokens-list"
                                    class="space-y-4 hidden"
                                >
                                    <!-- OAuth tokens will be rendered here -->
                                </div>
                                <div
                                    id="oauth-tokens-empty"
                                    class="text-center py-8 hidden"
                                >
                                    <div class="text-gray-500 mb-4">
                                        No OAuth tokens found
                                    </div>
                                    <p class="text-sm text-gray-600 mb-4">
                                        Add a provider with OAuth authentication
                                        to see tokens here
                                    </p>
                                </div>
                            </div>
                        </div>

                        <!-- Server Actions -->
                        <div class="card">
                            <h2 class="text-xl font-bold mb-4">
                                Server Actions
                            </h2>
                            <div class="flex gap-4">
                                <button
                                    type="button"
                                    onclick="restartServer()"
                                    class="btn-primary flex-1"
                                >
                                    Restart Server
                                </button>
                            </div>
                        </div>
                    </form>
                </div>

                <!-- Test Tab -->
                <div id="content-test" class="tab-content hidden">
                    <h1 class="text-4xl font-bold mb-3">Test Models</h1>
                    <p class="text-gray-600 text-lg mb-12">
                        Test your registered models with custom messages
                    </p>

                    <div class="space-y-6">
                        <!-- Model and Provider Selection -->
                        <div class="card">
                            <div class="space-y-4">
                                <div>
                                    <label
                                        class="block text-sm font-semibold text-gray-700 mb-3"
                                    >
                                        Select Model
                                    </label>
                                    <select
                                        id="test-model-select"
                                        class="input-field"
                                        onchange="updateTestProviders()"
                                    >
                                        <option value="">
                                            Choose a model...
                                        </option>
                                    </select>
                                </div>

                                <div
                                    id="test-provider-selection"
                                    class="hidden"
                                >
                                    <label
                                        class="block text-sm font-semibold text-gray-700 mb-3"
                                    >
                                        Select Provider (순위 무시)
                                    </label>
                                    <select
                                        id="test-provider-select"
                                        class="input-field"
                                    >
                                        <option value="">
                                            Use default routing...
                                        </option>
                                    </select>
                                    <p class="text-xs text-gray-500 mt-2">
                                        선택하면 라우팅 순위를 무시하고 해당
                                        provider로 직접 요청합니다
                                    </p>
                                </div>
                            </div>
                        </div>

                        <!-- Message Input -->
                        <div class="card">
                            <label
                                class="block text-sm font-semibold text-gray-700 mb-3"
                            >
                                Message
                            </label>
                            <textarea
                                id="test-message-input"
                                class="input-field font-mono text-sm"
                                rows="8"
                                placeholder="Enter your message here..."
                            ></textarea>

                            <!-- Advanced Options -->
                            <details class="mt-4">
                                <summary
                                    class="cursor-pointer text-sm font-semibold text-gray-700 select-none"
                                >
                                    Advanced Options
                                </summary>
                                <div class="mt-4 space-y-4">
                                    <div>
                                        <label
                                            class="block text-sm text-gray-700 mb-2"
                                        >
                                            Max Tokens
                                        </label>
                                        <input
                                            type="number"
                                            id="test-max-tokens"
                                            class="input-field"
                                            value="4096"
                                            min="1"
                                            max="200000"
                                        />
                                    </div>
                                    <div>
                                        <label
                                            class="block text-sm text-gray-700 mb-2"
                                        >
                                            Temperature
                                        </label>
                                        <input
                                            type="number"
                                            id="test-temperature"
                                            class="input-field"
                                            value="1.0"
                                            min="0"
                                            max="2"
                                            step="0.1"
                                        />
                                    </div>
                                    <div>
                                        <label
                                            class="flex items-center gap-2 text-sm text-gray-700 cursor-pointer"
                                        >
                                            <input
                                                type="checkbox"
                                                id="test-stream"
                                                class="rounded"
                                            />
                                            <span>Enable Streaming</span>
                                        </label>
                                    </div>
                                </div>
                            </details>

                            <div class="flex gap-3 mt-6">
                                <button
                                    onclick="sendTestMessage()"
                                    id="test-send-btn"
                                    class="btn-primary flex-1"
                                >
                                    Send Message
                                </button>
                                <button
                                    onclick="clearTestResponse()"
                                    class="btn-secondary px-6"
                                >
                                    Clear
                                </button>
                            </div>
                        </div>

                        <!-- Response Display -->
                        <div id="test-response-container" class="card hidden">
                            <div class="flex items-center justify-between mb-4">
                                <h3 class="text-lg font-semibold">Response</h3>
                                <div
                                    class="flex items-center gap-2 text-sm text-gray-600"
                                >
                                    <span id="test-response-time">-</span>
                                </div>
                            </div>

                            <!-- Loading State -->
                            <div id="test-loading" class="hidden">
                                <div
                                    class="flex items-center gap-3 text-gray-600"
                                >
                                    <svg
                                        class="animate-spin h-5 w-5"
                                        fill="none"
                                        viewBox="0 0 24 24"
                                    >
                                        <circle
                                            class="opacity-25"
                                            cx="12"
                                            cy="12"
                                            r="10"
                                            stroke="currentColor"
                                            stroke-width="4"
                                        ></circle>
                                        <path
                                            class="opacity-75"
                                            fill="currentColor"
                                            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                                        ></path>
                                    </svg>
                                    <span>Generating response...</span>
                                </div>
                            </div>

                            <!-- Response Content -->
                            <div id="test-response-content" class="hidden">
                                <div
                                    class="bg-gray-50 rounded-lg p-4 border border-gray-200"
                                >
                                    <pre
                                        id="test-response-text"
                                        class="whitespace-pre-wrap font-mono text-sm text-gray-800"
                                    ></pre>
                                </div>

                                <!-- Metadata -->
                                <div
                                    class="mt-4 grid grid-cols-2 gap-4 text-sm"
                                >
                                    <div>
                                        <span class="text-gray-600"
                                            >Input Tokens:</span
                                        >
                                        <span
                                            class="font-semibold ml-2"
                                            id="test-input-tokens"
                                            >-</span
                                        >
                                    </div>
                                    <div>
                                        <span class="text-gray-600"
                                            >Output Tokens:</span
                                        >
                                        <span
                                            class="font-semibold ml-2"
                                            id="test-output-tokens"
                                            >-</span
                                        >
                                    </div>
                                    <div>
                                        <span class="text-gray-600"
                                            >Stop Reason:</span
                                        >
                                        <span
                                            class="font-semibold ml-2"
                                            id="test-stop-reason"
                                            >-</span
                                        >
                                    </div>
                                    <div>
                                        <span class="text-gray-600"
                                            >Model:</span
                                        >
                                        <span
                                            class="font-semibold ml-2"
                                            id="test-response-model"
                                            >-</span
                                        >
                                    </div>
                                </div>
                            </div>

                            <!-- Error State -->
                            <div id="test-error" class="hidden">
                                <div
                                    class="bg-red-50 border border-red-200 rounded-lg p-4 text-red-800"
                                >
                                    <div class="font-semibold mb-2">Error</div>
                                    <div
                                        id="test-error-message"
                                        class="text-sm"
                                    ></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>

        <script>
            // Global State
            const appState = {
                config: null,
                loaded: false,
                editingProvider: null, // null or index
                editingModel: null, // null or index
            };

            // Notification Helper
            function notify(message, status = "primary") {
                if (typeof UIkit === "undefined" || !UIkit.notification) {
                    // Fallback to alert if UIkit is not loaded
                    alert(message);
                    return;
                }
                UIkit.notification({
                    message: message,
                    status: status,
                    pos: "top-right",
                    timeout: 3000,
                });
            }

            function notifySuccess(message) {
                notify(message, "success");
            }

            function notifyError(message) {
                notify(message, "danger");
            }

            function notifyWarning(message) {
                notify(message, "warning");
            }

            // Escape HTML Helper
            function escapeHtml(text) {
                const div = document.createElement("div");
                div.textContent = text;
                return div.innerHTML;
            }

            // LocalStorage helpers
            const STORAGE_KEY = "ccm_config";

            function saveToLocalStorage(config) {
                try {
                    localStorage.setItem(STORAGE_KEY, JSON.stringify(config));
                    return true;
                } catch (error) {
                    console.error("Failed to save to localStorage:", error);
                    return false;
                }
            }

            function loadFromLocalStorage() {
                try {
                    const stored = localStorage.getItem(STORAGE_KEY);
                    return stored ? JSON.parse(stored) : null;
                } catch (error) {
                    console.error("Failed to load from localStorage:", error);
                    return null;
                }
            }

            // Fetch config from server and save to localStorage (only on page load)
            async function loadConfig() {
                try {
                    const response = await fetch("/api/config/json");
                    const config = await response.json();
                    appState.config = config;
                    appState.loaded = true;
                    saveToLocalStorage(config);
                    return config;
                } catch (error) {
                    console.error("Failed to load config:", error);
                    notifyError("Failed to load configuration");
                    return null;
                }
            }

            // Sync localStorage to server (only called by save buttons)
            async function syncToServer() {
                try {
                    console.log("=== Syncing to server ===");
                    console.log(
                        "appState.config.router:",
                        appState.config.router,
                    );
                    console.log("Full config being sent:", appState.config);

                    const response = await fetch("/api/config/json", {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify(appState.config),
                    });

                    console.log("Server response status:", response.status);

                    if (response.ok) {
                        saveToLocalStorage(appState.config);
                    } else {
                        const errorText = await response.text();
                        console.error("Server error:", errorText);
                    }
                    return response.ok;
                } catch (error) {
                    console.error("Failed to sync to server:", error);
                    return false;
                }
            }

            // URL State Management
            function getURLParams() {
                return new URLSearchParams(window.location.search);
            }

            function updateURL(params, replace = false) {
                const url = new URL(window.location);
                Object.entries(params).forEach(([key, value]) => {
                    if (value === null || value === undefined) {
                        url.searchParams.delete(key);
                    } else {
                        url.searchParams.set(key, value);
                    }
                });

                if (replace) {
                    window.history.replaceState({}, "", url);
                } else {
                    window.history.pushState({}, "", url);
                }

                handleRoute();
            }

            function navigate(params) {
                updateURL(params, false);
            }

            // Tab Navigation (URL-based)
            function showTab(tabName) {
                navigate({ tab: tabName, view: null });
            }

            function handleRoute() {
                const params = getURLParams();
                const tab = params.get("tab") || "overview";
                const view = params.get("view");

                // Hide all tabs
                document
                    .querySelectorAll(".tab-content")
                    .forEach((el) => el.classList.add("hidden"));
                document.querySelectorAll('[id^="tab-"]').forEach((el) => {
                    el.classList.remove("tab-active");
                    el.classList.add("text-gray-600");
                });

                // Show selected tab
                document
                    .getElementById("content-" + tab)
                    .classList.remove("hidden");
                const tabBtn = document.getElementById("tab-" + tab);
                if (tabBtn) {
                    tabBtn.classList.add("tab-active");
                    tabBtn.classList.remove("text-gray-600");
                }

                // Handle views
                if (tab === "providers") {
                    if (view === "add") {
                        document
                            .getElementById("providers-list-view")
                            .classList.add("hidden");
                        document
                            .getElementById("providers-add-view")
                            .classList.remove("hidden");
                    } else {
                        document
                            .getElementById("providers-list-view")
                            .classList.remove("hidden");
                        document
                            .getElementById("providers-add-view")
                            .classList.add("hidden");
                        renderProvidersList();
                    }
                } else if (tab === "models") {
                    if (view === "add") {
                        document
                            .getElementById("models-list-view")
                            .classList.add("hidden");
                        document
                            .getElementById("models-add-view")
                            .classList.remove("hidden");
                        renderAddModelView();
                    } else {
                        document
                            .getElementById("models-list-view")
                            .classList.remove("hidden");
                        document
                            .getElementById("models-add-view")
                            .classList.add("hidden");
                        renderModelsList();
                    }
                } else if (tab === "test") {
                    loadTestModels();
                } else if (tab === "settings") {
                    loadSettingsTab();
                } else if (tab === "router") {
                    loadRouterTab();
                }
            }

            function loadRouterTab() {
                if (!appState.loaded) return;

                const config = appState.config;

                // Populate router form with current values
                const defaultSelect = document.querySelector(
                    '[name="default_model"]',
                );
                const thinkSelect = document.querySelector(
                    '[name="think_model"]',
                );
                const backgroundSelect = document.querySelector(
                    '[name="background_model"]',
                );
                const websearchSelect = document.querySelector(
                    '[name="websearch_model"]',
                );

                if (defaultSelect)
                    defaultSelect.value = config.router.default || "";
                if (thinkSelect) thinkSelect.value = config.router.think || "";
                if (backgroundSelect)
                    backgroundSelect.value = config.router.background || "";
                if (websearchSelect)
                    websearchSelect.value = config.router.websearch || "";
            }

            function loadSettingsTab() {
                if (!appState.loaded) return;

                const router = appState.config.router;

                // Load auto-map-regex
                const autoMapInput = document.getElementById("auto-map-regex");
                if (autoMapInput) {
                    autoMapInput.value = router.auto_map_regex || "";
                }

                // Load background-regex
                const backgroundRegexInput =
                    document.getElementById("background-regex");
                if (backgroundRegexInput) {
                    backgroundRegexInput.value = router.background_regex || "";
                }

                // Load OAuth tokens
                loadOAuthTokens();
            }

            // Provider Management
            function renderProvidersList() {
                if (!appState.loaded) return;

                const providers = appState.config.providers || [];
                const emptyState = document.getElementById("empty-providers");
                const providersList = document.getElementById("providers-list");

                // Clear existing provider cards (keep empty state)
                const existingCards = providersList.querySelectorAll(
                    ".card:not(#empty-providers)",
                );
                existingCards.forEach((card) => card.remove());

                if (providers.length === 0) {
                    emptyState.classList.remove("hidden");
                } else {
                    emptyState.classList.add("hidden");

                    // Render provider cards
                    providers.forEach((provider, index) => {
                        const providerCard = document.createElement("div");
                        providerCard.className = "card fade-in";
                        providerCard.id = `provider-card-${index}`;
                        const authType = provider.auth_type || "apikey";
                        const isOAuth = authType === "oauth";
                        const authBadge = isOAuth
                            ? '<span class="px-2 py-1 bg-purple-50 text-purple-600 rounded-full text-xs font-semibold">OAuth</span>'
                            : '<span class="px-2 py-1 bg-gray-50 text-gray-600 rounded-full text-xs font-semibold">API Key</span>';
                        const authStatus = isOAuth
                            ? "OAuth authenticated"
                            : "API key registered";

                        providerCard.innerHTML = `
                        <div class="flex items-start justify-between">
                            <div class="flex-1">
                                <div class="flex items-center gap-3 mb-2">
                                    <h3 class="text-xl font-bold">${escapeHtml(provider.name)}</h3>
                                    <span class="px-3 py-1 ${provider.enabled ? "bg-blue-50 text-blue-600" : "bg-gray-100 text-gray-500"} rounded-full text-sm font-semibold">
                                        ${provider.enabled ? "Active" : "Inactive"}
                                    </span>
                                    ${authBadge}
                                </div>
                                <p class="text-gray-600 mb-4">${escapeHtml(provider.provider_type)}</p>
                                <div class="text-sm text-gray-500">
                                    ${authStatus}
                                </div>
                            </div>
                            <div class="flex gap-2">
                                <button class="btn-secondary" onclick="editProvider(${index})">Edit</button>
                                <button class="btn-secondary text-red-600" onclick="deleteProvider(${index})">Delete</button>
                            </div>
                        </div>
                    `;
                        providersList.insertBefore(providerCard, emptyState);
                    });
                }
            }

            function addProviderCardToUI(provider, index) {
                const providersList = document.getElementById("providers-list");
                const emptyState = document.getElementById("empty-providers");

                const providerCard = document.createElement("div");
                providerCard.className = "card fade-in";
                providerCard.id = `provider-card-${index}`;

                const isVertexAi = provider.provider_type === "vertex-ai";
                const authType =
                    provider.auth_type || (isVertexAi ? "vertex" : "apikey");
                const isOAuth = authType === "oauth";

                const authBadge = isVertexAi
                    ? '<span class="px-2 py-1 bg-blue-50 text-blue-600 rounded-full text-xs font-semibold">Vertex AI</span>'
                    : isOAuth
                      ? '<span class="px-2 py-1 bg-purple-50 text-purple-600 rounded-full text-xs font-semibold">OAuth</span>'
                      : '<span class="px-2 py-1 bg-gray-50 text-gray-600 rounded-full text-xs font-semibold">API Key</span>';

                const authStatus = isVertexAi
                    ? `Vertex AI (${provider.project_id || "unknown"} / ${provider.location || "unknown"})`
                    : isOAuth
                      ? "OAuth authenticated"
                      : "API key registered";

                providerCard.innerHTML = `
                <div class="flex items-start justify-between">
                    <div class="flex-1">
                        <div class="flex items-center gap-3 mb-2">
                            <h3 class="text-xl font-bold">${escapeHtml(provider.name)}</h3>
                            <span class="px-3 py-1 ${provider.enabled ? "bg-blue-50 text-blue-600" : "bg-gray-100 text-gray-500"} rounded-full text-sm font-semibold">
                                ${provider.enabled ? "Active" : "Inactive"}
                            </span>
                            ${authBadge}
                        </div>
                        <p class="text-gray-600 mb-4">${escapeHtml(provider.provider_type)}</p>
                        <div class="text-sm text-gray-500">
                            ${authStatus}
                        </div>
                    </div>
                    <div class="flex gap-2">
                        <button class="btn-secondary" onclick="editProvider(${index})">Edit</button>
                        <button class="btn-secondary text-red-600" onclick="deleteProvider(${index})">Delete</button>
                    </div>
                </div>
            `;
                providersList.insertBefore(providerCard, emptyState);
            }

            async function deleteProvider(index) {
                if (
                    !confirm("Are you sure you want to delete this provider?")
                ) {
                    return;
                }

                const card = document.getElementById(`provider-card-${index}`);

                try {
                    card.classList.add("fade-out");

                    // Update state and save to localStorage only
                    appState.config.providers.splice(index, 1);
                    saveToLocalStorage(appState.config);

                    // Wait for animation, then re-render
                    setTimeout(() => {
                        renderProvidersList();
                        renderOverview();
                    }, 300);
                    notifySuccess("Provider deleted (click Save All to apply)");
                } catch (error) {
                    console.error("Failed to delete provider:", error);
                    card.classList.remove("fade-out");
                    notifyError("Failed to delete provider");
                }
            }

            function editProvider(index) {
                if (!appState.loaded || !appState.config.providers[index]) {
                    notifyError("Provider not found");
                    return;
                }

                // Set editing state
                appState.editingProvider = index;
                const provider = appState.config.providers[index];

                // Navigate to add view
                navigate({ tab: "providers", view: "add" });

                // Wait for DOM to update, then fill form
                setTimeout(() => {
                    const form = document.getElementById("add-provider-form");
                    if (!form) return;

                    // Fill form fields
                    const providerTypeRadio = form.querySelector(
                        `input[name="provider_type"][value="${provider.provider_type}"]`,
                    );
                    if (providerTypeRadio) {
                        providerTypeRadio.checked = true;
                        // Trigger updateOAuthLabel to show/hide Vertex AI config
                        updateOAuthLabel();
                    }

                    form.querySelector('[name="provider_name"]').value =
                        provider.name;

                    // For Vertex AI provider, fill project_id and location
                    if (provider.provider_type === "vertex-ai") {
                        const vertexProjectIdField =
                            document.getElementById("vertex-project-id");
                        const vertexLocationField =
                            document.getElementById("vertex-location");
                        if (vertexProjectIdField && provider.project_id) {
                            vertexProjectIdField.value = provider.project_id;
                        }
                        if (vertexLocationField && provider.location) {
                            vertexLocationField.value = provider.location;
                        }
                    } else {
                        // For other providers, fill API key
                        form.querySelector('[name="api_key"]').value =
                            provider.api_key || "";

                        const baseUrlField =
                            form.querySelector('[name="base_url"]');
                        if (baseUrlField && provider.base_url) {
                            baseUrlField.value = provider.base_url;
                        }
                    }

                    // Update UI labels
                    document.querySelector(
                        "#providers-add-view h1",
                    ).textContent = "Provider Edit";
                    document.querySelector(
                        "#providers-add-view > p",
                    ).textContent = "Edit provider information";
                    const submitBtn = form.querySelector(
                        'button[type="submit"]',
                    );
                    if (submitBtn) {
                        submitBtn.textContent = "Edit Provider";
                    }
                }, 100);
            }

            function showAddProvider() {
                appState.editingProvider = null;
                navigate({ tab: "providers", view: "add" });

                // Wait for DOM to update, then reset form UI
                setTimeout(() => {
                    document.querySelector(
                        "#providers-add-view h1",
                    ).textContent = "Provider Add";
                    document.querySelector(
                        "#providers-add-view > p",
                    ).textContent = "Enter your API key to start using";
                    const form = document.getElementById("add-provider-form");
                    if (form) {
                        form.reset();
                        const submitBtn = form.querySelector(
                            'button[type="submit"]',
                        );
                        if (submitBtn) {
                            submitBtn.textContent = "Add Provider";
                        }
                    }
                }, 100);
            }

            function showProvidersList() {
                navigate({ tab: "providers", view: null });
            }

            // Model Management
            let mappingCount = 1;

            function renderModelsList() {
                if (!appState.loaded) return;

                const models = appState.config.models || [];

                const emptyState = document.getElementById("empty-models");
                const modelsList = document.getElementById("models-list");

                // Clear existing model cards (keep empty state)
                const existingCards = modelsList.querySelectorAll(
                    ".card:not(#empty-models)",
                );
                existingCards.forEach((card) => card.remove());

                if (models.length === 0) {
                    emptyState.classList.remove("hidden");
                } else {
                    emptyState.classList.add("hidden");

                    // Render model cards
                    models.forEach((model, index) => {
                        const modelCard = document.createElement("div");
                        modelCard.className = "card fade-in";
                        modelCard.id = `model-card-${index}`;

                        // Build mappings HTML
                        const mappingsHtml = model.mappings
                            .sort((a, b) => a.priority - b.priority)
                            .map((mapping) => {
                                const isPrimary = mapping.priority === 1;
                                return `
                                    <div class="flex items-center gap-2 text-sm">
                                        <span class="px-2 py-1 ${isPrimary ? "bg-blue-50 text-blue-600" : "bg-gray-100 text-gray-600"} rounded-lg font-semibold">Priority ${mapping.priority}</span>
                                        <span class="text-gray-600">${escapeHtml(mapping.provider)}  ${escapeHtml(mapping.actual_model)}</span>
                                    </div>
                                `;
                            })
                            .join("");

                        modelCard.innerHTML = `
                            <div class="flex items-start justify-between">
                                <div class="flex-1">
                                    <h3 class="text-xl font-bold mb-4">${escapeHtml(model.name)}</h3>
                                    <div class="space-y-2">
                                        ${mappingsHtml}
                                    </div>
                                </div>
                                <div class="flex gap-2">
                                    <button class="btn-secondary" onclick="editModel(${index})">Edit</button>
                                    <button class="btn-secondary text-red-600" onclick="deleteModel(${index})">Delete</button>
                                </div>
                            </div>
                        `;
                        modelsList.insertBefore(modelCard, emptyState);
                    });
                }
            }

            function addModelCardToUI(model, index) {
                const modelsList = document.getElementById("models-list");
                const emptyState = document.getElementById("empty-models");

                const modelCard = document.createElement("div");
                modelCard.className = "card fade-in";
                modelCard.id = `model-card-${index}`;

                // Build mappings HTML
                const mappingsHtml = model.mappings
                    .sort((a, b) => a.priority - b.priority)
                    .map((mapping) => {
                        const isPrimary = mapping.priority === 1;
                        return `
                        <div class="flex items-center gap-2 text-sm">
                            <span class="px-2 py-1 ${isPrimary ? "bg-blue-50 text-blue-600" : "bg-gray-100 text-gray-600"} rounded-lg font-semibold">Priority ${mapping.priority}</span>
                            <span class="text-gray-600">${escapeHtml(mapping.provider)}  ${escapeHtml(mapping.actual_model)}</span>
                        </div>
                    `;
                    })
                    .join("");

                modelCard.innerHTML = `
                <div class="flex items-start justify-between">
                    <div class="flex-1">
                        <h3 class="text-xl font-bold mb-4">${escapeHtml(model.name)}</h3>
                        <div class="space-y-2">
                            ${mappingsHtml}
                        </div>
                    </div>
                    <div class="flex gap-2">
                        <button class="btn-secondary" onclick="editModel(${index})">Edit</button>
                        <button class="btn-secondary text-red-600" onclick="deleteModel(${index})">Delete</button>
                    </div>
                </div>
            `;
                modelsList.insertBefore(modelCard, emptyState);
            }

            async function deleteModel(index) {
                if (!confirm("Are you sure you want to delete this model?")) {
                    return;
                }

                const card = document.getElementById(`model-card-${index}`);

                try {
                    card.classList.add("fade-out");

                    // Update state and save to localStorage only
                    appState.config.models.splice(index, 1);
                    saveToLocalStorage(appState.config);

                    // Wait for animation, then re-render
                    setTimeout(() => {
                        renderModelsList();
                        renderOverview();
                    }, 300);
                    notifySuccess("Model deleted (click Save All to apply)");
                } catch (error) {
                    console.error("Failed to delete model:", error);
                    card.classList.remove("fade-out");
                    notifyError("Failed to delete model");
                }
            }

            function editModel(index) {
                if (!appState.loaded || !appState.config.models[index]) {
                    notifyError("Model not found");
                    return;
                }

                // Set editing state
                appState.editingModel = index;
                const model = appState.config.models[index];

                // Navigate to add view
                navigate({ tab: "models", view: "add" });

                // Wait for DOM to update, then fill form
                setTimeout(() => {
                    const form = document.getElementById("add-model-form");
                    if (!form) return;

                    // Fill model name
                    form.querySelector('[name="model_name"]').value =
                        model.name;

                    // Clear existing mappings and add model's mappings
                    const mappingsContainer =
                        document.getElementById("provider-mappings");
                    mappingsContainer.innerHTML = "";

                    mappingCount = model.mappings.length;

                    model.mappings.forEach((mapping, index) => {
                        const isPrimary = mapping.priority === 1;
                        const mappingDiv = document.createElement("div");
                        mappingDiv.className = isPrimary
                            ? "provider-mapping border-2 border-blue-200 bg-blue-50 rounded-xl p-6"
                            : "provider-mapping border-2 border-gray-200 rounded-xl p-6";
                        mappingDiv.setAttribute(
                            "data-priority",
                            mapping.priority,
                        );

                        const providers = appState.config.providers || [];
                        const providerOptions = providers
                            .filter((p) => p.enabled)
                            .map(
                                (p) =>
                                    `<option value="${escapeHtml(p.name)}" ${p.name === mapping.provider ? "selected" : ""}>${escapeHtml(p.name)} (${escapeHtml(p.provider_type)})</option>`,
                            )
                            .join("");

                        if (isPrimary) {
                            mappingDiv.innerHTML = `
                                <div class="flex items-center justify-between mb-4">
                                    <div class="flex items-center gap-3">
                                        <span class="px-3 py-1 bg-blue-600 text-white rounded-lg font-bold text-sm">Priority 1</span>
                                        <span class="text-blue-600 font-semibold">Primary</span>
                                    </div>
                                </div>
                                <div class="space-y-4">
                                    <div>
                                        <label class="label">Select Provider</label>
                                        <select name="mappings[${index}][provider]" class="input-field" required>
                                            <option value="">Choose a provider</option>
                                            ${providerOptions}
                                        </select>
                                    </div>
                                    <div>
                                        <label class="label">Model Name</label>
                                        <input type="text" name="mappings[${index}][actual_model]" class="input-field font-mono" value="${escapeHtml(mapping.actual_model)}" placeholder="e.g., claude-sonnet-4-5 or anthropic/claude-sonnet-4-5" required>
                                        <div class="helper-text">The actual model ID used by the provider</div>
                                    </div>
                                </div>
                            `;
                        } else {
                            mappingDiv.innerHTML = `
                                <div class="flex items-center justify-between mb-4">
                                    <div class="flex items-center gap-3">
                                        <span class="px-3 py-1 bg-gray-200 text-gray-700 rounded-lg font-bold text-sm">Priority ${mapping.priority}</span>
                                        <span class="text-gray-600 font-semibold">Fallback</span>
                                    </div>
                                    <div class="flex gap-2">
                                        <button type="button" onclick="moveMappingUp(this)" class="p-2 hover:bg-gray-100 rounded-lg">
                                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7"/>
                                            </svg>
                                        </button>
                                        <button type="button" onclick="moveMappingDown(this)" class="p-2 hover:bg-gray-100 rounded-lg">
                                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                                            </svg>
                                        </button>
                                        <button type="button" onclick="removeMapping(this)" class="p-2 hover:bg-red-50 text-red-600 rounded-lg">
                                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                                            </svg>
                                        </button>
                                    </div>
                                </div>
                                <div class="space-y-4">
                                    <div>
                                        <label class="label">Select Provider</label>
                                        <select name="mappings[${index}][provider]" class="input-field" required>
                                            <option value="">Choose a provider</option>
                                            ${providerOptions}
                                        </select>
                                    </div>
                                    <div>
                                        <label class="label">Model Name</label>
                                        <input type="text" name="mappings[${index}][actual_model]" class="input-field font-mono" value="${escapeHtml(mapping.actual_model)}" placeholder="e.g., claude-sonnet-4-5 or anthropic/claude-sonnet-4-5" required>
                                        <div class="helper-text">The actual model ID used by the provider</div>
                                    </div>
                                </div>
                            `;
                        }

                        mappingsContainer.appendChild(mappingDiv);
                    });

                    // Update UI labels
                    document.querySelector("#models-add-view h1").textContent =
                        "Edit Model";
                    document.querySelector("#models-add-view > p").textContent =
                        "Edit model information";
                    const submitBtn = form.querySelector(
                        'button[type="submit"]',
                    );
                    if (submitBtn) {
                        submitBtn.textContent = "Edit Model";
                    }
                }, 100);
            }

            function renderAddModelView() {
                if (!appState.loaded) return;

                const providers = appState.config.providers || [];

                // Build provider options
                const providerOptions = providers
                    .filter((p) => p.enabled)
                    .map(
                        (p) =>
                            `<option value="${escapeHtml(p.name)}">${escapeHtml(p.name)} (${escapeHtml(p.provider_type)})</option>`,
                    )
                    .join("");

                // Reset mappings
                mappingCount = 1;
                document.getElementById("provider-mappings").innerHTML = `
                <div class="provider-mapping border-2 border-blue-200 bg-blue-50 rounded-xl p-6" data-priority="1">
                    <div class="flex items-center justify-between mb-4">
                        <div class="flex items-center gap-3">
                            <span class="px-3 py-1 bg-blue-600 text-white rounded-lg font-bold text-sm">Priority 1</span>
                            <span class="text-blue-600 font-semibold">Primary</span>
                        </div>
                    </div>
                    <div class="space-y-4">
                        <div>
                            <label class="label">Select Provider</label>
                            <select name="mappings[0][provider]" class="input-field" required>
                                <option value="">Choose a provider</option>
                                ${providerOptions}
                            </select>
                        </div>
                        <div>
                            <label class="label">Model Name</label>
                            <input type="text" name="mappings[0][actual_model]" class="input-field font-mono" placeholder="e.g., claude-sonnet-4-5 or anthropic/claude-sonnet-4-5" required>
                            <div class="helper-text">The actual model ID used by the provider</div>
                        </div>
                    </div>
                </div>
            `;
            }

            function showAddModel() {
                appState.editingModel = null;
                navigate({ tab: "models", view: "add" });

                // Wait for DOM to update, then reset form UI
                setTimeout(() => {
                    document.querySelector("#models-add-view h1").textContent =
                        "Add Model";
                    document.querySelector("#models-add-view > p").textContent =
                        "Select a configured provider to create a model";
                    const form = document.getElementById("add-model-form");
                    if (form) {
                        form.reset();
                        const submitBtn = form.querySelector(
                            'button[type="submit"]',
                        );
                        if (submitBtn) {
                            submitBtn.textContent = "Add Model";
                        }
                    }
                    renderAddModelView();
                }, 100);
            }

            function showModelsList() {
                navigate({ tab: "models", view: null });
            }

            function addProviderMapping() {
                if (!appState.loaded) return;

                mappingCount++;
                const priority = mappingCount;
                const mappingsContainer =
                    document.getElementById("provider-mappings");

                const providers = appState.config.providers || [];

                // Build provider options
                const providerOptions = providers
                    .filter((p) => p.enabled)
                    .map(
                        (p) =>
                            `<option value="${escapeHtml(p.name)}">${escapeHtml(p.name)} (${escapeHtml(p.provider_type)})</option>`,
                    )
                    .join("");

                const newMapping = document.createElement("div");
                newMapping.className =
                    "provider-mapping border-2 border-gray-200 rounded-xl p-6";
                newMapping.setAttribute("data-priority", priority);
                newMapping.innerHTML = `
                <div class="flex items-center justify-between mb-4">
                    <div class="flex items-center gap-3">
                        <span class="px-3 py-1 bg-gray-200 text-gray-700 rounded-lg font-bold text-sm">Priority ${priority}</span>
                        <span class="text-gray-600 font-semibold">Fallback</span>
                    </div>
                    <div class="flex gap-2">
                        <button type="button" onclick="moveMappingUp(this)" class="p-2 hover:bg-gray-100 rounded-lg" ${priority === 2 ? "disabled" : ""}>
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7"/>
                            </svg>
                        </button>
                        <button type="button" onclick="moveMappingDown(this)" class="p-2 hover:bg-gray-100 rounded-lg">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                            </svg>
                        </button>
                        <button type="button" onclick="removeMapping(this)" class="p-2 hover:bg-red-50 text-red-600 rounded-lg">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                            </svg>
                        </button>
                    </div>
                </div>
                <div class="space-y-4">
                    <div>
                        <label class="label">Select Provider</label>
                        <select name="mappings[${priority - 1}][provider]" class="input-field" required>
                            <option value="">Choose a provider</option>
                            ${providerOptions}
                        </select>
                    </div>
                    <div>
                        <label class="label">Model Name</label>
                        <input type="text" name="mappings[${priority - 1}][actual_model]" class="input-field font-mono" placeholder="e.g., claude-sonnet-4-5 or anthropic/claude-sonnet-4-5" required>
                        <div class="helper-text">The actual model ID used by the provider</div>
                    </div>
                </div>
            `;

                mappingsContainer.appendChild(newMapping);
            }

            function removeMapping(btn) {
                const mapping = btn.closest(".provider-mapping");
                mapping.remove();
                updateMappingPriorities();
            }

            function moveMappingUp(btn) {
                const mapping = btn.closest(".provider-mapping");
                const prev = mapping.previousElementSibling;
                if (prev) {
                    mapping.parentNode.insertBefore(mapping, prev);
                    updateMappingPriorities();
                }
            }

            function moveMappingDown(btn) {
                const mapping = btn.closest(".provider-mapping");
                const next = mapping.nextElementSibling;
                if (next) {
                    mapping.parentNode.insertBefore(next, mapping);
                    updateMappingPriorities();
                }
            }

            function updateMappingPriorities() {
                const mappings = document.querySelectorAll(".provider-mapping");
                mappings.forEach((mapping, index) => {
                    const priority = index + 1;
                    mapping.setAttribute("data-priority", priority);

                    const badge = mapping.querySelector(".px-3");
                    const label = mapping.querySelector(".font-semibold");

                    if (priority === 1) {
                        badge.className =
                            "px-3 py-1 bg-blue-600 text-white rounded-lg font-bold text-sm";
                        badge.textContent = "Priority 1";
                        label.className = "text-blue-600 font-semibold";
                        label.textContent = "Primary";
                        mapping.className =
                            "provider-mapping border-2 border-blue-200 bg-blue-50 rounded-xl p-6";
                    } else {
                        badge.className =
                            "px-3 py-1 bg-gray-200 text-gray-700 rounded-lg font-bold text-sm";
                        badge.textContent = `Priority ${priority}`;
                        label.className = "text-gray-600 font-semibold";
                        label.textContent = "Fallback";
                        mapping.className =
                            "provider-mapping border-2 border-gray-200 rounded-xl p-6";
                    }

                    // Update input names
                    mapping
                        .querySelectorAll("select, input")
                        .forEach((input) => {
                            const name = input.name;
                            input.name = name.replace(/\[\d+\]/, `[${index}]`);
                        });
                });
            }

            // Render overview from state
            function renderOverview() {
                if (!appState.loaded) return;

                const config = appState.config;

                // Update router status
                document.getElementById("current-default").textContent =
                    config.router.default || "-";
                document.getElementById("current-think").textContent =
                    config.router.think || "Not configured";
                document.getElementById("current-background").textContent =
                    config.router.background || "Not configured";
                document.getElementById("current-websearch").textContent =
                    config.router.websearch || "Not configured";

                // Update server info
                document.getElementById("server-address").textContent =
                    `${config.server.host}:${config.server.port}`;

                // Update provider count
                const providerCount = config.providers
                    ? config.providers.length
                    : 0;
                document.getElementById("provider-count").textContent =
                    `${providerCount}`;

                // Update model count
                const modelCount = config.models ? config.models.length : 0;
                document.getElementById("model-count-overview").textContent =
                    `${modelCount}`;

                // Populate model selects with registered models
                populateModelSelects(config.models || []);

                // Populate router form
                document.querySelector('[name="default_model"]').value =
                    config.router.default || "";
                document.querySelector('[name="think_model"]').value =
                    config.router.think || "";
                document.querySelector('[name="background_model"]').value =
                    config.router.background || "";
                document.querySelector('[name="websearch_model"]').value =
                    config.router.websearch || "";

                // Update Test tab models list
                loadTestModels();
            }

            function populateModelSelects(models) {
                const selects = document.querySelectorAll(
                    'select[name$="_model"]',
                );
                selects.forEach((select) => {
                    const isRequired = select.required;
                    const currentValue = select.value;
                    select.innerHTML = isRequired
                        ? '<option value="">Select a model</option>'
                        : '<option value="">Not configured</option>';

                    models.forEach((model) => {
                        const option = document.createElement("option");
                        option.value = model.name;
                        option.textContent = model.name;
                        if (currentValue === model.name) {
                            option.selected = true;
                        }
                        select.appendChild(option);
                    });
                });
            }

            // Auto-save utility
            let autoSaveTimers = {};

            function debounce(key, callback, delay = 1000) {
                clearTimeout(autoSaveTimers[key]);
                autoSaveTimers[key] = setTimeout(callback, delay);
            }

            function showAutoSaveIndicator() {
                const indicator = document.createElement("div");
                indicator.textContent = "✓ Auto-saved";
                indicator.className =
                    "fixed top-20 right-4 bg-green-50 text-green-600 px-4 py-2 rounded-lg shadow-lg text-sm font-medium z-50";
                document.body.appendChild(indicator);

                setTimeout(() => {
                    indicator.style.opacity = "0";
                    indicator.style.transition = "opacity 0.3s";
                    setTimeout(() => indicator.remove(), 300);
                }, 2000);
            }

            // Router form auto-save
            function setupRouterAutoSave() {
                console.log("=== setupRouterAutoSave called ===");
                const routerForm = document.getElementById("router-form");
                console.log("Router form:", routerForm);
                if (!routerForm) {
                    console.warn("Router form not found!");
                    return;
                }

                const inputs = routerForm.querySelectorAll(
                    "input, select, textarea",
                );
                console.log(`Found ${inputs.length} inputs in router form`);

                inputs.forEach((input, index) => {
                    console.log(
                        `Setting up listener for input ${index}:`,
                        input.name,
                        input.tagName,
                    );
                    input.addEventListener("change", (e) => {
                        console.log(
                            "=== Change event fired ===",
                            e.target.name,
                            "=",
                            e.target.value,
                        );
                        debounce(
                            "router",
                            () => {
                                console.log(
                                    "=== Router form change detected (after debounce) ===",
                                );
                                const formData = new FormData(routerForm);
                                const defaultModel =
                                    formData.get("default_model");
                                const thinkModel = formData.get("think_model");
                                const backgroundModel =
                                    formData.get("background_model");
                                const websearchModel =
                                    formData.get("websearch_model");

                                console.log("FormData values:", {
                                    default: defaultModel,
                                    think: thinkModel,
                                    background: backgroundModel,
                                    websearch: websearchModel,
                                });

                                if (!defaultModel) return; // Skip if required field is empty

                                // Update router config in state
                                appState.config.router.default = defaultModel;

                                if (thinkModel) {
                                    appState.config.router.think = thinkModel;
                                } else {
                                    delete appState.config.router.think;
                                }

                                if (backgroundModel) {
                                    appState.config.router.background =
                                        backgroundModel;
                                } else {
                                    delete appState.config.router.background;
                                }

                                if (websearchModel) {
                                    appState.config.router.websearch =
                                        websearchModel;
                                } else {
                                    delete appState.config.router.websearch;
                                }

                                console.log(
                                    "Updated appState.config.router:",
                                    appState.config.router,
                                );

                                // Save to localStorage only
                                saveToLocalStorage(appState.config);
                                showAutoSaveIndicator();
                                renderOverview();
                            },
                            500,
                        );
                    });
                });
            }

            function setupSettingsAutoSave() {
                const settingsForm = document.getElementById("settings-form");
                if (!settingsForm) return;

                const inputs = settingsForm.querySelectorAll(
                    "input, select, textarea",
                );
                inputs.forEach((input) => {
                    input.addEventListener("change", () => {
                        debounce(
                            "settings",
                            () => {
                                const autoMapRegex =
                                    document.getElementById(
                                        "auto-map-regex",
                                    ).value;
                                if (autoMapRegex) {
                                    appState.config.router.auto_map_regex =
                                        autoMapRegex;
                                } else {
                                    delete appState.config.router
                                        .auto_map_regex;
                                }

                                const backgroundRegex =
                                    document.getElementById(
                                        "background-regex",
                                    ).value;
                                if (backgroundRegex) {
                                    appState.config.router.background_regex =
                                        backgroundRegex;
                                } else {
                                    delete appState.config.router
                                        .background_regex;
                                }

                                // Save to localStorage only
                                saveToLocalStorage(appState.config);
                                showAutoSaveIndicator();
                                renderOverview();
                            },
                            500,
                        );
                    });
                });
            }

            // Form Handlers
            document
                .getElementById("add-model-form")
                .addEventListener("submit", async function (e) {
                    e.preventDefault();

                    const formData = new FormData(e.target);
                    const modelName = formData.get("model_name")?.trim();

                    // Validation
                    if (!modelName) {
                        notifyError("Please enter a model name.");
                        return;
                    }

                    // Collect all mappings
                    const mappings = [];
                    document
                        .querySelectorAll(".provider-mapping")
                        .forEach((mapping, index) => {
                            const provider = formData
                                .get(`mappings[${index}][provider]`)
                                ?.trim();
                            const actualModel = formData
                                .get(`mappings[${index}][actual_model]`)
                                ?.trim();
                            if (provider && actualModel) {
                                mappings.push({
                                    priority: index + 1,
                                    provider: provider,
                                    actual_model: actualModel,
                                });
                            }
                        });

                    if (mappings.length === 0) {
                        notifyError(
                            "Please add at least one provider mapping.",
                        );
                        return;
                    }

                    const modelData = {
                        name: modelName,
                        mappings: mappings,
                    };

                    try {
                        const isEditing = appState.editingModel !== null;

                        if (isEditing) {
                            // Edit mode
                            const editIndex = appState.editingModel;

                            // Check for duplicate model name (excluding current model)
                            if (
                                appState.config.models &&
                                appState.config.models.some(
                                    (m, idx) =>
                                        idx !== editIndex &&
                                        m.name.toLowerCase() ===
                                            modelName.toLowerCase(),
                                )
                            ) {
                                notifyError(
                                    `A model named "${modelName}" already exists. Please use a different name.`,
                                );
                                return;
                            }

                            // Update model
                            appState.config.models[editIndex] = modelData;
                            saveToLocalStorage(appState.config);

                            notifySuccess("Model updated and auto-saved");
                            appState.editingModel = null;
                            e.target.reset();
                            navigate({ tab: "models", view: null });
                        } else {
                            // Add mode
                            // Check for duplicate model name (case-insensitive)
                            if (
                                appState.config.models &&
                                appState.config.models.some(
                                    (m) =>
                                        m.name.toLowerCase() ===
                                        modelName.toLowerCase(),
                                )
                            ) {
                                notifyError(
                                    `A model named "${modelName}" already exists. Please use a different name.`,
                                );
                                return;
                            }

                            // Add new model to state and save to localStorage only
                            if (!appState.config.models) {
                                appState.config.models = [];
                            }
                            appState.config.models.push(modelData);
                            saveToLocalStorage(appState.config);

                            notifySuccess("Model added and auto-saved");
                            e.target.reset();
                            navigate({ tab: "models", view: null });
                        }
                    } catch (error) {
                        console.error("Failed to save model:", error);
                        notifyError("Failed to save model");
                    }
                });

            document
                .getElementById("add-provider-form")
                .addEventListener("submit", async function (e) {
                    e.preventDefault();

                    const formData = new FormData(e.target);
                    const providerName = formData.get("provider_name")?.trim();
                    const providerType = formData.get("provider_type")?.trim();
                    const authType =
                        formData.get("auth_type")?.trim() || "apikey";
                    const apiKey = formData.get("api_key")?.trim();
                    const baseUrl = formData.get("base_url")?.trim();

                    // Validation
                    if (!providerName) {
                        notifyError("Please enter a provider name.");
                        return;
                    }

                    if (!providerType) {
                        notifyError("Please select a provider type.");
                        return;
                    }

                    // For Vertex AI, validate project_id and location
                    if (providerType === "vertex-ai") {
                        const vertexProjectId = formData
                            .get("vertex_project_id")
                            ?.trim();
                        const vertexLocation = formData
                            .get("vertex_location")
                            ?.trim();

                        if (!vertexProjectId) {
                            notifyError(
                                "Please enter a Google Cloud Project ID for Vertex AI.",
                            );
                            return;
                        }
                        if (!vertexLocation) {
                            notifyError(
                                "Please select a location for Vertex AI.",
                            );
                            return;
                        }
                    }

                    // For API key auth, require API key
                    if (
                        authType === "apikey" &&
                        !apiKey &&
                        providerType !== "vertex-ai"
                    ) {
                        notifyError("Please enter an API key.");
                        return;
                    }

                    // For OAuth, check if token was saved
                    const oauthProviderId =
                        sessionStorage.getItem("oauth_provider_id");
                    if (authType === "oauth" && !oauthProviderId) {
                        notifyError(
                            "Please complete OAuth authentication first.",
                        );
                        return;
                    }

                    const providerData = {
                        name: providerName,
                        provider_type: providerType,
                        models: [], // Empty array - models are defined in model mappings
                        enabled: true,
                    };

                    // Add provider-specific fields
                    if (providerType === "vertex-ai") {
                        // Vertex AI provider
                        providerData.project_id = formData
                            .get("vertex_project_id")
                            ?.trim();
                        providerData.location = formData
                            .get("vertex_location")
                            ?.trim();
                        // No auth_type needed for Vertex AI (uses ADC)
                    } else {
                        // Other providers with auth_type
                        providerData.auth_type = authType;

                        // Add auth-specific fields
                        if (authType === "oauth") {
                            providerData.oauth_provider = oauthProviderId;
                            // For OAuth, api_key is optional (not used)
                        } else {
                            providerData.api_key = apiKey;
                        }

                        if (baseUrl) {
                            providerData.base_url = baseUrl;
                        }
                    }

                    try {
                        const isEditing = appState.editingProvider !== null;

                        if (isEditing) {
                            // Edit mode
                            const editIndex = appState.editingProvider;

                            // Check for duplicate provider name (excluding current provider)
                            if (
                                appState.config.providers &&
                                appState.config.providers.some(
                                    (p, idx) =>
                                        idx !== editIndex &&
                                        p.name.toLowerCase() ===
                                            providerName.toLowerCase(),
                                )
                            ) {
                                notifyError(
                                    `A provider named "${providerName}" already exists. Please use a different name.`,
                                );
                                return;
                            }

                            // Preserve existing models array
                            providerData.models =
                                appState.config.providers[editIndex].models ||
                                [];

                            // Update provider
                            appState.config.providers[editIndex] = providerData;
                            saveToLocalStorage(appState.config);

                            notifySuccess("Provider updated and auto-saved");
                            appState.editingProvider = null;
                            e.target.reset();
                            navigate({ tab: "providers", view: null });
                        } else {
                            // Add mode
                            // Check for duplicate provider name (case-insensitive)
                            if (
                                appState.config.providers &&
                                appState.config.providers.some(
                                    (p) =>
                                        p.name.toLowerCase() ===
                                        providerName.toLowerCase(),
                                )
                            ) {
                                notifyError(
                                    `A provider named "${providerName}" already exists. Please use a different name.`,
                                );
                                return;
                            }

                            // Add new provider to state and save to localStorage only
                            if (!appState.config.providers) {
                                appState.config.providers = [];
                            }
                            appState.config.providers.push(providerData);
                            saveToLocalStorage(appState.config);

                            notifySuccess("Provider added and auto-saved");
                            e.target.reset();
                            navigate({ tab: "providers", view: null });
                        }
                    } catch (error) {
                        console.error("Failed to save provider:", error);
                        notifyError("Failed to save provider");
                    }
                });

            async function restartServer() {
                if (!confirm("Are you sure you want to restart the server?"))
                    return;

                try {
                    await fetch("/api/restart", { method: "POST" });
                    notifySuccess("Server restarted");
                } catch (error) {
                    console.error("Failed to restart server:", error);
                    notifyError("Failed to restart server");
                }
            }

            // Global Actions
            async function saveAllConfig() {
                console.log("Saving all configuration...");

                try {
                    // Sync localStorage to server
                    const success = await syncToServer();

                    if (success) {
                        updateLastSaved();
                        notifySuccess("All settings saved to server");
                        renderOverview();
                    } else {
                        notifyError("Failed to save to server");
                    }
                } catch (error) {
                    console.error("Failed to save all config:", error);
                    notifyError("Failed to save");
                }
            }

            async function saveAndRestart() {
                if (
                    !confirm(
                        "Save settings and Are you sure you want to restart the server?",
                    )
                )
                    return;

                try {
                    await saveAllConfig();
                    setTimeout(async () => {
                        await fetch("/api/restart", { method: "POST" });
                        notifySuccess("Server restarted");
                    }, 500);
                } catch (error) {
                    console.error("Failed to save and restart:", error);
                    notifyError("Failed to save and restart");
                }
            }

            function updateLastSaved() {
                const now = new Date();
                const timeStr = now.toLocaleTimeString("ko-KR", {
                    hour: "2-digit",
                    minute: "2-digit",
                    second: "2-digit",
                });
                document.getElementById("last-saved").textContent = timeStr;
            }

            // ============================================
            // Test Tab Functions
            // ============================================

            function loadTestModels() {
                if (!appState.loaded) return;

                const models = appState.config.models || [];
                const select = document.getElementById("test-model-select");

                // Clear existing options except the first one
                select.innerHTML =
                    '<option value="">Choose a model...</option>';

                // Add models from config
                models.forEach((model) => {
                    const option = document.createElement("option");
                    option.value = model.name;
                    option.textContent = model.name;
                    select.appendChild(option);
                });
            }

            function updateTestProviders() {
                const modelSelect =
                    document.getElementById("test-model-select");
                const providerSelect = document.getElementById(
                    "test-provider-select",
                );
                const providerSelection = document.getElementById(
                    "test-provider-selection",
                );
                const selectedModelName = modelSelect.value;

                if (!selectedModelName || !appState.loaded) {
                    providerSelection.classList.add("hidden");
                    return;
                }

                // Clear provider options
                providerSelect.innerHTML =
                    '<option value="">Use default routing...</option>';

                // Find the model config
                const modelConfig = appState.config.models.find(
                    (m) => m.name === selectedModelName,
                );

                if (
                    modelConfig &&
                    modelConfig.mappings &&
                    modelConfig.mappings.length > 0
                ) {
                    // Sort by priority and add providers from mappings
                    const sortedMappings = [...modelConfig.mappings].sort(
                        (a, b) => a.priority - b.priority,
                    );

                    sortedMappings.forEach((mapping) => {
                        const option = document.createElement("option");
                        option.value = mapping.provider;
                        option.textContent = `${mapping.provider} (${mapping.actual_model}) - Priority ${mapping.priority}`;
                        providerSelect.appendChild(option);
                    });
                    providerSelection.classList.remove("hidden");
                } else {
                    providerSelection.classList.add("hidden");
                }
            }

            async function sendTestMessage() {
                const modelSelect =
                    document.getElementById("test-model-select");
                const providerSelect = document.getElementById(
                    "test-provider-select",
                );
                const messageInput =
                    document.getElementById("test-message-input");
                const maxTokens = parseInt(
                    document.getElementById("test-max-tokens").value,
                );
                const temperature = parseFloat(
                    document.getElementById("test-temperature").value,
                );
                const stream = document.getElementById("test-stream").checked;

                const model = modelSelect.value;
                const provider = providerSelect.value;
                const message = messageInput.value.trim();

                // Validation
                if (!model) {
                    notifyError("Please select a model");
                    return;
                }

                if (!message) {
                    notifyError("Please enter a message");
                    return;
                }

                // Show response container and loading state
                const responseContainer = document.getElementById(
                    "test-response-container",
                );
                const loadingDiv = document.getElementById("test-loading");
                const contentDiv = document.getElementById(
                    "test-response-content",
                );
                const errorDiv = document.getElementById("test-error");

                responseContainer.classList.remove("hidden");
                loadingDiv.classList.remove("hidden");
                contentDiv.classList.add("hidden");
                errorDiv.classList.add("hidden");

                // Disable send button
                const sendBtn = document.getElementById("test-send-btn");
                sendBtn.disabled = true;
                sendBtn.textContent = "Sending...";

                const startTime = Date.now();

                try {
                    const headers = {
                        "Content-Type": "application/json",
                        "anthropic-version": "2023-06-01",
                    };

                    // Add provider header if selected
                    if (provider) {
                        headers["X-Provider"] = provider;
                    }

                    const response = await fetch("/v1/messages", {
                        method: "POST",
                        headers: headers,
                        body: JSON.stringify({
                            model: model,
                            max_tokens: maxTokens,
                            temperature: temperature,
                            stream: stream,
                            messages: [
                                {
                                    role: "user",
                                    content: message,
                                },
                            ],
                        }),
                    });

                    const endTime = Date.now();
                    const duration = ((endTime - startTime) / 1000).toFixed(2);

                    if (!response.ok) {
                        const errorData = await response.json();
                        throw new Error(
                            errorData.error?.message ||
                                `HTTP ${response.status}`,
                        );
                    }

                    if (stream) {
                        // Handle streaming response
                        await handleStreamingResponse(response, duration);
                    } else {
                        // Handle regular response
                        const data = await response.json();
                        displayTestResponse(data, duration);
                    }
                } catch (error) {
                    console.error("Test message error:", error);
                    loadingDiv.classList.add("hidden");
                    errorDiv.classList.remove("hidden");
                    document.getElementById("test-error-message").textContent =
                        error.message;
                } finally {
                    sendBtn.disabled = false;
                    sendBtn.textContent = "Send Message";
                }
            }

            async function handleStreamingResponse(response, duration) {
                const loadingDiv = document.getElementById("test-loading");
                const contentDiv = document.getElementById(
                    "test-response-content",
                );
                const responseText =
                    document.getElementById("test-response-text");

                loadingDiv.classList.add("hidden");
                contentDiv.classList.remove("hidden");
                responseText.textContent = "";

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let fullText = "";
                let inputTokens = 0;
                let outputTokens = 0;

                try {
                    while (true) {
                        const { done, value } = await reader.read();
                        if (done) break;

                        const chunk = decoder.decode(value);
                        const lines = chunk.split("\n");

                        for (const line of lines) {
                            if (line.startsWith("data: ")) {
                                const data = line.slice(6);
                                if (data === "[DONE]") continue;

                                try {
                                    const event = JSON.parse(data);

                                    if (event.type === "content_block_delta") {
                                        const text = event.delta?.text || "";
                                        fullText += text;
                                        responseText.textContent = fullText;
                                    } else if (event.type === "message_start") {
                                        inputTokens =
                                            event.message?.usage
                                                ?.input_tokens || 0;
                                    } else if (event.type === "message_delta") {
                                        outputTokens =
                                            event.usage?.output_tokens || 0;
                                    }
                                } catch (e) {
                                    // Ignore parse errors for partial chunks
                                }
                            }
                        }
                    }

                    // Update metadata
                    document.getElementById("test-response-time").textContent =
                        `${duration}s`;
                    document.getElementById("test-input-tokens").textContent =
                        inputTokens;
                    document.getElementById("test-output-tokens").textContent =
                        outputTokens;
                    document.getElementById("test-stop-reason").textContent =
                        "end_turn";
                    document.getElementById("test-response-model").textContent =
                        document.getElementById("test-model-select").value;
                } catch (error) {
                    console.error("Streaming error:", error);
                    throw error;
                }
            }

            function displayTestResponse(data, duration) {
                const loadingDiv = document.getElementById("test-loading");
                const contentDiv = document.getElementById(
                    "test-response-content",
                );

                loadingDiv.classList.add("hidden");
                contentDiv.classList.remove("hidden");

                // Extract text content
                const textContent = data.content
                    .filter((c) => c.type === "text")
                    .map((c) => c.text)
                    .join("\n");

                document.getElementById("test-response-text").textContent =
                    textContent;
                document.getElementById("test-response-time").textContent =
                    `${duration}s`;
                document.getElementById("test-input-tokens").textContent =
                    data.usage?.input_tokens || "-";
                document.getElementById("test-output-tokens").textContent =
                    data.usage?.output_tokens || "-";
                document.getElementById("test-stop-reason").textContent =
                    data.stop_reason || "-";
                document.getElementById("test-response-model").textContent =
                    data.model || "-";
            }

            function clearTestResponse() {
                document.getElementById("test-message-input").value = "";
                document
                    .getElementById("test-response-container")
                    .classList.add("hidden");
                document.getElementById("test-response-text").textContent = "";
            }

            // OAuth Functions
            function updateOAuthLabel() {
                const providerType = document.querySelector(
                    'input[name="provider_type"]:checked',
                )?.value;
                const oauthLabel = document.getElementById("oauth-label-title");
                const oauthDescription = document.getElementById(
                    "oauth-label-description",
                );
                const step1Instruction = document.getElementById(
                    "oauth-step1-instruction",
                );
                const step2Instructions = document.getElementById(
                    "oauth-step2-instructions",
                );

                const vertexAiConfig =
                    document.getElementById("vertex-ai-config");
                const authTypeSelector =
                    document.getElementById("auth-type-selector");
                const authCardTitle =
                    document.getElementById("auth-card-title");

                // Show/hide Vertex AI config based on provider type
                const vertexProjectIdField = document.getElementById("vertex-project-id");
                const vertexLocationField = document.getElementById("vertex-location");

                if (providerType === "vertex-ai") {
                    vertexAiConfig.classList.remove("hidden");
                    authTypeSelector.classList.add("hidden");
                    authCardTitle.textContent = "Vertex AI Configuration";

                    // Add required attributes for Vertex AI
                    if (vertexProjectIdField) vertexProjectIdField.setAttribute("required", "required");
                    if (vertexLocationField) vertexLocationField.setAttribute("required", "required");

                    return; // Skip OAuth label updates
                } else {
                    vertexAiConfig.classList.add("hidden");
                    authTypeSelector.classList.remove("hidden");
                    authCardTitle.textContent = "Choose authentication method";

                    // Remove required attributes when not Vertex AI
                    if (vertexProjectIdField) vertexProjectIdField.removeAttribute("required");
                    if (vertexLocationField) vertexLocationField.removeAttribute("required");
                }

                if (providerType === "openai") {
                    oauthLabel.textContent = "OAuth (ChatGPT Plus/Pro)";
                    oauthDescription.textContent =
                        "Free for ChatGPT Plus/Pro subscribers";
                    step1Instruction.textContent =
                        "Click the button below to authenticate with your ChatGPT Plus/Pro account.";
                    step2Instructions.innerHTML = `
                        <li>Log in to your ChatGPT Plus/Pro account</li>
                        <li>Click "Allow" to authorize</li>
                        <li>Copy the authorization code</li>
                        <li>Paste it in the field below</li>
                    `;
                } else if (providerType === "gemini") {
                    oauthLabel.textContent = "OAuth (Google AI Pro/Ultra)";
                    oauthDescription.textContent =
                        "Free for Google AI Pro/Ultra subscribers";
                    step1Instruction.textContent =
                        "Click the button below to authenticate with your Google account (AI Pro/Ultra).";
                    step2Instructions.innerHTML = `
                        <li>Log in to your Google account</li>
                        <li>Click "Allow" to authorize</li>
                        <li>Copy the authorization code</li>
                        <li>Paste it in the field below</li>
                    `;
                } else {
                    oauthLabel.textContent = "OAuth (Claude Pro/Max)";
                    oauthDescription.textContent =
                        "Free for Claude Max subscribers";
                    step1Instruction.textContent =
                        "Click the button below to authenticate with your Claude Pro/Max account.";
                    step2Instructions.innerHTML = `
                        <li>Log in to your Claude Pro/Max account</li>
                        <li>Click "Allow" to authorize</li>
                        <li>Copy the authorization code</li>
                        <li>Paste it in the field below</li>
                    `;
                }
            }

            function toggleAuthMethod() {
                const authType = document.querySelector(
                    'input[name="auth_type"]:checked',
                ).value;
                const apiKeySection =
                    document.getElementById("api-key-section");
                const oauthSection = document.getElementById("oauth-section");
                const apiKeyInput = document.getElementById("api-key-input");

                if (authType === "oauth") {
                    apiKeySection.classList.add("hidden");
                    oauthSection.classList.remove("hidden");
                    apiKeyInput.removeAttribute("required");

                    // Reset OAuth UI to step 1
                    document
                        .getElementById("oauth-step-1")
                        .classList.remove("hidden");
                    document
                        .getElementById("oauth-step-2")
                        .classList.add("hidden");
                    document
                        .getElementById("oauth-step-3")
                        .classList.add("hidden");
                    document.getElementById("oauth-code-input").value = "";
                } else {
                    apiKeySection.classList.remove("hidden");
                    oauthSection.classList.add("hidden");
                    apiKeyInput.setAttribute("required", "required");
                }
            }

            async function loadOAuthTokens() {
                const loadingEl = document.getElementById(
                    "oauth-tokens-loading",
                );
                const listEl = document.getElementById("oauth-tokens-list");
                const emptyEl = document.getElementById("oauth-tokens-empty");

                try {
                    const response = await fetch("/api/oauth/tokens");
                    if (!response.ok) {
                        throw new Error("Failed to load OAuth tokens");
                    }

                    const tokens = await response.json();

                    loadingEl.classList.add("hidden");

                    if (tokens.length === 0) {
                        emptyEl.classList.remove("hidden");
                        listEl.classList.add("hidden");
                    } else {
                        emptyEl.classList.add("hidden");
                        listEl.classList.remove("hidden");

                        // Render tokens
                        listEl.innerHTML = tokens
                            .map((token) => {
                                const expiresAt = new Date(token.expires_at);
                                const now = new Date();
                                const isExpired = expiresAt <= now;
                                const needsRefresh = token.needs_refresh;

                                return `
                                <div class="border-2 ${isExpired ? "border-red-200 bg-red-50" : needsRefresh ? "border-yellow-200 bg-yellow-50" : "border-green-200 bg-green-50"} rounded-xl p-4">
                                    <div class="flex items-start justify-between">
                                        <div class="flex-1">
                                            <div class="flex items-center gap-2 mb-2">
                                                <h3 class="font-bold">${escapeHtml(token.provider_id)}</h3>
                                                ${isExpired ? '<span class="px-2 py-1 bg-red-100 text-red-700 rounded-full text-xs font-semibold">Expired</span>' : needsRefresh ? '<span class="px-2 py-1 bg-yellow-100 text-yellow-700 rounded-full text-xs font-semibold">Needs Refresh</span>' : '<span class="px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs font-semibold">Active</span>'}
                                            </div>
                                            <div class="text-sm text-gray-600">
                                                Expires: ${expiresAt.toLocaleString()}
                                            </div>
                                        </div>
                                        <div class="flex gap-2">
                                            <button
                                                class="px-3 py-1 bg-blue-100 text-blue-700 rounded-lg text-sm font-semibold hover:bg-blue-200 transition-all"
                                                onclick="refreshOAuthToken('${escapeHtml(token.provider_id)}')"
                                            >
                                                Refresh
                                            </button>
                                            <button
                                                class="px-3 py-1 bg-red-100 text-red-700 rounded-lg text-sm font-semibold hover:bg-red-200 transition-all"
                                                onclick="deleteOAuthToken('${escapeHtml(token.provider_id)}')"
                                            >
                                                Delete
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            `;
                            })
                            .join("");
                    }
                } catch (error) {
                    console.error("Failed to load OAuth tokens:", error);
                    loadingEl.innerHTML =
                        '<div class="text-red-600">Failed to load OAuth tokens</div>';
                }
            }

            async function refreshOAuthToken(providerId) {
                try {
                    const response = await fetch("/api/oauth/tokens/refresh", {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({ provider_id: providerId }),
                    });

                    if (!response.ok) {
                        throw new Error("Failed to refresh token");
                    }

                    notifySuccess(`Token refreshed for ${providerId}`);
                    await loadOAuthTokens(); // Reload tokens list
                } catch (error) {
                    console.error("Failed to refresh token:", error);
                    notifyError(`Failed to refresh token: ${error.message}`);
                }
            }

            async function deleteOAuthToken(providerId) {
                if (
                    !confirm(
                        `Are you sure you want to delete the OAuth token for "${providerId}"?`,
                    )
                ) {
                    return;
                }

                try {
                    const response = await fetch("/api/oauth/tokens/delete", {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({ provider_id: providerId }),
                    });

                    if (!response.ok) {
                        throw new Error("Failed to delete token");
                    }

                    notifySuccess(`OAuth token deleted for ${providerId}`);
                    await loadOAuthTokens(); // Reload tokens list
                } catch (error) {
                    console.error("Failed to delete token:", error);
                    notifyError(`Failed to delete token: ${error.message}`);
                }
            }

            async function startOAuthFlow() {
                try {
                    // Determine oauth_type based on provider type
                    const providerType = document.querySelector(
                        'input[name="provider_type"]:checked',
                    )?.value;
                    let oauth_type = "max"; // default to anthropic max

                    if (providerType === "openai") {
                        oauth_type = "openai-codex";
                    } else if (providerType === "gemini") {
                        oauth_type = "gemini";
                    }

                    // Update instruction text based on provider type
                    const instructionEl = document.getElementById(
                        "oauth-step1-instruction",
                    );
                    if (providerType === "gemini") {
                        instructionEl.innerHTML = `
                            <p class="mb-2">Click the button below to authenticate with your Google account.</p>
                            <div class="bg-yellow-50 border-l-4 border-yellow-400 p-3 mt-2">
                                <p class="text-sm text-yellow-800">
                                    <strong> Google Cloud Project ID:</strong><br>
                                     <strong>Individual accounts</strong>: No project ID needed<br>
                                     <strong>Workspace/licensed users</strong>: Set <code class="bg-yellow-100 px-1">GOOGLE_CLOUD_PROJECT</code> environment variable before starting server
                                </p>
                            </div>
                        `;
                    }

                    // Step 1: Get authorization URL
                    const response = await fetch("/api/oauth/authorize", {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({ oauth_type }),
                    });

                    if (!response.ok) {
                        throw new Error("Failed to get authorization URL");
                    }

                    const data = await response.json();
                    const { url, verifier } = data;

                    // Store verifier and oauth_type for later use
                    console.log("🔐 Storing OAuth verifier:", verifier);
                    console.log("🔐 Storing OAuth type:", oauth_type);
                    sessionStorage.setItem("oauth_verifier", verifier);
                    sessionStorage.setItem("oauth_type", oauth_type);

                    // Step 2: Open authorization URL in new window
                    window.open(
                        url,
                        "OAuth Authorization",
                        "width=600,height=800",
                    );

                    // Update step 2 instructions based on provider type
                    const step2InstructionsEl = document.getElementById(
                        "oauth-step2-instructions",
                    );
                    if (providerType === "gemini") {
                        step2InstructionsEl.innerHTML = `
                            <li>Log in to your Google account</li>
                            <li>Click "Allow" to authorize</li>
                            <li>Copy the authorization code</li>
                            <li>Paste it in the field below</li>
                        `;
                    } else if (providerType === "openai") {
                        step2InstructionsEl.innerHTML = `
                            <li>Log in to your ChatGPT Plus/Pro account</li>
                            <li>Click "Allow" to authorize</li>
                            <li>Copy the authorization code</li>
                            <li>Paste it in the field below</li>
                        `;
                    } else {
                        step2InstructionsEl.innerHTML = `
                            <li>Log in to your Claude Pro/Max account</li>
                            <li>Click "Allow" to authorize</li>
                            <li>Copy the authorization code</li>
                            <li>Paste it in the field below</li>
                        `;
                    }

                    // Step 3: Show code input UI
                    document
                        .getElementById("oauth-step-1")
                        .classList.add("hidden");
                    document
                        .getElementById("oauth-step-2")
                        .classList.remove("hidden");

                    notifySuccess(
                        "Authorization window opened. Please complete authentication and paste the code.",
                    );
                } catch (error) {
                    console.error("OAuth flow error:", error);
                    notifyError(`Failed to start OAuth: ${error.message}`);
                }
            }

            async function completeOAuthFlow() {
                try {
                    const code = document
                        .getElementById("oauth-code-input")
                        .value.trim();

                    if (!code) {
                        notifyError("Please paste the authorization code");
                        return;
                    }

                    const verifier = sessionStorage.getItem("oauth_verifier");
                    if (!verifier) {
                        throw new Error(
                            "OAuth verifier not found. Please start the flow again.",
                        );
                    }

                    const oauthType = sessionStorage.getItem("oauth_type");
                    if (!oauthType) {
                        throw new Error(
                            "OAuth type not found. Please start the flow again.",
                        );
                    }

                    // Exchange code for tokens
                    const providerName =
                        document.querySelector('input[name="provider_name"]')
                            .value || "claude-max";
                    // Use provider name directly as the OAuth identifier (no -oauth suffix)
                    const providerId = providerName;

                    console.log(
                        "🔐 Exchanging code with oauth_type:",
                        oauthType,
                    );
                    console.log("🔐 Provider ID:", providerId);

                    const exchangeResponse = await fetch(
                        "/api/oauth/exchange",
                        {
                            method: "POST",
                            headers: { "Content-Type": "application/json" },
                            body: JSON.stringify({
                                code: code,
                                verifier: verifier,
                                provider_id: providerId,
                                oauth_type: oauthType,
                            }),
                        },
                    );

                    if (!exchangeResponse.ok) {
                        const error = await exchangeResponse.text();
                        throw new Error(`Failed to exchange code: ${error}`);
                    }

                    const tokenData = await exchangeResponse.json();

                    // Show success
                    document
                        .getElementById("oauth-step-2")
                        .classList.add("hidden");
                    document
                        .getElementById("oauth-step-3")
                        .classList.remove("hidden");
                    sessionStorage.setItem("oauth_provider_id", providerId);

                    notifySuccess(
                        `OAuth authentication successful! Token saved for ${providerId}`,
                    );
                } catch (error) {
                    console.error("OAuth completion error:", error);
                    notifyError(`Authentication failed: ${error.message}`);
                }
            }

            function cancelOAuthFlow() {
                // Reset to initial state
                document.getElementById("oauth-step-2").classList.add("hidden");
                document
                    .getElementById("oauth-step-1")
                    .classList.remove("hidden");
                document.getElementById("oauth-code-input").value = "";
                sessionStorage.removeItem("oauth_verifier");
                notifySuccess("OAuth flow canceled");
            }

            // Initialize
            window.addEventListener("DOMContentLoaded", async () => {
                await loadConfig();
                handleRoute();
                renderOverview();
                updateLastSaved();
                loadTestModels();
                setupRouterAutoSave();
                setupSettingsAutoSave();

                // Setup provider type change listeners to update OAuth label
                const providerTypeInputs = document.querySelectorAll(
                    'input[name="provider_type"]',
                );
                providerTypeInputs.forEach((input) => {
                    input.addEventListener("change", updateOAuthLabel);
                });

                // Initialize OAuth label based on current selection
                updateOAuthLabel();
            });

            // Handle browser back/forward buttons
            window.addEventListener("popstate", handleRoute);
        </script>
    </body>
</html>