awesome-omarchy-tui 0.5.1

A beautiful terminal UI for browsing the awesome-omarchy repository with search, navigation, and GitHub integration
Documentation
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
use crate::{
    App,
    models::{AppState, FocusArea},
};
use ratatui::{
    Frame,
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, List, ListItem, Paragraph, Wrap},
};

/// Dynamic color scheme that adapts to applied themes
pub struct ThemeColors {
    pub background: Color,
    pub foreground: Color,
    pub primary: Color,
    pub secondary: Color,
    pub accent: Color,
    pub success: Color,
    pub warning: Color,
    pub error: Color,
    pub muted: Color,
    pub highlight: Color,

    pub border_focused: Color,
    pub border_normal: Color,
}

impl ThemeColors {
    pub fn new() -> Self {
        Self {
            // Use ANSI colors for full terminal theme compatibility
            background: Color::Indexed(0), // ANSI black - adapts to terminal theme
            foreground: Color::Indexed(15), // ANSI bright white - adapts to terminal theme
            primary: Color::Indexed(4),    // ANSI blue - adapts to terminal theme
            secondary: Color::Indexed(6),  // ANSI cyan - adapts to terminal theme
            accent: Color::Indexed(12),    // ANSI bright blue - adapts to terminal theme
            success: Color::Indexed(2),    // ANSI green - adapts to terminal theme
            warning: Color::Indexed(3),    // ANSI yellow - adapts to terminal theme
            error: Color::Indexed(1),      // ANSI red - adapts to terminal theme
            muted: Color::Indexed(8), // ANSI bright black (dark gray) - adapts to terminal theme
            highlight: Color::Indexed(10), // ANSI bright green - adapts to terminal theme

            border_focused: Color::Indexed(2), // ANSI green for focused borders
            border_normal: Color::Indexed(8),  // ANSI bright black (muted) for normal borders
        }
    }
}

impl Default for ThemeColors {
    fn default() -> Self {
        Self::new()
    }
}

pub fn draw(f: &mut Frame, app: &mut App) {
    // Use default theme colors for main UI - themes only affect preview panels
    let default_theme_colors = ThemeColors::default();

    let main_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // Header
            Constraint::Min(0),    // Main content area (sidebar + content)
            Constraint::Length(2), // Footer
        ])
        .split(f.area());

    draw_header(f, main_chunks[0], app, &default_theme_colors);

    // Split the main content area horizontally for sidebar and content
    let content_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(20), // Left sidebar
            Constraint::Percentage(80), // Right content area
        ])
        .split(main_chunks[1]);

    draw_sidebar(f, content_chunks[0], app, &default_theme_colors);
    draw_main_content(f, content_chunks[1], app, &default_theme_colors);
    draw_footer(f, main_chunks[2], app, &default_theme_colors);

    if app.theme_browser_mode {
        draw_theme_browser_popup(f, app, &default_theme_colors);
    } else if app.search_mode {
        draw_search_popup(f, app, &default_theme_colors);
    }
}

fn draw_header(f: &mut Frame, area: Rect, app: &App, theme: &ThemeColors) {
    let title_text = if let Some(summary) = app.get_metadata_summary() {
        summary
    } else {
        "Loading...".to_string()
    };

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(1), Constraint::Length(1)])
        .split(area);

    // Enhanced main title with premium typography and visual flair
    let title = Paragraph::new(Line::from(vec![
        Span::styled("✨ ", Style::default().fg(theme.warning)),
        Span::styled(
            "┌",
            Style::default()
                .fg(theme.accent)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            " Awesome Omarchy ",
            Style::default()
                .fg(theme.secondary)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            "┐",
            Style::default()
                .fg(theme.accent)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(" ✨", Style::default().fg(theme.warning)),
    ]))
    .alignment(Alignment::Center);
    f.render_widget(title, chunks[0]);

    let meta_style = if app.state.is_loading() {
        Style::default()
            .fg(theme.warning)
            .add_modifier(Modifier::DIM)
    } else {
        Style::default().fg(theme.muted)
    };

    let meta = Paragraph::new(Line::from(vec![
        Span::styled("│ ", Style::default().fg(theme.accent)),
        Span::styled(title_text, meta_style),
        Span::styled(" │", Style::default().fg(theme.accent)),
    ]))
    .alignment(Alignment::Center);
    f.render_widget(meta, chunks[1]);
}

fn draw_sidebar(f: &mut Frame, area: Rect, app: &mut App, theme: &ThemeColors) {
    match &app.state {
        AppState::Loading => {
            let loading = Paragraph::new("🔄 Loading...")
                .style(Style::default().fg(theme.warning))
                .alignment(Alignment::Center)
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .title("📂 Sections")
                        .border_style(Style::default().fg(theme.primary)),
                );
            f.render_widget(loading, area);
        }
        AppState::Ready => {
            if !app.tabs.is_empty() {
                // Create sidebar items with section names and entry counts
                let items: Vec<ListItem> = app
                    .tabs
                    .iter()
                    .enumerate()
                    .map(|(i, tab)| {
                        let is_selected = i == app.current_tab;
                        let entry_count = if let Some(ref readme) = app.readme_content {
                            readme
                                .sections
                                .get(tab.section_index)
                                .map(|section| section.entries.len())
                                .unwrap_or(0)
                        } else {
                            0
                        };

                        if is_selected {
                            ListItem::new(Line::from(vec![
                                Span::styled(
                                    "◆ ",
                                    Style::default()
                                        .fg(theme.highlight)
                                        .add_modifier(Modifier::BOLD),
                                ),
                                Span::styled(
                                    &tab.title,
                                    Style::default()
                                        .fg(theme.foreground)
                                        .add_modifier(Modifier::BOLD),
                                ),
                                Span::styled(" ", Style::default()),
                                Span::styled("[", Style::default().fg(theme.accent)),
                                Span::styled(
                                    entry_count.to_string(),
                                    Style::default()
                                        .fg(theme.accent)
                                        .add_modifier(Modifier::BOLD),
                                ),
                                Span::styled("]", Style::default().fg(theme.accent)),
                            ]))
                        } else {
                            ListItem::new(Line::from(vec![
                                Span::styled("◇ ", Style::default().fg(theme.muted)),
                                Span::styled(
                                    &tab.title,
                                    Style::default()
                                        .fg(theme.foreground)
                                        .add_modifier(Modifier::DIM),
                                ),
                                Span::styled(" ", Style::default()),
                                Span::styled("[", Style::default().fg(theme.muted)),
                                Span::styled(
                                    entry_count.to_string(),
                                    Style::default().fg(theme.muted),
                                ),
                                Span::styled("]", Style::default().fg(theme.muted)),
                            ]))
                        }
                    })
                    .collect();

                // Enhanced border style based on focus
                let border_style = if app.focus_area == FocusArea::Sidebar {
                    Style::default().fg(theme.border_focused) // Focused
                } else {
                    Style::default().fg(theme.border_normal) // Not focused
                };

                let sidebar_list = List::new(items)
                    .block(
                        Block::default()
                            .borders(Borders::ALL)
                            .title(Line::from(vec![
                                Span::styled("📂 ", Style::default().fg(theme.primary)),
                                Span::styled(
                                    "Sections",
                                    Style::default()
                                        .fg(theme.foreground)
                                        .add_modifier(Modifier::BOLD),
                                ),
                            ]))
                            .border_style(border_style),
                    )
                    .style(Style::default())
                    .highlight_style(Style::default())
                    .highlight_symbol("")
                    .direction(ratatui::widgets::ListDirection::TopToBottom);

                f.render_widget(sidebar_list, area);
            } else {
                let empty = Paragraph::new("No sections available")
                    .style(Style::default().fg(theme.muted))
                    .alignment(Alignment::Center)
                    .block(
                        Block::default()
                            .borders(Borders::ALL)
                            .title("📂 Sections")
                            .border_style(Style::default().fg(theme.warning)),
                    );
                f.render_widget(empty, area);
            }
        }
        AppState::Error(error) => {
            let error_text = Paragraph::new(format!("❌ Error: {error}"))
                .style(Style::default().fg(theme.error))
                .alignment(Alignment::Center)
                .wrap(Wrap { trim: true })
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .title("📂 Sections")
                        .border_style(Style::default().fg(theme.error)),
                );
            f.render_widget(error_text, area);
        }
    }
}

