wifui 0.5.0

A lightweight, keyboard-driven Terminal User Interface (TUI) for managing Wi-Fi connections on Windows and Linux.
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
use crate::app::AppState;
use crate::config;
use crate::theme;
use ratatui::{
    prelude::*,
    widgets::{
        Block, BorderType, Borders, Clear, List, ListItem, Padding, Paragraph, Scrollbar,
        ScrollbarOrientation, ScrollbarState, Wrap,
    },
};

/// Bounding boxes of all interactive areas returned by render(), used by mouse hit-testing.
#[derive(Debug, Clone, Default)]
pub struct LayoutAreas {
    /// Inner area of the network list (excluding border)
    pub list_area: Rect,
    /// Outer area of the error panel, if visible
    pub error_area: Option<Rect>,
    /// Outer area of the password popup, if visible
    pub password_popup_area: Option<Rect>,
    /// Outer area of the QR popup, if visible
    pub qr_popup_area: Option<Rect>,
    /// Outer area of the manual-add popup, if visible
    pub manual_popup_area: Option<Rect>,
    /// Per-field bounding boxes inside the manual-add popup (SSID=0, Password=1, Security=2, Hidden=3)
    pub manual_field_areas: [Option<Rect>; 4],
    /// Bounding box of the Connect button inside the manual-add popup
    pub manual_connect_area: Option<Rect>,
}

fn display_auth_name(auth: &str) -> &str {
    match auth {
        "Open" => "Open",
        "WPA-PSK" => "WPA-Personal",
        "WPA2-PSK" => "WPA2-Personal",
        "WPA3-SAE" => "WPA3-Personal",
        "WPA" => "WPA-Enterprise",
        "WPA2" => "WPA2-Enterprise",
        "WPA3" | "WPA3ENT" | "WPA3ENT192" => "WPA3-Enterprise",
        "Shared" => "WEP (Shared)",
        "WEP" => "WEP",
        "OWE" => "Enhanced Open (OWE)",
        "WPA-None" => "WPA-None",
        _ => auth,
    }
}

