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
<!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://unpkg.com/franken-ui@latest/dist/css/slate.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">
                <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>
                    </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 All
                    </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>

                <!-- 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"
                                                >활성화</span
                                            >
                                        </div>
                                        <p class="text-gray-600 mb-4">
                                            anthropic-native
                                        </p>
                                        <div class="text-sm text-gray-500">
                                            3개 모델 • API 키 등록됨
                                        </div>
                                    </div>
                                    <div class="flex gap-2">
                                        <button class="btn-secondary">
                                            수정
                                        </button>
                                        <button
                                            class="btn-secondary text-red-600"
                                        >
                                            삭제
                                        </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">
                                    연결된 Provider가 없어요
                                </h3>
                                <p class="text-gray-600 mb-6">
                                    Provider를 추가하면 더 많은 AI 모델을 사용할
                                    수 있어요
                                </p>
                                <button
                                    onclick="showAddProvider()"
                                    class="btn-primary"
                                >
                                    첫 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"
                        >
                            ← Provider 목록으로
                        </button>

                        <h1 class="text-4xl font-bold mb-3">Provider 추가</h1>
                        <p class="text-gray-600 text-lg mb-12">
                            API 키를 입력하면 바로 사용할 수 있어요
                        </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">
                                    어떤 Provider를 추가하시나요?
                                </h2>
                                <div class="grid grid-cols-2 gap-4">
                                    <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 모델
                                            </div>
                                        </div>
                                    </label>
                                    <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 모델
                                            </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">
                                                통합 라우터
                                            </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">
                                                국내 모델
                                            </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">
                                                중국 모델
                                            </div>
                                        </div>
                                    </label>
                                </div>
                            </div>

                            <!-- Step 2: Basic Info -->
                            <div class="card">
                                <h2 class="text-2xl font-bold mb-8">
                                    Provider 이름을 정해주세요
                                </h2>
                                <div>
                                    <label class="label">이름</label>
                                    <input
                                        type="text"
                                        name="provider_name"
                                        class="input-field"
                                        placeholder="예: anthropic-main"
                                        required
                                    />
                                    <div class="helper-text">
                                        Provider를 구분할 수 있는 이름이에요
                                    </div>
                                </div>
                            </div>

                            <!-- Step 3: API Key -->
                            <div class="card">
                                <h2 class="text-2xl font-bold mb-8">
                                    API 키를 입력해주세요
                                </h2>
                                <div>
                                    <label class="label">API Key</label>
                                    <input
                                        type="password"
                                        name="api_key"
                                        class="input-field font-mono"
                                        placeholder="sk-ant-..."
                                        required
                                    />
                                    <div class="helper-text">
                                        API 키는 안전하게 보관돼요
                                    </div>
                                </div>
                            </div>

                            <!-- Step 4: Optional -->
                            <div class="card">
                                <h2 class="text-2xl font-bold mb-4">
                                    추가 설정
                                </h2>
                                <p class="text-gray-600 mb-8">
                                    필요한 경우만 입력하세요
                                </p>
                                <div>
                                    <label class="label"
                                        >커스텀 엔드포인트 (선택)</label
                                    >
                                    <input
                                        type="url"
                                        name="base_url"
                                        class="input-field font-mono"
                                        placeholder="https://api.anthropic.com"
                                    />
                                    <div class="helper-text">
                                        기본 엔드포인트 대신 다른 URL을 사용하고
                                        싶을 때만 입력하세요
                                    </div>
                                </div>
                            </div>

                            <div class="flex gap-4">
                                <button
                                    type="button"
                                    onclick="showProvidersList()"
                                    class="btn-secondary flex-1"
                                >
                                    취소
                                </button>
                                <button
                                    type="submit"
                                    class="btn-primary flex-1"
                                >
                                    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">모델 관리</h1>
                        <p class="text-gray-600 text-lg mb-12">
                            여러 Provider로 안정성을 높이세요
                        </p>

                        <button
                            onclick="showAddModel()"
                            class="btn-primary mb-8"
                        >
                            새 모델 추가하기
                        </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-2">
                                            claude-sonnet-4-5
                                        </h3>
                                        <p class="text-sm text-gray-600 mb-4">
                                            외부에 노출되는 모델 이름
                                        </p>
                                        <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"
                                                    >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"
                                                    >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">
                                            수정
                                        </button>
                                        <button
                                            class="btn-secondary text-red-600"
                                        >
                                            삭제
                                        </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">
                                    등록된 모델이 없어요
                                </h3>
                                <p class="text-gray-600 mb-6">
                                    모델을 추가하면 API를 통해 사용할 수 있어요
                                </p>
                                <button
                                    onclick="showAddModel()"
                                    class="btn-primary"
                                >
                                    첫 모델 추가하기
                                </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"
                        >
                            ← 모델 목록으로
                        </button>

                        <h1 class="text-4xl font-bold mb-3">모델 추가</h1>
                        <p class="text-gray-600 text-lg mb-12">
                            여러 Provider를 설정해 안정성을 높일 수 있어요
                        </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">
                                    외부에 노출할 모델 이름을 정해주세요
                                </h2>
                                <div>
                                    <label class="label">모델 이름</label>
                                    <input
                                        type="text"
                                        name="model_name"
                                        class="input-field font-mono"
                                        placeholder="예: claude-sonnet-4-5"
                                        required
                                    />
                                    <div class="helper-text">
                                        API 요청 시 이 이름으로 사용하게 돼요
                                    </div>
                                </div>
                            </div>

                            <!-- Step 2: Provider Mappings -->
                            <div class="card">
                                <h2 class="text-2xl font-bold mb-4">
                                    Provider와 실제 모델을 연결하세요
                                </h2>
                                <p class="text-gray-600 mb-8">
                                    순서대로 시도하며, 실패 시 다음 Provider로
                                    자동 전환돼요
                                </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"
                                                    >1순위</span
                                                >
                                                <span
                                                    class="text-blue-600 font-semibold"
                                                    >Primary</span
                                                >
                                            </div>
                                        </div>
                                        <div class="space-y-4">
                                            <div>
                                                <label class="label"
                                                    >Provider 선택</label
                                                >
                                                <select
                                                    name="mappings[0][provider]"
                                                    class="input-field"
                                                    required
                                                >
                                                    <option value="">
                                                        Provider를 선택하세요
                                                    </option>
                                                    <option value="anthropic">
                                                        Anthropic
                                                    </option>
                                                    <option value="openrouter">
                                                        OpenRouter
                                                    </option>
                                                    <option value="openai">
                                                        OpenAI
                                                    </option>
                                                </select>
                                            </div>
                                            <div>
                                                <label class="label"
                                                    >실제 모델명</label
                                                >
                                                <input
                                                    type="text"
                                                    name="mappings[0][actual_model]"
                                                    class="input-field font-mono"
                                                    placeholder="예: claude-sonnet-4-5 또는 anthropic/claude-sonnet-4-5"
                                                    required
                                                />
                                                <div class="helper-text">
                                                    Provider에서 사용하는 실제
                                                    모델 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 추가
                                </button>
                            </div>

                            <div class="flex gap-4">
                                <button
                                    type="button"
                                    onclick="showModelsList()"
                                    class="btn-secondary flex-1"
                                >
                                    취소
                                </button>
                                <button
                                    type="submit"
                                    class="btn-primary flex-1"
                                >
                                    모델 추가하기
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Router Tab -->
                <div id="content-router" class="tab-content hidden">
                    <h1 class="text-4xl font-bold mb-3">라우터 설정</h1>
                    <p class="text-gray-600 text-lg mb-12">
                        상황에 따라 다른 모델을 사용하도록 설정하세요
                    </p>

                    <form id="router-form" class="space-y-6">
                        <div class="card">
                            <h2 class="text-xl font-bold mb-6">기본 모델</h2>
                            <p class="text-gray-600 mb-6">
                                대부분의 요청에 사용될 모델이에요
                            </p>
                            <select
                                name="default_model"
                                class="input-field"
                                required
                            >
                                <option value="">모델을 선택하세요</option>
                            </select>
                        </div>

                        <div class="card">
                            <h2 class="text-xl font-bold mb-6">사고 모델</h2>
                            <p class="text-gray-600 mb-6">
                                복잡한 추론이 필요할 때 사용할 모델이에요
                            </p>
                            <select name="think_model" class="input-field">
                                <option value="">사용 안 함</option>
                            </select>
                        </div>

                        <div class="card">
                            <h2 class="text-xl font-bold mb-6">
                                백그라운드 모델
                            </h2>
                            <p class="text-gray-600 mb-6">
                                간단한 작업에 사용할 빠른 모델이에요
                            </p>
                            <select name="background_model" class="input-field">
                                <option value="">사용 안 함</option>
                            </select>
                        </div>

                        <div class="card">
                            <h2 class="text-xl font-bold mb-6">웹검색 모델</h2>
                            <p class="text-gray-600 mb-6">
                                웹 검색이 필요할 때 사용할 모델이에요
                            </p>
                            <select name="websearch_model" class="input-field">
                                <option value="">사용 안 함</option>
                            </select>
                        </div>

                        <div class="flex gap-4">
                            <button type="submit" class="btn-primary flex-1">
                                저장
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Settings Tab -->
                <div id="content-settings" class="tab-content hidden">
                    <h1 class="text-4xl font-bold mb-3">설정</h1>
                    <p class="text-gray-600 text-lg mb-12">
                        서버 설정을 관리하세요
                    </p>

                    <form id="settings-form" class="space-y-6">
                        <div class="flex gap-4">
                            <button
                                type="button"
                                onclick="restartServer()"
                                class="btn-primary flex-1"
                            >
                                서버 재시작
                            </button>
                        </div>
                    </form>
                </div>
            </main>
        </div>

        <!-- UIkit - Load before our scripts -->
        <script src="https://cdn.jsdelivr.net/npm/uikit@dev/dist/js/uikit.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/uikit@dev/dist/js/uikit-icons.min.js"></script>

        <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("설정을 불러오는데 실패했습니다");
                    return null;
                }
            }

            // Sync localStorage to server (only called by save buttons)
            async function syncToServer() {
                try {
                    const response = await fetch("/api/config/json", {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify(appState.config),
                    });
                    if (response.ok) {
                        saveToLocalStorage(appState.config);
                    }
                    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();
                    }
                }
            }

            // 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}`;
                        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 ? "활성화" : "비활성화"}
                                    </span>
                                </div>
                                <p class="text-gray-600 mb-4">${escapeHtml(provider.provider_type)}</p>
                                <div class="text-sm text-gray-500">
                                    API  
                                </div>
                            </div>
                            <div class="flex gap-2">
                                <button class="btn-secondary" onclick="editProvider(${index})"></button>
                                <button class="btn-secondary text-red-600" onclick="deleteProvider(${index})"></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}`;
                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 ? "활성화" : "비활성화"}
                            </span>
                        </div>
                        <p class="text-gray-600 mb-4">${escapeHtml(provider.provider_type)}</p>
                        <div class="text-sm text-gray-500">
                            API  
                        </div>
                    </div>
                    <div class="flex gap-2">
                        <button class="btn-secondary" onclick="editProvider(${index})"></button>
                        <button class="btn-secondary text-red-600" onclick="deleteProvider(${index})"></button>
                    </div>
                </div>
            `;
                providersList.insertBefore(providerCard, emptyState);
            }

            async function deleteProvider(index) {
                if (!confirm("정말로 이 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가 삭제되었어요 (저장 버튼을 눌러 적용하세요)",
                    );
                } catch (error) {
                    console.error("Failed to delete provider:", error);
                    card.classList.remove("fade-out");
                    notifyError("Provider 삭제에 실패했습니다");
                }
            }

            function editProvider(index) {
                if (!appState.loaded || !appState.config.providers[index]) {
                    notifyError("Provider를 찾을 수 없습니다");
                    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;
                    }

                    form.querySelector('[name="provider_name"]').value = provider.name;
                    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 수정';
                    document.querySelector('#providers-add-view > p').textContent = 'Provider 정보를 수정하세요';
                    const submitBtn = form.querySelector('button[type="submit"]');
                    if (submitBtn) {
                        submitBtn.textContent = '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 추가';
                    document.querySelector('#providers-add-view > p').textContent = 'API 키를 입력하면 바로 사용할 수 있어요';
                    const form = document.getElementById("add-provider-form");
                    if (form) {
                        form.reset();
                        const submitBtn = form.querySelector('button[type="submit"]');
                        if (submitBtn) {
                            submitBtn.textContent = '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">${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-2">${escapeHtml(model.name)}</h3>
                                    <p class="text-sm text-gray-600 mb-4">   </p>
                                    <div class="space-y-2">
                                        ${mappingsHtml}
                                    </div>
                                </div>
                                <div class="flex gap-2">
                                    <button class="btn-secondary" onclick="editModel(${index})"></button>
                                    <button class="btn-secondary text-red-600" onclick="deleteModel(${index})"></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">${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-2">${escapeHtml(model.name)}</h3>
                        <p class="text-sm text-gray-600 mb-4">   </p>
                        <div class="space-y-2">
                            ${mappingsHtml}
                        </div>
                    </div>
                    <div class="flex gap-2">
                        <button class="btn-secondary" onclick="editModel(${index})"></button>
                        <button class="btn-secondary text-red-600" onclick="deleteModel(${index})"></button>
                    </div>
                </div>
            `;
                modelsList.insertBefore(modelCard, emptyState);
            }

            async function deleteModel(index) {
                if (!confirm("정말로 이 모델을 삭제하시겠습니까?")) {
                    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(
                        "모델이 삭제되었어요 (저장 버튼을 눌러 적용하세요)",
                    );
                } catch (error) {
                    console.error("Failed to delete model:", error);
                    card.classList.remove("fade-out");
                    notifyError("모델 삭제에 실패했습니다");
                }
            }

            function editModel(index) {
                if (!appState.loaded || !appState.config.models[index]) {
                    notifyError("모델을 찾을 수 없습니다");
                    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">1</span>
                                        <span class="text-blue-600 font-semibold">Primary</span>
                                    </div>
                                </div>
                                <div class="space-y-4">
                                    <div>
                                        <label class="label">Provider </label>
                                        <select name="mappings[${index}][provider]" class="input-field" required>
                                            <option value="">Provider </option>
                                            ${providerOptions}
                                        </select>
                                    </div>
                                    <div>
                                        <label class="label"> </label>
                                        <input type="text" name="mappings[${index}][actual_model]" class="input-field font-mono" value="${escapeHtml(mapping.actual_model)}" placeholder=": claude-sonnet-4-5  anthropic/claude-sonnet-4-5" required>
                                        <div class="helper-text">Provider    ID</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">${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">Provider </label>
                                        <select name="mappings[${index}][provider]" class="input-field" required>
                                            <option value="">Provider </option>
                                            ${providerOptions}
                                        </select>
                                    </div>
                                    <div>
                                        <label class="label"> </label>
                                        <input type="text" name="mappings[${index}][actual_model]" class="input-field font-mono" value="${escapeHtml(mapping.actual_model)}" placeholder=": claude-sonnet-4-5  anthropic/claude-sonnet-4-5" required>
                                        <div class="helper-text">Provider    ID</div>
                                    </div>
                                </div>
                            `;
                        }

                        mappingsContainer.appendChild(mappingDiv);
                    });

                    // Update UI labels
                    document.querySelector('#models-add-view h1').textContent = '모델 수정';
                    document.querySelector('#models-add-view > p').textContent = '모델 정보를 수정하세요';
                    const submitBtn = form.querySelector('button[type="submit"]');
                    if (submitBtn) {
                        submitBtn.textContent = '모델 수정하기';
                    }
                }, 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">1</span>
                            <span class="text-blue-600 font-semibold">Primary</span>
                        </div>
                    </div>
                    <div class="space-y-4">
                        <div>
                            <label class="label">Provider </label>
                            <select name="mappings[0][provider]" class="input-field" required>
                                <option value="">Provider </option>
                                ${providerOptions}
                            </select>
                        </div>
                        <div>
                            <label class="label"> </label>
                            <input type="text" name="mappings[0][actual_model]" class="input-field font-mono" placeholder=": claude-sonnet-4-5  anthropic/claude-sonnet-4-5" required>
                            <div class="helper-text">Provider    ID</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 = '모델 추가';
                    document.querySelector('#models-add-view > p').textContent = '등록된 Provider를 선택하여 모델을 만드세요';
                    const form = document.getElementById("add-model-form");
                    if (form) {
                        form.reset();
                        const submitBtn = form.querySelector('button[type="submit"]');
                        if (submitBtn) {
                            submitBtn.textContent = '모델 추가하기';
                        }
                    }
                    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}</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">Provider </label>
                        <select name="mappings[${priority - 1}][provider]" class="input-field" required>
                            <option value="">Provider </option>
                            ${providerOptions}
                        </select>
                    </div>
                    <div>
                        <label class="label"> </label>
                        <input type="text" name="mappings[${priority - 1}][actual_model]" class="input-field font-mono" placeholder=": claude-sonnet-4-5  anthropic/claude-sonnet-4-5" required>
                        <div class="helper-text">Provider    ID</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 = "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}`;
                        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 || "사용 안 함";
                document.getElementById("current-background").textContent =
                    config.router.background || "사용 안 함";
                document.getElementById("current-websearch").textContent =
                    config.router.websearch || "사용 안 함";

                // 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 || "";
            }

            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="">모델을 선택하세요</option>'
                        : '<option value="">사용 안 함</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);
                    });
                });
            }

            // 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("모델 이름을 입력해주세요.");
                        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(
                            "최소 1개 이상의 Provider 매핑을 추가해주세요.",
                        );
                        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(
                                    ` "${modelName}"   .   .`,
                                );
                                return;
                            }

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

                            notifySuccess(
                                "모델이 수정되었어요 (저장 버튼을 눌러 적용하세요)",
                            );
                            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(
                                    ` "${modelName}"   .   .`,
                                );
                                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(
                                "모델이 추가되었어요 (저장 버튼을 눌러 적용하세요)",
                            );
                            e.target.reset();
                            navigate({ tab: "models", view: null });
                        }
                    } catch (error) {
                        console.error("Failed to save model:", error);
                        notifyError("모델 저장 중 오류가 발생했어요");
                    }
                });

            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 apiKey = formData.get("api_key")?.trim();
                    const baseUrl = formData.get("base_url")?.trim();

                    // Validation
                    if (!providerName) {
                        notifyError("Provider 이름을 입력해주세요.");
                        return;
                    }

                    if (!providerType) {
                        notifyError("Provider 타입을 선택해주세요.");
                        return;
                    }

                    if (!apiKey) {
                        notifyError("API Key를 입력해주세요.");
                        return;
                    }

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

                    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(
                                    ` "${providerName}"  Provider .   .`,
                                );
                                return;
                            }

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

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

                            notifySuccess(
                                "Provider가 수정되었어요 (저장 버튼을 눌러 적용하세요)",
                            );
                            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(
                                    ` "${providerName}"  Provider .   .`,
                                );
                                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가 추가되었어요 (저장 버튼을 눌러 적용하세요)",
                            );
                            e.target.reset();
                            navigate({ tab: "providers", view: null });
                        }
                    } catch (error) {
                        console.error("Failed to save provider:", error);
                        notifyError("Provider 저장 중 오류가 발생했어요");
                    }
                });

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

                    const formData = new FormData(e.target);
                    const defaultModel = formData.get("default_model");
                    const thinkModel = formData.get("think_model");
                    const backgroundModel = formData.get("background_model");
                    const websearchModel = formData.get("websearch_model");

                    // Validation
                    if (!defaultModel) {
                        notifyError("기본 모델을 선택해주세요.");
                        return;
                    }

                    try {
                        // 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;
                        }

                        // Save to localStorage only
                        saveToLocalStorage(appState.config);

                        notifySuccess("라우터 설정이 변경되었어요 (저장 버튼을 눌러 적용하세요)");
                        renderOverview();
                    } catch (error) {
                        console.error("Failed to save router config:", error);
                        notifyError("저장 중 오류가 발생했어요");
                    }
                });

            async function restartServer() {
                if (!confirm("서버를 재시작하시겠어요?")) return;

                try {
                    await fetch("/api/restart", { method: "POST" });
                    notifySuccess("서버가 재시작되었어요");
                } catch (error) {
                    console.error("Failed to restart server:", error);
                    notifyError("서버 재시작에 실패했습니다");
                }
            }

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

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

                    if (success) {
                        updateLastSaved();
                        notifySuccess("모든 설정이 저장되었어요");
                        renderOverview();
                    } else {
                        notifyError("저장에 실패했어요");
                    }
                } catch (error) {
                    console.error("Failed to save all config:", error);
                    notifyError("저장 중 오류가 발생했어요");
                }
            }

            async function saveAndRestart() {
                if (!confirm("설정을 저장하고 서버를 재시작하시겠어요?"))
                    return;

                try {
                    await saveAllConfig();
                    setTimeout(async () => {
                        await fetch("/api/restart", { method: "POST" });
                        notifySuccess("서버가 재시작되었어요");
                    }, 500);
                } catch (error) {
                    console.error("Failed to save and restart:", error);
                    notifyError("저장 및 재시작에 실패했습니다");
                }
            }

            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;
            }

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

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