fn draw_main_content(f: &mut Frame, area: Rect, app: &mut App, theme: &ThemeColors) {
    match &app.state {
        AppState::Loading => {
            draw_loading(f, area, theme);
        }
        AppState::Ready => {
            draw_repository_content(f, area, app, theme);
        }
        AppState::Error(error) => {
            draw_error(f, area, error, theme);
        }
    }
}

fn draw_repository_content(f: &mut Frame, area: Rect, app: &mut App, theme: &ThemeColors) {
    use ratatui::widgets::ListState;

    if let Some(current_tab) = app.current_tab() {
        let section_title = current_tab.title.clone();
        let section_index = current_tab.section_index;

        // Get selected index from list state
        let selected_index = current_tab.list_state.selected_index;

        // Get section data
        let section_data = if let Some(ref readme) = app.readme_content {
            readme
                .sections
                .get(section_index)
                .map(|section| (&section.entries, section.raw_content.clone()))
        } else {
            None
        };

        if let Some((entries, raw_content)) = section_data {
            let has_entries = !entries.is_empty();
            let entry_count = entries.len();

            if has_entries {
                // Create List items from repository entries
                let items: Vec<ListItem> = entries
                    .iter()
                    .enumerate()
                    .map(|(idx, entry)| {
                        let is_selected = selected_index == Some(idx);

                        // Create formatted list item with enhanced visual hierarchy
                        let title_line = if is_selected {
                            Line::from(vec![
                                Span::styled(
                                    format!("{:2}. ", idx + 1),
                                    Style::default().fg(theme.muted),
                                ),
                                Span::styled("◆ ", Style::default().fg(theme.highlight)),
                                Span::styled(
                                    &entry.title,
                                    Style::default()
                                        .fg(theme.foreground)
                                        .add_modifier(Modifier::BOLD),
                                ),
                            ])
                        } else {
                            Line::from(vec![
                                Span::styled(
                                    format!("{:2}. ", idx + 1),
                                    Style::default().fg(theme.muted).add_modifier(Modifier::DIM),
                                ),
                                Span::styled("◇ ", Style::default().fg(theme.muted)),
                                Span::styled(
                                    &entry.title,
                                    Style::default()
                                        .fg(theme.foreground)
                                        .add_modifier(Modifier::DIM),
                                ),
                            ])
                        };

                        let mut lines = vec![title_line];

                        // Add enhanced description with markdown-style formatting
                        if !entry.description.is_empty() {
                            let formatted_desc = format_markdown_text(&entry.description);
                            let desc_line = if is_selected {
                                Line::from(vec![
                                    Span::styled("    ", Style::default()),
                                    Span::styled("┃ ", Style::default().fg(theme.accent)),
                                    Span::styled(
                                        formatted_desc,
                                        Style::default()
                                            .fg(theme.foreground)
                                            .add_modifier(Modifier::ITALIC),
                                    ),
                                ])
                            } else {
                                Line::from(vec![
                                    Span::styled("      ", Style::default()),
                                    Span::styled("┃ ", Style::default().fg(theme.muted)),
                                    Span::styled(
                                        formatted_desc,
                                        Style::default()
                                            .fg(theme.muted)
                                            .add_modifier(Modifier::ITALIC),
                                    ),
                                ])
                            };
                            lines.push(desc_line);
                        }

                        // Add enhanced tags with visual badges
                        if !entry.tags.is_empty() {
                            let tag_badges: Vec<Span> = entry
                                .tags
                                .iter()
                                .enumerate()
                                .flat_map(|(i, tag)| {
                                    let badge_color = get_tag_color(tag, theme);
                                    let mut spans = vec![
                                        Span::styled("[", Style::default().fg(badge_color)),
                                        Span::styled(
                                            tag,
                                            Style::default()
                                                .fg(badge_color)
                                                .add_modifier(Modifier::BOLD),
                                        ),
                                        Span::styled("]", Style::default().fg(badge_color)),
                                    ];
                                    if i < entry.tags.len() - 1 {
                                        spans.push(Span::styled(" ", Style::default()));
                                    }
                                    spans
                                })
                                .collect();

                            let mut tag_spans = if is_selected {
                                vec![
                                    Span::styled("    ", Style::default()),
                                    Span::styled("🏷️ ", Style::default().fg(theme.warning)),
                                ]
                            } else {
                                vec![
                                    Span::styled("      ", Style::default()),
                                    Span::styled("🏷️ ", Style::default().fg(theme.muted)),
                                ]
                            };
                            tag_spans.extend(tag_badges);
                            lines.push(Line::from(tag_spans));
                        }

                        // Add enhanced URL with better formatting
                        let formatted_url = format_github_url(&entry.url);
                        let url_line = if is_selected {
                            Line::from(vec![
                                Span::styled("    ", Style::default()),
                                Span::styled("🔗 ", Style::default().fg(theme.primary)),
                                Span::styled(
                                    formatted_url,
                                    Style::default()
                                        .fg(theme.primary)
                                        .add_modifier(Modifier::UNDERLINED),
                                ),
                            ])
                        } else {
                            Line::from(vec![
                                Span::styled("      ", Style::default()),
                                Span::styled("🔗 ", Style::default().fg(theme.muted)),
                                Span::styled(
                                    formatted_url,
                                    Style::default()
                                        .fg(theme.primary)
                                        .add_modifier(Modifier::DIM),
                                ),
                            ])
                        };
                        lines.push(url_line);

                        // Add enhanced separator and metadata for selected items
                        if is_selected {
                            // Add repository stats if available (placeholder for future enhancement)
                            lines.push(Line::from(vec![
                                Span::styled("    ", Style::default()),
                                Span::styled("└─", Style::default().fg(theme.accent)),
                                Span::styled(
                                    " GitHub Repository ",
                                    Style::default()
                                        .fg(theme.accent)
                                        .add_modifier(Modifier::DIM),
                                ),
                                Span::styled("⭐", Style::default().fg(theme.warning)),
                            ]));
                        }

                        // Add enhanced spacing between entries
                        lines.push(Line::from(Span::styled("", Style::default())));

                        ListItem::new(lines)
                    })
                    .collect();

                // Create ratatui ListState
                let mut ratatui_state = ListState::default();
                ratatui_state.select(selected_index);

                // Enhanced border style based on focus with better visual feedback
                let border_style = if app.focus_area == FocusArea::Content {
                    Style::default().fg(theme.border_focused)
                } else {
                    Style::default().fg(theme.border_normal)
                };

                let list = List::new(items)
                    .block(
                        Block::default()
                            .borders(Borders::ALL)
                            .title(Line::from(vec![
                                Span::styled("📋 ", Style::default().fg(theme.accent)),
                                Span::styled(
                                    &section_title,
                                    Style::default()
                                        .fg(theme.foreground)
                                        .add_modifier(Modifier::BOLD),
                                ),
                                Span::styled(
                                    format!(" ({entry_count} entries)"),
                                    Style::default().fg(theme.muted).add_modifier(Modifier::DIM),
                                ),
                            ]))
                            .border_style(border_style),
                    )
                    .style(Style::default().fg(theme.foreground))
                    .highlight_style(Style::default())
                    .highlight_symbol("")
                    .direction(ratatui::widgets::ListDirection::TopToBottom);

                f.render_stateful_widget(list, area, &mut ratatui_state);
            } else {
                // No entries - show raw content or empty section
                if !raw_content.trim().is_empty()
                    && !raw_content.starts_with("•")
                    && !raw_content.contains("URL:")
                {
                    // Show raw content for sections without structured entries
                    let border_style = if app.focus_area == FocusArea::Content {
                        Style::default().fg(theme.success)
                    } else {
                        Style::default().fg(theme.primary)
                    };

                    let paragraph = Paragraph::new(raw_content)
                        .block(
                            Block::default()
                                .borders(Borders::ALL)
                                .title(format!("📄 {section_title}"))
                                .border_style(border_style),
                        )
                        .style(Style::default().fg(theme.foreground))
                        .wrap(Wrap { trim: true });
                    f.render_widget(paragraph, area);
                } else {
                    // Empty section
                    let border_style = if app.focus_area == FocusArea::Content {
                        Style::default().fg(theme.success)
                    } else {
                        Style::default().fg(theme.primary)
                    };

                    let empty = Paragraph::new("📭 No entries in this section")
                        .style(Style::default().fg(theme.muted))
                        .alignment(Alignment::Center)
                        .block(
                            Block::default()
                                .borders(Borders::ALL)
                                .title(format!("📂 {section_title}"))
                                .border_style(border_style),
                        );
                    f.render_widget(empty, area);
                }
            }
        } else {
            // Section not found
            let border_style = if app.focus_area == FocusArea::Content {
                Style::default().fg(theme.success)
            } else {
                Style::default().fg(theme.primary)
            };

            let error = Paragraph::new("Section not found")
                .style(Style::default().fg(theme.error))
                .alignment(Alignment::Center)
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .title("❌ Error")
                        .border_style(border_style),
                );
            f.render_widget(error, area);
        }
    } else {
        // No current tab
        let error = Paragraph::new("No section selected")
            .style(Style::default().fg(theme.muted))
            .alignment(Alignment::Center)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title("📂 Content")
                    .border_style(Style::default().fg(theme.primary)),
            );
        f.render_widget(error, area);
    }
}