pub fn render(frame: &mut Frame, state: &mut AppState) -> LayoutAreas {
    let mut areas = LayoutAreas::default();
    let area = frame.area();
    let is_dimmed = state.is_popup_open();
    let icons = &state.ui.icon_set;

    // Set background color for the entire screen
    frame.render_widget(
        Block::default().style(Style::default().bg(theme::BACKGROUND).fg(theme::FOREGROUND)),
        area,
    );

    // Calculate dynamic dimensions to ensure perfect centering
    // Adjust width/height to match the parity of the terminal size
    let target_height = config::MAIN_WINDOW_HEIGHT;
    let height = if area.height % 2 == 0 {
        if target_height % 2 == 0 {
            target_height
        } else {
            target_height + 1
        }
    } else {
        if target_height % 2 != 0 {
            target_height
        } else {
            target_height + 1
        }
    };

    let target_width = config::MAIN_WINDOW_WIDTH;
    let width = if area.width % 2 == 0 {
        if target_width % 2 == 0 {
            target_width
        } else {
            target_width + 1
        }
    } else {
        if target_width % 2 != 0 {
            target_width
        } else {
            target_width + 1
        }
    };

    // Center the main window
    let vertical_layout = Layout::vertical([
        Constraint::Fill(1),
        Constraint::Length(height),
        Constraint::Fill(1),
    ])
    .split(area);

    let horizontal_layout = Layout::horizontal([
        Constraint::Fill(1),
        Constraint::Length(width),
        Constraint::Fill(1),
    ])
    .split(vertical_layout[1]);

    let main_area = horizontal_layout[1];

    let border_style = Style::default().fg(theme::DIMMED);

    let title_style = if is_dimmed {
        Style::default()
            .fg(theme::DIMMED)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default()
            .fg(theme::CYAN)
            .add_modifier(Modifier::BOLD)
    };

    let main_block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(border_style)
        .title_top(
            Line::from(Span::styled(
                format!(" WIFUI v{} ", env!("CARGO_PKG_VERSION")),
                title_style,
            ))
            .centered(),
        )
        .title_bottom(
            Line::from(Span::styled(
                format!(" {} ", crate::wifi::backend_name()),
                border_style,
            ))
            .right_aligned(),
        );

    frame.render_widget(main_block, main_area);

    let inner_area = main_area.inner(Margin {
        vertical: 1,
        horizontal: 2,
    });

    let mut constraints = vec![
        Constraint::Min(9),     // Network list
        Constraint::Length(10), // Details
        Constraint::Length(2),  // Bottom bar
    ];

    if state.ui.is_searching || !state.inputs.search_input.value.is_empty() {
        constraints.insert(0, Constraint::Length(3));
    }

    let content_layout = Layout::vertical(constraints).split(inner_area);

    let (search_area, list_area, details_area, help_area) =
        if state.ui.is_searching || !state.inputs.search_input.value.is_empty() {
            (
                Some(content_layout[0]),
                content_layout[1],
                content_layout[2],
                content_layout[3],
            )
        } else {
            (
                None,
                content_layout[0],
                content_layout[1],
                content_layout[2],
            )
        };

    if let Some(area) = search_area {
        let search_style = if is_dimmed {
            Style::default().fg(theme::DIMMED)
        } else if state.ui.is_searching {
            Style::default().fg(theme::YELLOW)
        } else {
            Style::default().fg(theme::CYAN)
        };

        let search_block = Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .title(" Search (/) ")
            .border_style(search_style);

        let max_width = (area.width.saturating_sub(2)) as usize;
        let input_len = state.inputs.search_input.value.chars().count();
        let cursor_pos = state.inputs.search_input.cursor;

        let (display_text, cursor_x) = if input_len < max_width {
            (state.inputs.search_input.value.clone(), cursor_pos)
        } else {
            // If cursor is near the end, show the end
            if cursor_pos >= max_width {
                let skip = cursor_pos - max_width + 1;
                let take = max_width;
                let text: String = state
                    .inputs
                    .search_input
                    .value
                    .chars()
                    .skip(skip)
                    .take(take)
                    .collect();
                (text, max_width - 1)
            } else {
                // If cursor is at the beginning, show the beginning
                let text: String = state
                    .inputs
                    .search_input
                    .value
                    .chars()
                    .take(max_width)
                    .collect();
                (text, cursor_pos)
            }
        };

        let mut spans = Vec::new();
        let chars: Vec<char> = display_text.chars().collect();

        for (i, c) in chars.iter().enumerate() {
            if i == cursor_x && state.ui.is_searching && !is_dimmed {
                spans.push(Span::styled(
                    c.to_string(),
                    Style::default().bg(theme::FOREGROUND).fg(theme::BACKGROUND),
                ));
            } else if is_dimmed {
                spans.push(Span::styled(
                    c.to_string(),
                    Style::default().fg(theme::DIMMED),
                ));
            } else {
                spans.push(Span::raw(c.to_string()));
            }
        }

        if cursor_x == chars.len() && state.ui.is_searching && !is_dimmed {
            spans.push(Span::styled(
                " ",
                Style::default().bg(theme::FOREGROUND).fg(theme::BACKGROUND),
            ));
        }

        let search_text = Paragraph::new(Line::from(spans)).block(search_block);

        frame.render_widget(search_text, area);
    }

    if state.refresh.is_initial_loading {
        let spinner_frame = state.ui.loading_frame % config::LOADING_CHARS.len();
        let spinner_char = config::LOADING_CHARS[spinner_frame];

        let combined_area = Rect {
            x: list_area.x,
            y: list_area.y,
            width: list_area.width,
            height: list_area.height + details_area.height,
        };

        let inner_height = combined_area.height.saturating_sub(2);
        let text_height = 2u16;
        let top_padding = inner_height.saturating_sub(text_height) / 2;

        let padded_block = Block::default()
            .title(" Networks ")
            .title_style(
                Style::default()
                    .fg(theme::BLUE)
                    .add_modifier(Modifier::BOLD),
            )
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme::BLUE))
            .padding(Padding::new(0, 0, top_padding, 0));

        let spinner_paragraph = Paragraph::new(vec![
            Line::from(Span::styled(
                spinner_char,
                Style::default()
                    .fg(theme::CYAN)
                    .add_modifier(Modifier::BOLD),
            )),
            Line::from(Span::styled(
                "Scanning networks...",
                Style::default().fg(theme::FOREGROUND),
            )),
        ])
        .block(padded_block)
        .alignment(Alignment::Center)
        .wrap(Wrap { trim: false });

        frame.render_widget(spinner_paragraph, combined_area);
    } else if !crate::wifi::is_backend_available() {
        let combined_area = Rect {
            x: list_area.x,
            y: list_area.y,
            width: list_area.width,
            height: list_area.height + details_area.height,
        };

        let unavailable = Paragraph::new(crate::wifi::backend_unavailable_message())
            .block(
                Block::default()
                    .title(" Networks ")
                    .title_style(
                        Style::default()
                            .fg(theme::BLUE)
                            .add_modifier(Modifier::BOLD),
                    )
                    .borders(Borders::ALL)
                    .border_type(BorderType::Rounded)
                    .border_style(Style::default().fg(theme::BLUE))
                    .padding(Padding::new(1, 1, 0, 0)),
            )
            .style(Style::default().fg(theme::YELLOW))
            .alignment(Alignment::Center)
            .wrap(Wrap { trim: true });

        frame.render_widget(unavailable, combined_area);
    } else {
        let spinner_char =
            config::LOADING_CHARS[state.ui.loading_frame % config::LOADING_CHARS.len()];
        let connecting_ssid = if state.connection.is_connecting {
            state.connection.target_ssid.as_deref()
        } else {
            None
        };
        let disconnecting_ssid = if state.connection.is_disconnecting {
            state.connection.disconnecting_ssid.as_deref()
        } else {
            None
        };

        let list_items: Vec<ListItem> = state
            .network
            .filtered_wifi_list
            .iter()
            .enumerate()
            .map(|(index, w)| {
                let is_this_connecting = connecting_ssid.is_some_and(|s| s == w.ssid.as_str());
                let is_this_disconnecting =
                    disconnecting_ssid.is_some_and(|s| s == w.ssid.as_str());
                let is_connected = (w.is_connected
                    || state
                        .network
                        .connected_ssid
                        .as_deref()
                        .is_some_and(|ssid| ssid == w.ssid))
                    && !is_this_disconnecting;

                // Preserve the original row-wide coloring: saved rows are blue,
                // connected rows are green and bold, connecting is yellow, and disconnecting is orange.
                // Mouse hover gets a subtle background when nothing else overrides.
                let row_style = if is_dimmed {
                    if is_connected {
                        Style::default()
                            .fg(theme::DIMMED)
                            .add_modifier(Modifier::BOLD)
                    } else {
                        Style::default().fg(theme::DIMMED)
                    }
                } else if is_this_connecting {
                    Style::default()
                        .fg(theme::YELLOW)
                        .add_modifier(Modifier::BOLD)
                } else if is_this_disconnecting {
                    Style::default()
                        .fg(theme::PURPLE)
                        .add_modifier(Modifier::BOLD)
                } else if is_connected {
                    Style::default()
                        .fg(theme::GREEN)
                        .add_modifier(Modifier::BOLD)
                } else if w.is_saved {
                    Style::default().fg(theme::BLUE)
                } else if state.mouse.hovered_row == Some(index) {
                    Style::default().bg(theme::HOVER_BG)
                } else {
                    Style::default()
                };

                // Prefix: spinner while connecting/disconnecting, otherwise the usual icon
                let prefix_text = if is_this_connecting || is_this_disconnecting {
                    spinner_char
                } else if w.is_saved {
                    icons.saved()
                } else if w.authentication == "Open" {
                    icons.open()
                } else {
                    icons.locked()
                };

                let mut spans = vec![
                    Span::styled(prefix_text, row_style),
                    // Spinner char has no trailing space; icons do — add one to keep width stable
                    if is_this_connecting || is_this_disconnecting {
                        Span::raw(" ")
                    } else {
                        Span::raw("")
                    },
                ];

                // SSID text
                spans.push(Span::styled(w.ssid.clone(), row_style));

                // Connected indicator
                if is_connected {
                    spans.push(Span::styled(icons.connected(), row_style));
                }

                // Suffix: "connecting..." / "disconnecting...", otherwise auto-connect status
                if is_this_connecting {
                    spans.push(Span::styled(" connecting...", row_style));
                } else if is_this_disconnecting {
                    spans.push(Span::styled(" disconnecting...", row_style));
                } else if w.is_saved {
                    if w.auto_connect {
                        spans.push(Span::styled(format!(" {}", icons.auto_on()), row_style));
                    } else {
                        spans.push(Span::styled(format!(" {}", icons.auto_off()), row_style));
                    }
                }

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

        let list_border_style = if is_dimmed {
            Style::default().fg(theme::DIMMED)
        } else {
            Style::default().fg(theme::BLUE)
        };

        let list_title_style = if is_dimmed {
            Style::default()
                .fg(theme::DIMMED)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default()
                .fg(theme::BLUE)
                .add_modifier(Modifier::BOLD)
        };

        let networks_title = if state.refresh.is_refreshing_networks {
            let spinner_char =
                config::LOADING_CHARS[state.ui.loading_frame % config::LOADING_CHARS.len()];
            Line::from(vec![
                Span::styled(" Networks ", list_title_style),
                Span::styled(spinner_char, list_title_style),
                Span::raw(" "),
            ])
        } else {
            Line::from(Span::styled(" Networks ", list_title_style))
        };

        let list = List::new(list_items)
            .block(
                Block::default()
                    .title(networks_title)
                    .title_style(list_title_style)
                    .borders(Borders::ALL)
                    .border_type(BorderType::Rounded)
                    .border_style(list_border_style),
            )
            .highlight_symbol(icons.highlight())
            .highlight_style(
                Style::default()
                    .add_modifier(Modifier::BOLD)
                    .bg(if is_dimmed {
                        theme::BACKGROUND
                    } else {
                        theme::SELECTION_BG
                    }),
            );

        frame.render_stateful_widget(list, list_area, &mut state.ui.l_state);
        areas.list_area = list_area;

        let viewport_height = list_area.height.saturating_sub(2) as usize;
        let content_len = state.network.filtered_wifi_list.len();

        let mut scroll_state = ScrollbarState::new(content_len)
            .position(state.ui.l_state.selected().unwrap_or(0))
            .viewport_content_length(viewport_height);

        if content_len > viewport_height {
            let scrollbar_style = if is_dimmed {
                Style::default().fg(theme::DIMMED)
            } else {
                Style::default().fg(theme::BLUE)
            };

            let scrollbar = Scrollbar::default()
                .orientation(ScrollbarOrientation::VerticalRight)
                .begin_symbol(Some(""))
                .end_symbol(Some(""))
                .thumb_symbol("â–ˆ")
                .track_symbol(Some("│"))
                .style(scrollbar_style);

            frame.render_stateful_widget(
                scrollbar,
                list_area.inner(Margin {
                    vertical: 1,
                    horizontal: 0,
                }),
                &mut scroll_state,
            );
        }

        if let Some(selected) = state.ui.l_state.selected()
            && let Some(wifi) = state.network.filtered_wifi_list.get(selected)
        {
            let label_style = if is_dimmed {
                Style::default().fg(theme::DIMMED)
            } else {
                Style::default().fg(theme::CYAN)
            };

            let value_style = if is_dimmed {
                Style::default().fg(theme::DIMMED)
            } else {
                Style::default()
            };

            let label = |text: &str| Span::styled(format!("{:>11} ", text), label_style);

            let sec_icon = if wifi.authentication == "Open" {
                icons.open()
            } else {
                icons.locked()
            };
            let saved_icon = icons.saved();

            let signal_bar_width = (wifi.signal as usize / 10).min(10);
            let signal_color = if is_dimmed {
                theme::DIMMED
            } else if wifi.signal > 70 {
                theme::GREEN
            } else if wifi.signal > 40 {
                theme::YELLOW
            } else {
                theme::RED
            };
            let signal_bar = "â–ˆ".repeat(signal_bar_width) + &"â–‘".repeat(10 - signal_bar_width);
            let channel_text = if wifi.channel == 0 || wifi.frequency == 0 {
                "Unknown".to_string()
            } else {
                format!(
                    "{} @ {:.3} GHz",
                    wifi.channel,
                    wifi.frequency as f64 / 1_000_000.0
                )
            };

            let mut info = vec![
                if wifi.is_connected {
                    Line::from(vec![
                        label("Status"),
                        Span::styled(
                            format!("{} Connected ", icons.connected().trim()),
                            if is_dimmed {
                                Style::default().fg(theme::DIMMED)
                            } else {
                                Style::default()
                                    .fg(theme::GREEN)
                                    .add_modifier(Modifier::BOLD)
                            },
                        ),
                        Span::styled(
                            format!("{}Saved", saved_icon),
                            if is_dimmed {
                                Style::default().fg(theme::DIMMED)
                            } else {
                                Style::default().fg(theme::BLUE)
                            },
                        ),
                    ])
                } else if wifi.is_saved {
                    Line::from(vec![
                        label("Status"),
                        Span::styled(
                            format!("{}Saved", saved_icon),
                            if is_dimmed {
                                Style::default().fg(theme::DIMMED)
                            } else {
                                Style::default().fg(theme::BLUE)
                            },
                        ),
                    ])
                } else {
                    Line::from(vec![
                        label("Status"),
                        Span::styled(
                            "Available",
                            if is_dimmed {
                                Style::default().fg(theme::DIMMED)
                            } else {
                                value_style
                            },
                        ),
                    ])
                },
                Line::from(vec![
                    label("SSID"),
                    Span::styled(
                        format!("{}", wifi.ssid),
                        value_style.add_modifier(Modifier::BOLD),
                    ),
                ]),
                Line::from(vec![
                    label("Signal"),
                    Span::styled(format!("{}% ", wifi.signal), value_style),
                    Span::styled(signal_bar, Style::default().fg(signal_color)),
                ]),
                Line::from(vec![
                    label("Security"),
                    Span::styled(
                        format!(
                            "{}{} / {}",
                            sec_icon,
                            display_auth_name(&wifi.authentication),
                            wifi.encryption
                        ),
                        value_style,
                    ),
                ]),
                Line::from(vec![
                    label("Standard"),
                    Span::styled(format!("{}", wifi.phy_type), value_style),
                ]),
                Line::from(vec![
                    label("Channel"),
                    Span::styled(channel_text, value_style),
                ]),
            ];

            if wifi.is_saved {
                let auto_text = if wifi.auto_connect {
                    format!("{} Enabled", icons.auto_on())
                } else {
                    format!("{} Disabled", icons.auto_off())
                };
                info.push(Line::from(vec![
                    label("Auto-Conn"),
                    Span::styled(auto_text, value_style),
                ]));
            }

            if let Some(speed) = wifi.link_speed {
                info.push(Line::from(vec![
                    label("Link Speed"),
                    Span::styled(format!("{} Mbps", speed), value_style),
                ]));
            }

            let details_border_style = if is_dimmed {
                Style::default().fg(theme::DIMMED)
            } else {
                Style::default().fg(theme::PURPLE)
            };

            let details_title_style = if is_dimmed {
                Style::default()
                    .fg(theme::DIMMED)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default()
                    .fg(theme::PURPLE)
                    .add_modifier(Modifier::BOLD)
            };

            let paragraph = Paragraph::new(info).wrap(Wrap { trim: false }).block(
                Block::default()
                    .title(" Details ")
                    .title_style(details_title_style)
                    .borders(Borders::ALL)
                    .border_type(BorderType::Rounded)
                    .border_style(details_border_style)
                    .padding(Padding::new(1, 1, 0, 0)),
            );
            frame.render_widget(paragraph, details_area);
        }
    }

    let help_text = if state.ui.show_password_popup {
        // Password input active - show password-specific shortcuts
        vec![Line::from(vec![
            Span::styled(icons.enter(), Style::default().fg(theme::FOREGROUND)),
            Span::styled(" connect • ", Style::default().fg(theme::DIMMED)),
            Span::styled("esc", Style::default().fg(theme::FOREGROUND)),
            Span::styled(" cancel", Style::default().fg(theme::DIMMED)),
        ])]
    } else if state.ui.show_manual_add_popup {
        // Manual add popup active - show relevant navigation & actions
        vec![
            Line::from(vec![
                Span::styled(icons.tab_next(), Style::default().fg(theme::FOREGROUND)),
                Span::styled(" next • ", Style::default().fg(theme::DIMMED)),
                Span::styled(icons.tab_prev(), Style::default().fg(theme::FOREGROUND)),
                Span::styled(" prev • ", Style::default().fg(theme::DIMMED)),
                Span::styled(icons.enter(), Style::default().fg(theme::FOREGROUND)),
                Span::styled(" connect • ", Style::default().fg(theme::DIMMED)),
                Span::styled("esc", Style::default().fg(theme::FOREGROUND)),
                Span::styled(" cancel", Style::default().fg(theme::DIMMED)),
            ]),
            Line::from(vec![
                Span::styled(icons.space(), Style::default().fg(theme::FOREGROUND)),
                Span::styled(" checkbox • ", Style::default().fg(theme::DIMMED)),
                Span::styled("h/l/j/k", Style::default().fg(theme::FOREGROUND)),
                Span::styled(" dropdown", Style::default().fg(theme::DIMMED)),
            ]),
        ]
    } else if state.ui.is_searching || !state.inputs.search_input.value.is_empty() {
        // Search active - show search-specific shortcuts
        vec![Line::from(vec![
            Span::styled(icons.enter(), Style::default().fg(theme::FOREGROUND)),
            Span::styled(" apply • ", Style::default().fg(theme::DIMMED)),
            Span::styled("esc esc", Style::default().fg(theme::FOREGROUND)),
            Span::styled(" cancel", Style::default().fg(theme::DIMMED)),
        ])]
    } else {
        // Default global help
        vec![
            Line::from(vec![
                Span::styled("q", Style::default().fg(theme::FOREGROUND)),
                Span::styled(" quit • ", Style::default().fg(theme::DIMMED)),
                Span::styled("j/k", Style::default().fg(theme::FOREGROUND)),
                Span::styled(" nav • ", Style::default().fg(theme::DIMMED)),
                Span::styled(icons.enter(), Style::default().fg(theme::FOREGROUND)),
                Span::styled(" conn / dconn • ", Style::default().fg(theme::DIMMED)),
                Span::styled("f", Style::default().fg(theme::FOREGROUND)),
                Span::styled(" forget • ", Style::default().fg(theme::DIMMED)),
                Span::styled("r", Style::default().fg(theme::FOREGROUND)),
                Span::styled(" refresh", Style::default().fg(theme::DIMMED)),
            ]),
            Line::from(vec![
                Span::styled("a", Style::default().fg(theme::FOREGROUND)),
                Span::styled(" auto-conn • ", Style::default().fg(theme::DIMMED)),
                Span::styled("s", Style::default().fg(theme::FOREGROUND)),
                Span::styled(" share • ", Style::default().fg(theme::DIMMED)),
                Span::styled("n", Style::default().fg(theme::FOREGROUND)),
                Span::styled(" add • ", Style::default().fg(theme::DIMMED)),
                Span::styled("/", Style::default().fg(theme::FOREGROUND)),
                Span::styled(" search • ", Style::default().fg(theme::DIMMED)),
                Span::styled("esc", Style::default().fg(theme::FOREGROUND)),
                Span::styled(" back", Style::default().fg(theme::DIMMED)),
            ]),
        ]
    };
    let help_paragraph = Paragraph::new(help_text)
        .style(Style::default().fg(theme::DIMMED))
        .alignment(Alignment::Center);

    frame.render_widget(help_paragraph, help_area);

    if let Some(error) = &state.ui.error_message {
        let error_area = Rect::new(area.x + 2, area.height - 4, area.width - 4, 3);
        areas.error_area = Some(error_area);
        let error_paragraph = Paragraph::new(error.as_str())
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_type(BorderType::Rounded)
                    .border_style(Style::default().fg(theme::RED))
                    .title(" ERROR "),
            )
            .style(Style::default().fg(theme::RED).bg(theme::BACKGROUND))
            .wrap(Wrap { trim: true });
        frame.render_widget(Clear, error_area);
        frame.render_widget(error_paragraph, error_area);
    }

    if state.ui.show_password_popup {
        let networks_area = list_area;
        let popup_height = 3;
        let popup_area = Rect {
            x: networks_area.x,
            y: networks_area.y + networks_area.height.saturating_sub(popup_height),
            width: networks_area.width,
            height: popup_height,
        };
        areas.password_popup_area = Some(popup_area);

        let popup_text: String = state
            .inputs
            .password_input
            .value
            .chars()
            .map(|_| '•')
            .collect();

        let max_width = (popup_area.width.saturating_sub(4)) as usize;
        let input_len = popup_text.chars().count();
        let cursor_pos = state.inputs.password_input.cursor;

        let (display_text, cursor_x) = if input_len < max_width {
            (popup_text, cursor_pos)
        } else {
            if cursor_pos >= max_width {
                let skip = cursor_pos - max_width + 1;
                let take = max_width;
                let text: String = popup_text.chars().skip(skip).take(take).collect();
                (text, max_width - 1)
            } else {
                let text: String = popup_text.chars().take(max_width).collect();
                (text, cursor_pos)
            }
        };

        let mut spans = Vec::new();
        let chars: Vec<char> = display_text.chars().collect();

        for (i, c) in chars.iter().enumerate() {
            if i == cursor_x {
                spans.push(Span::styled(
                    c.to_string(),
                    Style::default().bg(theme::FOREGROUND).fg(theme::BACKGROUND),
                ));
            } else {
                spans.push(Span::raw(c.to_string()));
            }
        }

        if cursor_x == chars.len() {
            spans.push(Span::styled(
                " ",
                Style::default().bg(theme::FOREGROUND).fg(theme::BACKGROUND),
            ));
        }

        let popup_block = Block::default()
            .title(format!(
                " Password for {} ",
                state
                    .connection
                    .pending_password_ssid
                    .as_deref()
                    .unwrap_or("")
            ))
            .title_alignment(Alignment::Left)
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme::YELLOW))
            .padding(Padding::new(1, 1, 0, 0)); // Add padding to center vertically

        let popup = Paragraph::new(Line::from(spans))
            .block(popup_block)
            .style(Style::default().fg(theme::FOREGROUND).bg(theme::BACKGROUND))
            .alignment(Alignment::Left);

        frame.render_widget(Clear, popup_area);
        frame.render_widget(popup, popup_area);
    }

    if state.ui.show_manual_add_popup {
        let networks_area = list_area;
        let popup_height = 13;
        let popup_area = Rect {
            x: networks_area.x,
            y: networks_area.y + networks_area.height.saturating_sub(popup_height),
            width: networks_area.width,
            height: popup_height,
        };
        areas.manual_popup_area = Some(popup_area);

        frame.render_widget(Clear, popup_area);

        let block = Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .title(" Add Network ")
            .title_alignment(Alignment::Center)
            .style(Style::default().fg(theme::CYAN).bg(theme::BACKGROUND));

        frame.render_widget(block.clone(), popup_area);

        let inner = popup_area.inner(Margin {
            vertical: 1,
            horizontal: 2,
        });
        let layout = Layout::vertical([
            Constraint::Length(3), // SSID
            Constraint::Length(3), // Password
            Constraint::Length(3), // Security
            Constraint::Length(1), // Spacer
            Constraint::Length(1), // Hidden + Connect
        ])
        .split(inner);

        // Capture field areas for mouse hit-testing
        areas.manual_field_areas[0] = Some(layout[0]);
        areas.manual_field_areas[1] = Some(layout[1]);
        areas.manual_field_areas[2] = Some(layout[2]);

        // SSID Input
        let ssid_style = if state.inputs.manual_input_field == 0 {
            Style::default().fg(theme::YELLOW)
        } else {
            Style::default().fg(theme::FOREGROUND)
        };
        let ssid_block = Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .title(" SSID ")
            .border_style(ssid_style)
            .style(Style::default().bg(theme::BACKGROUND));

        // SSID Cursor Logic
        let max_width_ssid = (layout[0].width.saturating_sub(2)) as usize;
        let ssid_text = &state.inputs.manual_ssid_input.value;
        let ssid_len = ssid_text.chars().count();
        let ssid_cursor = state.inputs.manual_ssid_input.cursor;

        let (display_ssid, ssid_cursor_x) = if ssid_len < max_width_ssid {
            (ssid_text.clone(), ssid_cursor)
        } else {
            if ssid_cursor >= max_width_ssid {
                let skip = ssid_cursor - max_width_ssid + 1;
                let take = max_width_ssid;
                let text: String = ssid_text.chars().skip(skip).take(take).collect();
                (text, max_width_ssid - 1)
            } else {
                let text: String = ssid_text.chars().take(max_width_ssid).collect();
                (text, ssid_cursor)
            }
        };

        let mut ssid_spans = Vec::new();
        let ssid_chars: Vec<char> = display_ssid.chars().collect();
        for (i, c) in ssid_chars.iter().enumerate() {
            if i == ssid_cursor_x && state.inputs.manual_input_field == 0 {
                ssid_spans.push(Span::styled(
                    c.to_string(),
                    Style::default().bg(theme::FOREGROUND).fg(theme::BACKGROUND),
                ));
            } else {
                ssid_spans.push(Span::raw(c.to_string()));
            }
        }
        if ssid_cursor_x == ssid_chars.len() && state.inputs.manual_input_field == 0 {
            ssid_spans.push(Span::styled(
                " ",
                Style::default().bg(theme::FOREGROUND).fg(theme::BACKGROUND),
            ));
        }

        let ssid_para = Paragraph::new(Line::from(ssid_spans)).block(ssid_block);
        frame.render_widget(ssid_para, layout[0]);

        // Password Input
        let pass_style = if state.inputs.manual_input_field == 1 {
            Style::default().fg(theme::YELLOW)
        } else {
            Style::default().fg(theme::FOREGROUND)
        };
        let pass_block = Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .title(" Password ")
            .border_style(pass_style)
            .style(Style::default().bg(theme::BACKGROUND));

        // Password Cursor Logic
        let max_width_pass = (layout[1].width.saturating_sub(2)) as usize;
        let pass_text: String = state
            .inputs
            .manual_password_input
            .value
            .chars()
            .map(|_| '•')
            .collect();
        let pass_len = pass_text.chars().count();
        let pass_cursor = state.inputs.manual_password_input.cursor;

        let (display_pass, pass_cursor_x) = if pass_len < max_width_pass {
            (pass_text, pass_cursor)
        } else {
            if pass_cursor >= max_width_pass {
                let skip = pass_cursor - max_width_pass + 1;
                let take = max_width_pass;
                let text: String = pass_text.chars().skip(skip).take(take).collect();
                (text, max_width_pass - 1)
            } else {
                let text: String = pass_text.chars().take(max_width_pass).collect();
                (text, pass_cursor)
            }
        };

        let mut pass_spans = Vec::new();
        let pass_chars: Vec<char> = display_pass.chars().collect();
        for (i, c) in pass_chars.iter().enumerate() {
            if i == pass_cursor_x && state.inputs.manual_input_field == 1 {
                pass_spans.push(Span::styled(
                    c.to_string(),
                    Style::default().bg(theme::FOREGROUND).fg(theme::BACKGROUND),
                ));
            } else {
                pass_spans.push(Span::raw(c.to_string()));
            }
        }
        if pass_cursor_x == pass_chars.len() && state.inputs.manual_input_field == 1 {
            pass_spans.push(Span::styled(
                " ",
                Style::default().bg(theme::FOREGROUND).fg(theme::BACKGROUND),
            ));
        }

        let pass_para = Paragraph::new(Line::from(pass_spans)).block(pass_block);
        frame.render_widget(pass_para, layout[1]);

        // Security Selector
        let is_active = state.inputs.manual_input_field == 2;
        let sec_border_style = if is_active {
            Style::default().fg(theme::YELLOW)
        } else {
            Style::default().fg(theme::FOREGROUND)
        };
        let sec_block = Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .title(" Security ")
            .border_style(sec_border_style)
            .style(Style::default().bg(theme::BACKGROUND));

        let arrow_style = if is_active {
            Style::default().fg(theme::YELLOW)
        } else {
            Style::default().fg(theme::DIMMED)
        };

        let value_style = if is_active {
            Style::default()
                .fg(theme::FOREGROUND)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(theme::FOREGROUND)
        };

        let sec_para = Paragraph::new(Line::from(vec![
            Span::styled(format!("{} ", icons.arrow_left()), arrow_style),
            Span::styled(format!(" {} ", state.inputs.manual_security), value_style),
            Span::styled(format!(" {}", icons.arrow_right()), arrow_style),
        ]))
        .block(sec_block)
        .alignment(Alignment::Center);
        frame.render_widget(sec_para, layout[2]);

        // Hidden Checkbox + Connect Button Row
        let bottom_layout =
            Layout::horizontal([Constraint::Min(20), Constraint::Length(15)]).split(layout[4]);

        // Capture hidden checkbox and connect button areas for mouse hit-testing
        areas.manual_field_areas[3] = Some(bottom_layout[0]);
        areas.manual_connect_area = Some(bottom_layout[1]);

        // Hidden Checkbox
        let hidden_style = if state.inputs.manual_input_field == 3 {
            Style::default().fg(theme::YELLOW)
        } else {
            Style::default().fg(theme::FOREGROUND)
        };
        let hidden_text = format!(
            "{} Hidden Network",
            icons.checkbox(state.inputs.manual_hidden)
        );
        let hidden_para = Paragraph::new(hidden_text).style(hidden_style);
        frame.render_widget(hidden_para, bottom_layout[0]);

        // Connect Button
        let connect_btn = if state.inputs.manual_input_field == 4 {
            Paragraph::new(Line::from(vec![
                Span::styled(icons.btn_left(), Style::default().fg(theme::GREEN)),
                Span::styled(
                    "Connect",
                    Style::default().bg(theme::GREEN).fg(theme::BACKGROUND),
                ),
                Span::styled(
                    format!("{} ", icons.btn_right()),
                    Style::default().fg(theme::GREEN),
                ),
            ]))
        } else {
            Paragraph::new(" Connect  ").style(Style::default().fg(theme::GREEN))
        }
        .alignment(Alignment::Right);
        frame.render_widget(connect_btn, bottom_layout[1]);
    }

    if state.ui.show_key_logger {
        if let Some((key, time)) = &state.ui.last_key_press {
            if time.elapsed() < std::time::Duration::from_secs(2) {
                let key_text = format!(" {} ", key);
                let width = key_text.len() as u16 + 2;

                // Position right below the bottom right of the main UI
                let key_area = Rect::new(
                    main_area.x + main_area.width - width,
                    main_area.y + main_area.height,
                    width,
                    3,
                );

                let block = Block::default()
                    .borders(Borders::ALL)
                    .border_type(BorderType::Rounded)
                    .border_style(Style::default().fg(theme::BRIGHT_PURPLE))
                    .style(Style::default().bg(theme::BACKGROUND));

                let paragraph = Paragraph::new(key_text)
                    .block(block)
                    .style(
                        Style::default()
                            .fg(theme::BRIGHT_PURPLE)
                            .add_modifier(Modifier::BOLD),
                    )
                    .alignment(Alignment::Center);

                frame.render_widget(Clear, key_area);
                frame.render_widget(paragraph, key_area);
            }
        }
    }

    // QR Code popup
    if state.ui.show_qr_popup {
        // Calculate QR popup size based on terminal size
        let qr_height = state.ui.qr_code_lines.len() as u16 + 4; // +4 for borders and padding
        let qr_width = state.ui.qr_code_lines.first().map(|l| l.len()).unwrap_or(0) as u16 + 4;

        // Center the popup
        let qr_x = area.width.saturating_sub(qr_width) / 2;
        let qr_y = area.height.saturating_sub(qr_height) / 2;

        let qr_area = Rect::new(
            qr_x,
            qr_y,
            qr_width.min(area.width),
            qr_height.min(area.height),
        );
        areas.qr_popup_area = Some(qr_area);

        // Clear background
        frame.render_widget(Clear, qr_area);

        // QR code block
        let qr_block = Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme::CYAN))
            .title(" Share WiFi (Scan with phone) ")
            .title_alignment(Alignment::Center)
            .title_style(
                Style::default()
                    .fg(theme::CYAN)
                    .add_modifier(Modifier::BOLD),
            )
            .style(Style::default().bg(theme::BACKGROUND));

        frame.render_widget(qr_block.clone(), qr_area);

        // Render QR code lines inside the block
        let inner = qr_area.inner(Margin {
            vertical: 1,
            horizontal: 1,
        });

        let qr_text = state.ui.qr_code_lines.join("\n");
        let qr_paragraph = Paragraph::new(qr_text)
            .alignment(Alignment::Center)
            .style(Style::default().fg(theme::FOREGROUND).bg(theme::BACKGROUND));

        frame.render_widget(qr_paragraph, inner);

        // Help text below QR code (clamp to terminal bounds)
        let help_y = qr_area.y.saturating_add(qr_area.height).saturating_add(1);
        if help_y < area.y.saturating_add(area.height) && area.width > 0 {
            let help_area = Rect::new(area.x, help_y, area.width, 1);
            let help_text = Paragraph::new("Press ESC, q, or Enter to close")
                .alignment(Alignment::Center)
                .style(Style::default().fg(theme::DIMMED));
            frame.render_widget(help_text, help_area);
        }
    }
    areas
}