fn draw_loading(f: &mut Frame, area: Rect, theme: &ThemeColors) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage(40),
            Constraint::Length(5),
            Constraint::Percentage(40),
        ])
        .split(area);

    let loading_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(25),
            Constraint::Percentage(50),
            Constraint::Percentage(25),
        ])
        .split(chunks[1]);

    let loading = Paragraph::new(Line::from(vec![
        Span::styled(
            "⏳ ",
            Style::default()
                .fg(theme.warning)
                .add_modifier(Modifier::SLOW_BLINK),
        ),
        Span::styled(
            "Loading README content...\n\n",
            Style::default()
                .fg(theme.warning)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            "✨ Fetching awesome resources from GitHub ✨",
            Style::default()
                .fg(theme.secondary)
                .add_modifier(Modifier::DIM),
        ),
    ]))
    .alignment(Alignment::Center)
    .block(
        Block::default()
            .borders(Borders::ALL)
            .title(Line::from(vec![
                Span::styled("📡 ", Style::default().fg(theme.warning)),
                Span::styled(
                    "Loading",
                    Style::default()
                        .fg(theme.warning)
                        .add_modifier(Modifier::BOLD),
                ),
            ]))
            .border_style(Style::default().fg(theme.warning)),
    );
    f.render_widget(loading, loading_chunks[1]);
}

fn draw_error(f: &mut Frame, area: Rect, error: &str, theme: &ThemeColors) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage(35),
            Constraint::Length(7),
            Constraint::Percentage(35),
        ])
        .split(area);

    let error_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(15),
            Constraint::Percentage(70),
            Constraint::Percentage(15),
        ])
        .split(chunks[1]);

    let error_text = Paragraph::new(Line::from(vec![
        Span::styled(
            "❌ ",
            Style::default()
                .fg(theme.error)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            "Error Occurred\n\n",
            Style::default()
                .fg(theme.error)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(error, Style::default().fg(theme.muted)),
        Span::styled("\n\n", Style::default()),
        Span::styled("💡 Press ", Style::default().fg(theme.muted)),
        Span::styled(
            "'R'",
            Style::default()
                .fg(theme.warning)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(" to retry", Style::default().fg(theme.muted)),
    ]))
    .alignment(Alignment::Center)
    .wrap(Wrap { trim: true })
    .block(
        Block::default()
            .borders(Borders::ALL)
            .title(Line::from(vec![
                Span::styled("⚠️  ", Style::default().fg(theme.error)),
                Span::styled(
                    "Error",
                    Style::default()
                        .fg(theme.error)
                        .add_modifier(Modifier::BOLD),
                ),
            ]))
            .border_style(Style::default().fg(theme.error)),
    );
    f.render_widget(error_text, error_chunks[1]);
}

fn draw_footer(f: &mut Frame, area: Rect, app: &App, theme: &ThemeColors) {
    let help_text = if app.search_mode {
        Line::from(vec![
            Span::styled(
                "ESC",
                Style::default()
                    .fg(theme.warning)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(": Exit search │ ", Style::default().fg(theme.muted)),
            Span::styled(
                "j/k",
                Style::default()
                    .fg(theme.secondary)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(": Navigate │ ", Style::default().fg(theme.muted)),
            Span::styled(
                "Enter",
                Style::default()
                    .fg(theme.success)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                ": Open URL │ Type to search...",
                Style::default().fg(theme.muted),
            ),
        ])
    } else {
        let theme_key_style = if app.is_theme_applied() {
            Style::default()
                .fg(theme.success)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default()
                .fg(theme.secondary)
                .add_modifier(Modifier::BOLD)
        };

        Line::from(vec![
            Span::styled(
                "h/l",
                Style::default()
                    .fg(theme.secondary)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(": Switch sections │ ", Style::default().fg(theme.muted)),
            Span::styled(
                "j/k",
                Style::default()
                    .fg(theme.secondary)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(": Navigate │ ", Style::default().fg(theme.muted)),
            Span::styled(
                "Enter",
                Style::default()
                    .fg(theme.success)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(": Open URL │ ", Style::default().fg(theme.muted)),
            Span::styled(
                "R",
                Style::default()
                    .fg(theme.warning)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(": Reload │ ", Style::default().fg(theme.muted)),
            Span::styled("T", theme_key_style),
            Span::styled(
                if app.is_theme_applied() {
                    ": Themes (applied) │ "
                } else {
                    ": Themes │ "
                },
                Style::default().fg(theme.muted),
            ),
            Span::styled(
                "Q",
                Style::default()
                    .fg(theme.error)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(": Quit", Style::default().fg(theme.muted)),
        ])
    };

    let footer = Paragraph::new(help_text).alignment(Alignment::Center);
    f.render_widget(footer, area);
}

fn draw_search_popup(f: &mut Frame, app: &App, theme: &ThemeColors) {
    let popup_area = centered_rect(80, 60, f.area());

    f.render_widget(Clear, popup_area);

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(3), Constraint::Min(0)])
        .split(popup_area);

    // Enhanced search input with premium styling
    let search_text = Line::from(vec![
        Span::styled("🔍 ", Style::default().fg(theme.warning)),
        Span::styled(&app.search_query, Style::default().fg(theme.warning)),
        Span::styled(
            "▌",
            Style::default()
                .fg(theme.warning)
                .add_modifier(Modifier::SLOW_BLINK),
        ),
    ]);

    let search_input = Paragraph::new(search_text).block(
        Block::default()
            .borders(Borders::ALL)
            .title(Line::from(vec![
                Span::styled("🔍 ", Style::default().fg(theme.warning)),
                Span::styled(
                    "Search",
                    Style::default()
                        .fg(theme.warning)
                        .add_modifier(Modifier::BOLD),
                ),
            ]))
            .border_style(Style::default().fg(theme.warning)),
    );
    f.render_widget(search_input, chunks[0]);

    // Simplified results display
    if !app.search_results.is_empty() {
        let results: Vec<ListItem> = app
            .search_results
            .iter()
            .take(10)
            .enumerate()
            .map(|(i, result)| {
                let display_text = app
                    .readme_content
                    .as_ref()
                    .and_then(|readme| {
                        let section = readme.sections.get(result.section_index)?;
                        match result.entry_index {
                            Some(entry_idx) => section.entries.get(entry_idx).map(|e| &e.title),
                            None => Some(&section.title),
                        }
                    })
                    .unwrap_or(&result.line_content);

                ListItem::new(Line::from(vec![
                    Span::styled(format!("{}. ", i + 1), Style::default().fg(theme.secondary)),
                    Span::styled(
                        display_text.chars().take(60).collect::<String>(),
                        Style::default().fg(theme.foreground),
                    ),
                ]))
            })
            .collect();

        let mut search_state = ratatui::widgets::ListState::default();
        search_state.select(app.search_selection);

        let results_list = List::new(results)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title(format!("Results ({})", app.search_results.len()))
                    .border_style(Style::default().fg(theme.success)),
            )
            .highlight_style(Style::default().fg(theme.warning))
            .highlight_symbol("▶ ");
        f.render_stateful_widget(results_list, chunks[1], &mut search_state);
    }
}

fn draw_theme_browser_popup(f: &mut Frame, app: &App, theme: &ThemeColors) {
    let popup_area = centered_rect(85, 70, f.area());

    f.render_widget(Clear, popup_area);

    // Add search bar if in search mode
    let (title_area, main_area) = if app.theme_browser.search_mode {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(3), // Title
                Constraint::Length(3), // Search bar
                Constraint::Min(0),    // Main content
            ])
            .split(popup_area);
        (chunks[0], chunks[2])
    } else {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(3), Constraint::Min(0)])
            .split(popup_area);
        (chunks[0], chunks[1])
    };

    // Theme browser title with enhanced styling
    let title_text = "🎨 Hybrid Multi-Panel Theme Preview";

    let preview_info = match app.preview_state {
        crate::models::PreviewState::Loading => " - Loading theme preview...",
        crate::models::PreviewState::Applied(_) => " - Multi-panel preview active! ESC to restore",
        crate::models::PreviewState::Error => " - Error loading theme",
        _ => {
            if app.theme_browser.search_mode {
                " - Type to filter themes, j/k navigate, Enter to apply, ESC to clear"
            } else {
                " - Navigate with j/k, Enter for preview, / to search, ESC to close"
            }
        }
    };

    let title = Paragraph::new(Line::from(vec![
        Span::styled("🎨 ", Style::default().fg(theme.secondary)),
        Span::styled(
            title_text,
            Style::default()
                .fg(theme.secondary)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(preview_info, Style::default().fg(theme.muted)),
    ]))
    .block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(Style::default().fg(theme.secondary)),
    );
    f.render_widget(title, title_area);

    // Render search bar if in search mode
    if app.theme_browser.search_mode {
        let search_chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(3), // Title
                Constraint::Length(3), // Search bar
                Constraint::Min(0),    // Main content
            ])
            .split(popup_area);

        let search_text = Line::from(vec![
            Span::styled("🔍 ", Style::default().fg(theme.warning)),
            Span::styled(
                &app.theme_browser.search_query,
                Style::default().fg(theme.warning),
            ),
            Span::styled(
                "▌",
                Style::default()
                    .fg(theme.warning)
                    .add_modifier(Modifier::SLOW_BLINK),
            ),
        ]);

        let result_count = if app.theme_browser.search_query.trim().is_empty() {
            String::new()
        } else {
            format!(" ({} matches)", app.theme_browser.filtered_themes.len())
        };

        let search_input = Paragraph::new(search_text).block(
            Block::default()
                .borders(Borders::ALL)
                .title(Line::from(vec![
                    Span::styled("🔍 ", Style::default().fg(theme.warning)),
                    Span::styled(
                        "Filter Themes",
                        Style::default()
                            .fg(theme.warning)
                            .add_modifier(Modifier::BOLD),
                    ),
                    Span::styled(&result_count, Style::default().fg(theme.muted)),
                ]))
                .border_style(Style::default().fg(theme.warning)),
        );
        f.render_widget(search_input, search_chunks[1]);
    }

    // Theme content
    if app.theme_browser.loading {
        let loading = Paragraph::new("🔄 Loading themes...")
            .style(Style::default().fg(theme.warning))
            .alignment(Alignment::Center)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title("Loading")
                    .border_style(Style::default().fg(theme.warning)),
            );
        f.render_widget(loading, main_area);
    } else if let Some(ref error) = app.theme_browser.error {
        let error_text = Paragraph::new(format!("❌ Error: {error}"))
            .style(Style::default().fg(theme.error))
            .alignment(Alignment::Center)
            .wrap(Wrap { trim: true })
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title("Error")
                    .border_style(Style::default().fg(theme.error)),
            );
        f.render_widget(error_text, main_area);
    } else {
        // Show theme content
        draw_aur_theme_content(f, main_area, app, theme);
    }
}

fn draw_aur_theme_content(f: &mut Frame, area: Rect, app: &App, theme: &ThemeColors) {
    if app.theme_entries.is_empty() {
        let empty_text = Paragraph::new("No themes found in README")
            .style(Style::default().fg(theme.muted))
            .alignment(Alignment::Center)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title("Empty")
                    .border_style(Style::default().fg(theme.muted)),
            );
        f.render_widget(empty_text, area);
        return;
    }

    // Split the area into two parts: theme selector and preview
    let main_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(25), // Theme list
            Constraint::Percentage(75), // Multi-panel preview
        ])
        .split(area);

    // Draw theme selector on the left
    draw_theme_selector(f, main_chunks[0], app, theme);

    // Draw multi-panel preview on the right
    if let Some(current_theme) = get_current_preview_theme(app) {
        draw_hybrid_multi_panel_preview(f, main_chunks[1], current_theme, theme);
    } else {
        // Show instructions when no theme is selected
        draw_preview_instructions(f, main_chunks[1], theme);
    }
}

fn draw_theme_selector(f: &mut Frame, area: Rect, app: &App, theme: &ThemeColors) {
    let (items, selected_index) = if app.theme_browser.search_mode
        && !app.theme_browser.filtered_themes.is_empty()
    {
        // Show filtered results
        let filtered_items: Vec<ListItem> = app
                .theme_browser.filtered_themes
                .iter()
                .enumerate()
                .filter_map(|(list_idx, &theme_idx)| {
                    app.theme_entries.get(theme_idx).map(|theme_entry| {
                        let is_selected = app.theme_browser.filtered_selected == Some(list_idx);
                        let is_applied = matches!(app.preview_state,
                            crate::models::PreviewState::Applied(ref t) if t.as_ref().name == theme_entry.name
                        );

                        let name_style = if is_selected {
                            if is_applied {
                                Style::default()
                                    .fg(theme.success)
                                    .add_modifier(Modifier::BOLD)
                            } else {
                                Style::default()
                                    .fg(theme.foreground)
                                    .add_modifier(Modifier::BOLD)
                            }
                        } else {
                            Style::default().fg(theme.muted)
                        };

                        let mut spans = vec![
                            if is_selected {
                                Span::styled("▶ ", Style::default().fg(theme.success))
                            } else {
                                Span::styled("  ", Style::default())
                            },
                            Span::styled(&theme_entry.name, name_style),
                        ];

                        if is_applied {
                            spans.push(Span::styled(" ✨", Style::default().fg(theme.success)));
                        }

                        ListItem::new(Line::from(spans))
                    })
                })
                .collect();

        (filtered_items, app.theme_browser.filtered_selected)
    } else if app.theme_browser.search_mode
        && app.theme_browser.filtered_themes.is_empty()
        && !app.theme_browser.search_query.trim().is_empty()
    {
        // Show "no matches" when search has no results
        let no_matches = vec![ListItem::new(Line::from(vec![
            Span::styled("  No themes match \"", Style::default().fg(theme.muted)),
            Span::styled(
                &app.theme_browser.search_query,
                Style::default().fg(theme.warning),
            ),
            Span::styled("\"", Style::default().fg(theme.muted)),
        ]))];
        (no_matches, None)
    } else {
        // Show all themes
        let all_items: Vec<ListItem> = app
                .theme_entries
                .iter()
                .enumerate()
                .map(|(i, theme_entry)| {
                    let is_selected = app.theme_browser.selected_index == Some(i);
                    let is_applied = matches!(app.preview_state,
                        crate::models::PreviewState::Applied(ref t) if t.as_ref().name == theme_entry.name
                    );

                    let name_style = if is_selected {
                        if is_applied {
                            Style::default()
                                .fg(theme.success)
                                .add_modifier(Modifier::BOLD)
                        } else {
                            Style::default()
                                .fg(theme.foreground)
                                .add_modifier(Modifier::BOLD)
                        }
                    } else {
                        Style::default().fg(theme.muted)
                    };

                    let mut spans = vec![
                        if is_selected {
                            Span::styled("▶ ", Style::default().fg(theme.success))
                        } else {
                            Span::styled("  ", Style::default())
                        },
                        Span::styled(&theme_entry.name, name_style),
                    ];

                    if is_applied {
                        spans.push(Span::styled(" ✨", Style::default().fg(theme.success)));
                    }

                    ListItem::new(Line::from(spans))
                })
                .collect();

        (all_items, app.theme_browser.selected_index)
    };

    let mut list_state = ratatui::widgets::ListState::default();
    list_state.select(selected_index);

    let theme_count =
        if app.theme_browser.search_mode && !app.theme_browser.search_query.trim().is_empty() {
            format!(
                " ({}/{})",
                app.theme_browser.filtered_themes.len(),
                app.theme_entries.len()
            )
        } else {
            format!(" ({})", app.theme_entries.len())
        };

    let list = List::new(items)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(format!("🎨 Themes{theme_count}"))
                .border_style(Style::default().fg(theme.primary)),
        )
        .highlight_style(Style::default())
        .highlight_symbol("");

    f.render_stateful_widget(list, area, &mut list_state);
}

fn draw_preview_instructions(f: &mut Frame, area: Rect, theme: &ThemeColors) {
    let instructions = Paragraph::new(vec![
        Line::from(vec![
            Span::styled("🔍 ", Style::default().fg(theme.warning)),
            Span::styled(
                "Theme Preview",
                Style::default()
                    .fg(theme.foreground)
                    .add_modifier(Modifier::BOLD),
            ),
        ]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "Navigation:",
            Style::default()
                .fg(theme.secondary)
                .add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![
            Span::styled(
                "  j/k",
                Style::default()
                    .fg(theme.primary)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(" - Navigate themes", Style::default().fg(theme.muted)),
        ]),
        Line::from(vec![
            Span::styled(
                "  Enter",
                Style::default()
                    .fg(theme.success)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                " - Apply theme and show preview",
                Style::default().fg(theme.muted),
            ),
        ]),
        Line::from(vec![
            Span::styled(
                "  ESC",
                Style::default()
                    .fg(theme.error)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(" - Close and restore", Style::default().fg(theme.muted)),
        ]),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                "Select a theme and press ",
                Style::default().fg(theme.muted),
            ),
            Span::styled(
                "Enter",
                Style::default()
                    .fg(theme.success)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(" to see:", Style::default().fg(theme.muted)),
        ]),
        Line::from(""),
        Line::from(vec![
            Span::styled("• ", Style::default().fg(theme.warning)),
            Span::styled(
                "Terminal simulation with theme colors",
                Style::default().fg(theme.muted),
            ),
        ]),
        Line::from(vec![
            Span::styled("• ", Style::default().fg(theme.warning)),
            Span::styled(
                "Application preview (btop-style)",
                Style::default().fg(theme.muted),
            ),
        ]),
        Line::from(vec![
            Span::styled("• ", Style::default().fg(theme.warning)),
            Span::styled(
                "Code editor with syntax highlighting",
                Style::default().fg(theme.muted),
            ),
        ]),
        Line::from(vec![
            Span::styled("• ", Style::default().fg(theme.warning)),
            Span::styled(
                "Color palette with hex values",
                Style::default().fg(theme.muted),
            ),
        ]),
    ])
    .alignment(Alignment::Center)
    .block(
        Block::default()
            .borders(Borders::ALL)
            .title("📋 Preview Instructions")
            .border_style(Style::default().fg(theme.primary)),
    );

    f.render_widget(instructions, area);
}

fn get_current_preview_theme(app: &App) -> Option<&crate::models::Theme> {
    match &app.preview_state {
        crate::models::PreviewState::Applied(theme) => Some(theme.as_ref()),
        _ => None,
    }
}

fn draw_hybrid_multi_panel_preview(
    f: &mut Frame,
    area: Rect,
    theme_colors: &crate::models::Theme,
    ui_theme: &ThemeColors,
) {
    // Create 4-panel layout
    let main_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage(50), // Top row (Terminal + Application)
            Constraint::Percentage(50), // Bottom row (Editor + Palette)
        ])
        .split(area);

    // Top row: Terminal and Application panels
    let top_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(50), // Terminal panel
            Constraint::Percentage(50), // Application panel
        ])
        .split(main_chunks[0]);

    // Bottom row: Editor and Palette panels
    let bottom_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(50), // Editor panel
            Constraint::Percentage(50), // Palette panel
        ])
        .split(main_chunks[1]);

    // Draw each panel with the applied theme
    draw_terminal_preview_panel(f, top_chunks[0], theme_colors, ui_theme);
    draw_application_preview_panel(f, top_chunks[1], theme_colors, ui_theme);
    draw_editor_preview_panel(f, bottom_chunks[0], theme_colors, ui_theme);
    draw_palette_preview_panel(f, bottom_chunks[1], theme_colors, ui_theme);
}

fn draw_terminal_preview_panel(
    f: &mut Frame,
    area: Rect,
    theme: &crate::models::Theme,
    ui_theme: &ThemeColors,
) {
    let bg_color = parse_hex_color(&theme.colors.background).unwrap_or(ui_theme.background);
    let fg_color = parse_hex_color(&theme.colors.foreground).unwrap_or(ui_theme.foreground);
    let prompt_color = parse_hex_color(&theme.colors.bright.green).unwrap_or(ui_theme.success);
    let command_color = parse_hex_color(&theme.colors.normal.yellow).unwrap_or(ui_theme.warning);
    let file_color = parse_hex_color(&theme.colors.bright.blue).unwrap_or(ui_theme.primary);
    let dir_color = parse_hex_color(&theme.colors.bright.cyan).unwrap_or(ui_theme.secondary);

    let terminal_content = vec![
        Line::from(vec![
            Span::styled(
                "user@omarchy ",
                Style::default()
                    .fg(prompt_color)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                "~/awesome-omarchy ",
                Style::default().fg(dir_color).add_modifier(Modifier::BOLD),
            ),
            Span::styled("$ ", Style::default().fg(fg_color)),
            Span::styled("ls -la", Style::default().fg(command_color)),
        ]),
        Line::from(vec![Span::styled(
            "total 42",
            Style::default().fg(fg_color),
        )]),
        Line::from(vec![
            Span::styled(
                "drwxr-xr-x 5 user user 4096 Aug 21 14:30 ",
                Style::default().fg(fg_color),
            ),
            Span::styled(
                ".",
                Style::default().fg(dir_color).add_modifier(Modifier::BOLD),
            ),
        ]),
        Line::from(vec![
            Span::styled(
                "drwxr-xr-x 3 user user 4096 Aug 21 14:25 ",
                Style::default().fg(fg_color),
            ),
            Span::styled(
                "..",
                Style::default().fg(dir_color).add_modifier(Modifier::BOLD),
            ),
        ]),
        Line::from(vec![
            Span::styled(
                "-rw-r--r-- 1 user user 1034 Aug 21 14:30 ",
                Style::default().fg(fg_color),
            ),
            Span::styled("Cargo.toml", Style::default().fg(file_color)),
        ]),
        Line::from(vec![
            Span::styled(
                "-rw-r--r-- 1 user user 5847 Aug 21 14:28 ",
                Style::default().fg(fg_color),
            ),
            Span::styled("README.md", Style::default().fg(file_color)),
        ]),
        Line::from(vec![
            Span::styled(
                "drwxr-xr-x 2 user user 4096 Aug 21 14:25 ",
                Style::default().fg(fg_color),
            ),
            Span::styled(
                "src/",
                Style::default().fg(dir_color).add_modifier(Modifier::BOLD),
            ),
        ]),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                "user@omarchy ",
                Style::default()
                    .fg(prompt_color)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                "~/awesome-omarchy ",
                Style::default().fg(dir_color).add_modifier(Modifier::BOLD),
            ),
            Span::styled("$ ", Style::default().fg(fg_color)),
            Span::styled("cargo run", Style::default().fg(command_color)),
        ]),
        Line::from(vec![Span::styled(
            "   Compiling awesome-omarchy-tui v0.1.0",
            Style::default().fg(fg_color),
        )]),
        Line::from(vec![
            Span::styled("    Finished ", Style::default().fg(fg_color)),
            Span::styled(
                "dev",
                Style::default()
                    .fg(prompt_color)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(" [unoptimized + debuginfo]", Style::default().fg(fg_color)),
        ]),
    ];

    let terminal_panel = Paragraph::new(terminal_content)
        .style(Style::default().bg(bg_color).fg(fg_color))
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title("🖥️ Terminal")
                .border_style(Style::default().fg(ui_theme.primary)),
        );

    f.render_widget(terminal_panel, area);
}

fn draw_application_preview_panel(
    f: &mut Frame,
    area: Rect,
    theme: &crate::models::Theme,
    ui_theme: &ThemeColors,
) {
    let bg_color = parse_hex_color(&theme.colors.background).unwrap_or(ui_theme.background);
    let fg_color = parse_hex_color(&theme.colors.foreground).unwrap_or(ui_theme.foreground);
    let cpu_color = parse_hex_color(&theme.colors.normal.red).unwrap_or(ui_theme.error);
    let mem_color = parse_hex_color(&theme.colors.normal.blue).unwrap_or(ui_theme.primary);
    let disk_color = parse_hex_color(&theme.colors.normal.green).unwrap_or(ui_theme.success);
    let label_color = parse_hex_color(&theme.colors.bright.white).unwrap_or(ui_theme.foreground);

    let application_content = vec![
        Line::from(vec![Span::styled(
            "System Monitor",
            Style::default()
                .fg(label_color)
                .add_modifier(Modifier::BOLD),
        )]),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                "CPU: ",
                Style::default()
                    .fg(label_color)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("████████████████░░░░ ", Style::default().fg(cpu_color)),
            Span::styled(
                "67%",
                Style::default().fg(cpu_color).add_modifier(Modifier::BOLD),
            ),
        ]),
        Line::from(vec![Span::styled(
            "     Intel i7-12700K @ 3.60GHz",
            Style::default().fg(fg_color),
        )]),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                "MEM: ",
                Style::default()
                    .fg(label_color)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("████████████░░░░░░░░ ", Style::default().fg(mem_color)),
            Span::styled(
                "54%",
                Style::default().fg(mem_color).add_modifier(Modifier::BOLD),
            ),
        ]),
        Line::from(vec![Span::styled(
            "     8.7GB / 16.0GB",
            Style::default().fg(fg_color),
        )]),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                "DSK: ",
                Style::default()
                    .fg(label_color)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("██████░░░░░░░░░░░░░░ ", Style::default().fg(disk_color)),
            Span::styled(
                "23%",
                Style::default().fg(disk_color).add_modifier(Modifier::BOLD),
            ),
        ]),
        Line::from(vec![Span::styled(
            "     247GB / 1TB SSD",
            Style::default().fg(fg_color),
        )]),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                "NET: ",
                Style::default()
                    .fg(label_color)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("↓", Style::default().fg(disk_color)),
            Span::styled("127MB/s ", Style::default().fg(fg_color)),
            Span::styled("↑", Style::default().fg(cpu_color)),
            Span::styled("42MB/s", Style::default().fg(fg_color)),
        ]),
    ];

    let application_panel = Paragraph::new(application_content)
        .style(Style::default().bg(bg_color).fg(fg_color))
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title("📊 System Monitor")
                .border_style(Style::default().fg(ui_theme.primary)),
        );

    f.render_widget(application_panel, area);
}

fn draw_editor_preview_panel(
    f: &mut Frame,
    area: Rect,
    theme: &crate::models::Theme,
    ui_theme: &ThemeColors,
) {
    let bg_color = parse_hex_color(&theme.colors.background).unwrap_or(ui_theme.background);
    let fg_color = parse_hex_color(&theme.colors.foreground).unwrap_or(ui_theme.foreground);
    let keyword_color = parse_hex_color(&theme.colors.bright.magenta).unwrap_or(ui_theme.accent);
    let string_color = parse_hex_color(&theme.colors.normal.green).unwrap_or(ui_theme.success);
    let comment_color = parse_hex_color(&theme.colors.normal.black).unwrap_or(ui_theme.muted);
    let function_color = parse_hex_color(&theme.colors.bright.blue).unwrap_or(ui_theme.primary);
    let number_color = parse_hex_color(&theme.colors.normal.cyan).unwrap_or(ui_theme.secondary);

    let editor_content = vec![
        Line::from(vec![
            Span::styled("1 ", Style::default().fg(comment_color)),
            Span::styled(
                "use ",
                Style::default()
                    .fg(keyword_color)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("std::collections::HashMap;", Style::default().fg(fg_color)),
        ]),
        Line::from(vec![Span::styled("2 ", Style::default().fg(comment_color))]),
        Line::from(vec![
            Span::styled("3 ", Style::default().fg(comment_color)),
            Span::styled(
                "// Theme preview implementation",
                Style::default()
                    .fg(comment_color)
                    .add_modifier(Modifier::ITALIC),
            ),
        ]),
        Line::from(vec![
            Span::styled("4 ", Style::default().fg(comment_color)),
            Span::styled(
                "pub fn ",
                Style::default()
                    .fg(keyword_color)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                "apply_theme",
                Style::default()
                    .fg(function_color)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("(theme: &", Style::default().fg(fg_color)),
            Span::styled("Theme", Style::default().fg(keyword_color)),
            Span::styled(") {", Style::default().fg(fg_color)),
        ]),
        Line::from(vec![
            Span::styled("5 ", Style::default().fg(comment_color)),
            Span::styled("    ", Style::default()),
            Span::styled(
                "let ",
                Style::default()
                    .fg(keyword_color)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("colors = theme.colors;", Style::default().fg(fg_color)),
        ]),
        Line::from(vec![
            Span::styled("6 ", Style::default().fg(comment_color)),
            Span::styled("    ", Style::default()),
            Span::styled(
                "println!",
                Style::default()
                    .fg(function_color)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("(", Style::default().fg(fg_color)),
            Span::styled("\"Theme: {}\"", Style::default().fg(string_color)),
            Span::styled(", theme.name);", Style::default().fg(fg_color)),
        ]),
        Line::from(vec![
            Span::styled("7 ", Style::default().fg(comment_color)),
            Span::styled("}", Style::default().fg(fg_color)),
        ]),
        Line::from(vec![Span::styled("8 ", Style::default().fg(comment_color))]),
        Line::from(vec![
            Span::styled("9 ", Style::default().fg(comment_color)),
            Span::styled(
                "const ",
                Style::default()
                    .fg(keyword_color)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("MAX_THEMES", Style::default().fg(fg_color)),
            Span::styled(": ", Style::default().fg(fg_color)),
            Span::styled("usize ", Style::default().fg(keyword_color)),
            Span::styled("= ", Style::default().fg(fg_color)),
            Span::styled(
                "42",
                Style::default()
                    .fg(number_color)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(";", Style::default().fg(fg_color)),
        ]),
    ];

    let editor_panel = Paragraph::new(editor_content)
        .style(Style::default().bg(bg_color).fg(fg_color))
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title("📝 Code Editor")
                .border_style(Style::default().fg(ui_theme.primary)),
        );

    f.render_widget(editor_panel, area);
}

fn draw_palette_preview_panel(
    f: &mut Frame,
    area: Rect,
    theme: &crate::models::Theme,
    ui_theme: &ThemeColors,
) {
    let bg_color = parse_hex_color(&theme.colors.background).unwrap_or(ui_theme.background);
    let fg_color = parse_hex_color(&theme.colors.foreground).unwrap_or(ui_theme.foreground);

    let palette_content = vec![
        Line::from(vec![Span::styled(
            "Color Palette",
            Style::default().fg(fg_color).add_modifier(Modifier::BOLD),
        )]),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                "BG: ",
                Style::default().fg(fg_color).add_modifier(Modifier::BOLD),
            ),
            Span::styled("██ ", Style::default().bg(bg_color)),
            Span::styled(
                &theme.colors.background,
                Style::default().fg(ui_theme.muted),
            ),
        ]),
        Line::from(vec![
            Span::styled(
                "FG: ",
                Style::default().fg(fg_color).add_modifier(Modifier::BOLD),
            ),
            Span::styled("██ ", Style::default().bg(fg_color)),
            Span::styled(
                &theme.colors.foreground,
                Style::default().fg(ui_theme.muted),
            ),
        ]),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                "🔴 ",
                Style::default()
                    .fg(parse_hex_color(&theme.colors.normal.red).unwrap_or(Color::Indexed(1))),
            ),
            Span::styled(
                &theme.colors.normal.red,
                Style::default().fg(ui_theme.muted),
            ),
            Span::styled(" RED", Style::default().fg(ui_theme.muted)),
        ]),
        Line::from(vec![
            Span::styled(
                "🟢 ",
                Style::default()
                    .fg(parse_hex_color(&theme.colors.normal.green).unwrap_or(Color::Indexed(2))),
            ),
            Span::styled(
                &theme.colors.normal.green,
                Style::default().fg(ui_theme.muted),
            ),
            Span::styled(" GREEN", Style::default().fg(ui_theme.muted)),
        ]),
        Line::from(vec![
            Span::styled(
                "🔵 ",
                Style::default()
                    .fg(parse_hex_color(&theme.colors.normal.blue).unwrap_or(Color::Indexed(4))),
            ),
            Span::styled(
                &theme.colors.normal.blue,
                Style::default().fg(ui_theme.muted),
            ),
            Span::styled(" BLUE", Style::default().fg(ui_theme.muted)),
        ]),
        Line::from(vec![
            Span::styled(
                "🟡 ",
                Style::default()
                    .fg(parse_hex_color(&theme.colors.normal.yellow).unwrap_or(Color::Indexed(3))),
            ),
            Span::styled(
                &theme.colors.normal.yellow,
                Style::default().fg(ui_theme.muted),
            ),
            Span::styled(" YELLOW", Style::default().fg(ui_theme.muted)),
        ]),
        Line::from(vec![
            Span::styled(
                "🟣 ",
                Style::default()
                    .fg(parse_hex_color(&theme.colors.normal.magenta).unwrap_or(Color::Indexed(5))),
            ),
            Span::styled(
                &theme.colors.normal.magenta,
                Style::default().fg(ui_theme.muted),
            ),
            Span::styled(" MAGENTA", Style::default().fg(ui_theme.muted)),
        ]),
        Line::from(vec![
            Span::styled(
                "🩵 ",
                Style::default()
                    .fg(parse_hex_color(&theme.colors.normal.cyan).unwrap_or(Color::Indexed(6))),
            ),
            Span::styled(
                &theme.colors.normal.cyan,
                Style::default().fg(ui_theme.muted),
            ),
            Span::styled(" CYAN", Style::default().fg(ui_theme.muted)),
        ]),
    ];

    let palette_panel = Paragraph::new(palette_content)
        .style(Style::default().bg(bg_color).fg(fg_color))
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title("🎨 Color Palette")
                .border_style(Style::default().fg(ui_theme.primary)),
        );

    f.render_widget(palette_panel, area);
}

fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
    let popup_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage((100 - percent_y) / 2),
            Constraint::Percentage(percent_y),
            Constraint::Percentage((100 - percent_y) / 2),
        ])
        .split(r);

    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage((100 - percent_x) / 2),
            Constraint::Percentage(percent_x),
            Constraint::Percentage((100 - percent_x) / 2),
        ])
        .split(popup_layout[1])[1]
}

// Helper function to parse hex colors to ratatui Color
fn parse_hex_color(hex: &str) -> Option<Color> {
    let hex = hex.strip_prefix('#').unwrap_or(hex);
    if hex.len() != 6 {
        return None;
    }

    let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
    let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
    let b = u8::from_str_radix(&hex[4..6], 16).ok()?;

    Some(Color::Rgb(r, g, b))
}

/// Format markdown text with basic styling hints
fn format_markdown_text(text: &str) -> String {
    // Simple markdown formatting - replace **bold** and *italic* markers
    let text = text.replace("**", "");
    let text = text.replace("*", "");
    // Remove excessive whitespace and clean up
    text.trim().to_string()
}

/// Get color for different tag types - using ANSI colors for terminal theme compatibility
fn get_tag_color(tag: &str, theme: &ThemeColors) -> Color {
    match tag.to_lowercase().as_str() {
        "rust" => Color::Indexed(11),  // ANSI bright yellow (rust-like)
        "python" => Color::Indexed(3), // ANSI yellow
        "javascript" | "typescript" => Color::Indexed(11), // ANSI bright yellow
        "go" | "golang" => Color::Indexed(6), // ANSI cyan
        "java" => Color::Indexed(1),   // ANSI red
        "cpp" | "c++" => Color::Indexed(4), // ANSI blue
        "tool" | "cli" => theme.primary,
        "library" => theme.secondary,
        "framework" => theme.accent,
        "web" => Color::Indexed(2), // ANSI green
        "api" => Color::Indexed(5), // ANSI magenta
        "plugin" | "extension" => theme.warning,
        _ => theme.muted,
    }
}

/// Format GitHub URL to show only repository name
fn format_github_url(url: &str) -> String {
    if let Some(repo_part) = url.strip_prefix("https://github.com/") {
        // Extract just the owner/repo part
        let parts: Vec<&str> = repo_part.split('/').collect();
        if parts.len() >= 2 {
            format!("{}/{}", parts[0], parts[1])
        } else {
            repo_part.to_string()
        }
    } else {
        url.to_string()
    }
}