reeve-cli 0.1.0

Localhost web dev stack manager: web servers, per-vhost PHP versions, SSL, and DNS — RunCloud, scaled down.
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
//! ratatui dashboard — stacked Servers / PHP / Vhosts panels with live status
//! and action keys. Shares all lifecycle logic with the CLI via `crate::ops`.

mod pathpick;
mod ui;

use crate::backends::settings_defs;
use crate::brew::Brew;
use crate::config::{load_config, save_config, Config};
use crate::daemon::{self, Status};
use crate::ops;
use crate::php;
use crate::state::{load_state, Backend, State};
use anyhow::Result;
use crossterm::{
    event::{
        self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind, KeyModifiers,
    },
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{backend::CrosstermBackend, Terminal};
use std::io::{self, Stdout};
use std::time::Duration;

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Panel {
    Servers,
    Php,
    Vhosts,
}

pub struct App {
    pub config: Config,
    pub state: State,
    pub focus: Panel,
    pub sel_server: usize,
    pub sel_php: usize,
    pub sel_vhost: usize,
    pub server_status: Vec<Status>,
    pub php_status: Vec<Status>,
    pub message: String,
    pub wizard: Option<VhostWizard>,
    /// When set, a "remove vhost <name>?" confirmation is showing.
    pub confirm_remove: Option<String>,
    /// Server-edit modal (ports/backend), when open.
    pub server_wizard: Option<ServerWizard>,
    /// Per-backend settings modal, when open.
    pub settings_modal: Option<SettingsModal>,
    /// PHP-install input modal, when open.
    pub php_install: Option<PhpInstallModal>,
    /// When set, a "remove PHP <version>?" confirmation is showing.
    pub confirm_remove_php: Option<String>,
    /// A PHP version queued for install — run_loop suspends the TUI, installs
    /// it (showing brew output), then resumes. Avoids a frozen screen.
    pub pending_install: Option<String>,
    /// Whether `*.tld` system resolution is configured (/etc/resolver present).
    pub dns_ok: bool,
    /// "remove server <name>?" confirmation, when showing.
    pub confirm_remove_server: Option<String>,
    /// PHP extensions manager modal, when open.
    pub ext_modal: Option<ExtModal>,
    /// A queued (slow) pecl add/remove — run_loop suspends the TUI to show output.
    pub pending_ext: Option<PendingExt>,
    /// Global preferences (local TLD, sites root, default backend) modal.
    pub config_modal: Option<ConfigModal>,
    /// Set after an action that may have disturbed the terminal (e.g. the admin
    /// dialog); run_loop does a full repaint to clear any leftover artifacts.
    force_clear: bool,
    should_quit: bool,
}

/// Global preferences modal. Edits `config.toml` (local TLD, sites root,
/// default backend) — distinct from per-server [`SettingsModal`].
pub struct ConfigModal {
    pub tld: String,
    pub sites_root: String,
    pub backend_idx: usize,
    /// 0 = TLD, 1 = sites root, 2 = default backend.
    pub field: usize,
    pub error: Option<String>,
    /// TLD as saved on open, so we can warn when it changes (DNS needs re-setup).
    pub orig_tld: String,
}

/// Editable fields in the global config modal.
pub const CONFIG_FIELDS: usize = 3;

/// Modal to type a PHP version to install.
pub struct PhpInstallModal {
    pub version: String,
    pub error: Option<String>,
}

/// PHP extensions manager modal for one version.
pub struct ExtModal {
    pub version: String,
    /// Currently-loaded extensions (`php -m`), sorted.
    pub loaded: Vec<String>,
    /// Text being typed to add a new extension.
    pub input: String,
    /// Highlighted entry in `loaded` (used when `input` is empty).
    pub sel: usize,
    pub error: Option<String>,
}

/// A queued pecl operation, run outside the alternate screen (it's slow).
pub enum ExtAction {
    Add(String),
    Remove(String),
}
pub struct PendingExt {
    pub version: String,
    pub action: ExtAction,
}

/// Per-backend settings modal state. `values` parallels
/// `backends::settings_defs(backend)`.
pub struct SettingsModal {
    pub server_name: String,
    pub backend: Backend,
    pub values: Vec<String>,
    pub field: usize,
    pub error: Option<String>,
}

/// Backends in selector order.
pub const BACKENDS: [Backend; 4] = [
    Backend::Caddy,
    Backend::Apache,
    Backend::Nginx,
    Backend::Ols,
];
/// Editable fields in the server modal (Backend, HTTP, HTTPS, Default site).
pub const SERVER_FIELDS: usize = 4;

/// Modal form state for editing a server's ports/backend.
pub struct ServerWizard {
    pub backend_idx: usize,
    pub http: String,
    pub https: String,
    /// Serve a catch-all default site on the HTTP port.
    pub default_site: bool,
    pub field: usize,
    pub error: Option<String>,
    /// `Some(orig)` when editing an existing server; `None` when creating one.
    pub editing: Option<String>,
    /// Whether each backend (parallel to `BACKENDS`) has its brew formula present.
    pub installed: [bool; 4],
}

/// Number of editable fields in the new-vhost wizard.
pub const WIZARD_FIELDS: usize = 5;

/// Modal form state for creating a vhost.
pub struct VhostWizard {
    pub server_name: String,
    pub docroot: String,
    pub php_idx: usize,
    pub server_idx: usize,
    pub ssl: bool,
    pub field: usize,
    pub error: Option<String>,
    /// `Some(original_host)` when editing an existing vhost; `None` when creating.
    pub editing: Option<String>,
    /// Whether the Doc root autocomplete dropdown is open (captures ↑/↓).
    pub dropdown_open: bool,
    /// Highlighted entry within the open dropdown.
    pub path_sel: Option<usize>,
}

impl VhostWizard {
    /// Live filesystem suggestions for the current `docroot` text (capped).
    pub fn path_suggestions(&self) -> Vec<pathpick::PathEntry> {
        pathpick::read_dir_filtered(&self.docroot, PATH_SUGGESTION_CAP)
    }

    /// True when the dropdown should capture ↑/↓ (Doc root field + open).
    fn dropdown_active(&self) -> bool {
        self.field == FIELD_DOCROOT && self.dropdown_open
    }

    /// Move to a field; landing on Doc root (re)opens its dropdown.
    fn goto_field(&mut self, field: usize) {
        self.field = field;
        self.path_sel = None;
        if field == FIELD_DOCROOT {
            self.dropdown_open = true;
        }
    }

    fn next_field(&mut self) {
        self.goto_field((self.field + 1) % WIZARD_FIELDS);
    }

    fn prev_field(&mut self) {
        self.goto_field((self.field + WIZARD_FIELDS - 1) % WIZARD_FIELDS);
    }
}

/// Max entries shown in the Doc root dropdown.
pub const PATH_SUGGESTION_CAP: usize = 8;

impl App {
    fn load() -> Result<Self> {
        let mut app = App {
            config: load_config().unwrap_or_default(),
            state: State::default(),
            focus: Panel::Servers,
            sel_server: 0,
            sel_php: 0,
            sel_vhost: 0,
            server_status: Vec::new(),
            php_status: Vec::new(),
            message: "ready".into(),
            wizard: None,
            confirm_remove: None,
            server_wizard: None,
            settings_modal: None,
            php_install: None,
            confirm_remove_php: None,
            pending_install: None,
            dns_ok: false,
            confirm_remove_server: None,
            ext_modal: None,
            pending_ext: None,
            config_modal: None,
            force_clear: false,
            should_quit: false,
        };
        app.refresh();
        Ok(app)
    }

    /// Reload state from disk and recompute live launchd statuses.
    fn refresh(&mut self) {
        self.state = load_state().unwrap_or_default();
        self.config = load_config().unwrap_or_default();
        self.server_status = self
            .state
            .servers
            .iter()
            .map(|s| daemon::status(&crate::backends::server_service_id(s)))
            .collect();
        self.php_status = self
            .state
            .php_versions
            .iter()
            .map(|p| daemon::status(&php::service_id(&p.version)))
            .collect();
        self.dns_ok = crate::dns::resolver_ok_all(&self.config.local_tlds);
        self.clamp();
    }

    fn clamp(&mut self) {
        self.sel_server = self
            .sel_server
            .min(self.state.servers.len().saturating_sub(1));
        self.sel_php = self
            .sel_php
            .min(self.state.php_versions.len().saturating_sub(1));
        self.sel_vhost = self
            .sel_vhost
            .min(self.state.vhosts.len().saturating_sub(1));
    }

    fn focus_len(&self) -> usize {
        match self.focus {
            Panel::Servers => self.state.servers.len(),
            Panel::Php => self.state.php_versions.len(),
            Panel::Vhosts => self.state.vhosts.len(),
        }
    }

    fn sel_mut(&mut self) -> &mut usize {
        match self.focus {
            Panel::Servers => &mut self.sel_server,
            Panel::Php => &mut self.sel_php,
            Panel::Vhosts => &mut self.sel_vhost,
        }
    }

    fn move_sel(&mut self, delta: isize) {
        let len = self.focus_len();
        if len == 0 {
            return;
        }
        let sel = self.sel_mut();
        let new = (*sel as isize + delta).rem_euclid(len as isize) as usize;
        *sel = new;
    }

    fn cycle_focus(&mut self, forward: bool) {
        // Visual order top→bottom: Servers, Vhosts, PHP (PHP least used, at bottom).
        self.focus = match (self.focus, forward) {
            (Panel::Servers, true) => Panel::Vhosts,
            (Panel::Vhosts, true) => Panel::Php,
            (Panel::Php, true) => Panel::Servers,
            (Panel::Servers, false) => Panel::Php,
            (Panel::Vhosts, false) => Panel::Servers,
            (Panel::Php, false) => Panel::Vhosts,
        };
    }

    /// Run an action, capturing success/error into the message line instead of
    /// tearing down the TUI.
    fn act(&mut self, label: &str, result: Result<String>) {
        self.message = match result {
            Ok(msg) => format!("{msg}"),
            Err(e) => format!("{label}: {e}"),
        };
        self.refresh();
    }

    fn selected_server_name(&self) -> Option<String> {
        self.state
            .servers
            .get(self.sel_server)
            .map(|s| s.name.clone())
    }

    fn selected_php_version(&self) -> Option<String> {
        self.state
            .php_versions
            .get(self.sel_php)
            .map(|p| p.version.clone())
    }

    fn selected_vhost_name(&self) -> Option<String> {
        self.state
            .vhosts
            .get(self.sel_vhost)
            .map(|v| v.server_name.clone())
    }
}

/// Render a single dashboard frame to plain text using ratatui's TestBackend.
/// Lets us verify TUI layout + data binding without a real terminal.
pub fn snapshot(width: u16, height: u16, modal: &str) -> Result<String> {
    let mut app = App::load()?;
    match modal {
        "wizard" => open_wizard_for_snapshot(&mut app),
        "server" => open_edit_server(&mut app),
        "newserver" => open_new_server(&mut app),
        "settings" => open_settings(&mut app),
        "php" => {
            app.php_install = Some(PhpInstallModal {
                version: "8.".into(),
                error: None,
            })
        }
        "ext" => open_ext_modal(&mut app),
        "config" => open_config_modal(&mut app),
        _ => {}
    }
    let backend = ratatui::backend::TestBackend::new(width, height);
    let mut terminal = Terminal::new(backend)?;
    terminal.draw(|f| ui::render(f, &app))?;
    let buf = terminal.backend().buffer();
    let mut out = String::new();
    for y in 0..height {
        for x in 0..width {
            if let Some(cell) = buf.cell((x, y)) {
                out.push_str(cell.symbol());
            }
        }
        out.push('\n');
    }
    Ok(out)
}

pub async fn run() -> Result<()> {
    if load_config().is_err() {
        println!("reeve is not configured. Run `reeve init` first.");
        return Ok(());
    }

    let mut terminal = setup_terminal()?;
    let mut app = App::load()?;
    let res = run_loop(&mut terminal, &mut app);
    restore_terminal(&mut terminal)?;
    res
}

fn run_loop(terminal: &mut Terminal<CrosstermBackend<Stdout>>, app: &mut App) -> Result<()> {
    loop {
        if app.force_clear {
            terminal.clear()?;
            app.force_clear = false;
        }
        terminal.draw(|f| ui::render(f, app))?;

        // Poll with a timeout so statuses refresh even without keypresses.
        if event::poll(Duration::from_millis(2000))? {
            if let Event::Key(key) = event::read()? {
                if key.kind == KeyEventKind::Press {
                    handle_key(app, key.code, key.modifiers);
                }
            }
        } else {
            app.refresh();
        }

        // A queued PHP install runs outside the alternate screen so brew's
        // (long) output is visible, then we resume the dashboard.
        if let Some(ver) = app.pending_install.take() {
            run_install_suspended(terminal, app, &ver)?;
        }

        // A queued extension add/remove (pecl is slow) runs the same way.
        if let Some(pe) = app.pending_ext.take() {
            run_ext_suspended(terminal, app, pe)?;
        }

        if app.should_quit {
            return Ok(());
        }
    }
}

fn handle_key(app: &mut App, code: KeyCode, mods: KeyModifiers) {
    // Modals capture all input while open.
    if app.confirm_remove.is_some() {
        handle_confirm_key(app, code);
        return;
    }
    if app.wizard.is_some() {
        handle_wizard_key(app, code);
        return;
    }
    if app.server_wizard.is_some() {
        handle_server_wizard_key(app, code);
        return;
    }
    if app.settings_modal.is_some() {
        handle_settings_key(app, code);
        return;
    }
    if app.php_install.is_some() {
        handle_php_install_key(app, code);
        return;
    }
    if app.confirm_remove_php.is_some() {
        handle_php_confirm_key(app, code);
        return;
    }
    if app.confirm_remove_server.is_some() {
        handle_server_confirm_key(app, code);
        return;
    }
    if app.ext_modal.is_some() {
        handle_ext_key(app, code);
        return;
    }
    if app.config_modal.is_some() {
        handle_config_key(app, code);
        return;
    }
    match code {
        KeyCode::Char('q') | KeyCode::Esc => app.should_quit = true,
        KeyCode::Char('c') if mods.contains(KeyModifiers::CONTROL) => app.should_quit = true,
        KeyCode::Tab => app.cycle_focus(true),
        KeyCode::BackTab => app.cycle_focus(false),
        // Any arrow (or hjkl) moves the selection within the focused panel.
        // Left/Right matter for the horizontal PHP row; Up/Down for the lists.
        KeyCode::Up | KeyCode::Char('k') | KeyCode::Left | KeyCode::Char('h') => app.move_sel(-1),
        KeyCode::Down | KeyCode::Char('j') | KeyCode::Right | KeyCode::Char('l') => app.move_sel(1),
        KeyCode::Enter => match app.focus {
            // Enter activates: starts a server / restarts a PHP FPM master.
            Panel::Servers => {
                if let Some(name) = app.selected_server_name() {
                    let r = ops::start_server(&name)
                        .map(|st| format!("started '{name}' — {}", st.as_str()));
                    app.act("start", r);
                }
            }
            Panel::Php => restart_selected_fpm(app),
            Panel::Vhosts => {}
        },
        KeyCode::Char('s') if app.focus == Panel::Servers => open_settings(app),
        KeyCode::Char('x') if app.focus == Panel::Servers => {
            if let Some(name) = app.selected_server_name() {
                let r = ops::stop_server(&name).map(|_| format!("stopped '{name}'"));
                app.act("stop", r);
            }
        }
        KeyCode::Char('r') => match app.focus {
            Panel::Servers => {
                if let Some(name) = app.selected_server_name() {
                    let r = ops::restart_server(&name)
                        .map(|st| format!("restarted '{name}' — {}", st.as_str()));
                    app.act("restart", r);
                }
            }
            Panel::Php => {
                // Context-aware: 'r' removes (unmanages) the selected PHP version.
                if let Some(ver) = app.selected_php_version() {
                    app.confirm_remove_php = Some(ver);
                }
            }
            Panel::Vhosts => {
                // Context-aware: 'r' removes the selected vhost (with confirm).
                if let Some(name) = app.selected_vhost_name() {
                    app.confirm_remove = Some(name);
                }
            }
        },
        KeyCode::Char('a') => {
            let r = apply_all().map(|n| format!("applied {n} server(s)"));
            app.act("apply", r);
        }
        KeyCode::Char('n') => match app.focus {
            // 'n' = new, scoped to the focused panel: server / vhost / PHP install.
            Panel::Servers => open_new_server(app),
            Panel::Vhosts => open_wizard(app),
            Panel::Php => {
                app.php_install = Some(PhpInstallModal {
                    version: String::new(),
                    error: None,
                })
            }
        },
        KeyCode::Char('v') => validate_all(app),
        KeyCode::Char('c') => open_config_modal(app),
        KeyCode::Delete | KeyCode::Backspace => match app.focus {
            // Remove the focused item (always behind a confirm).
            Panel::Servers => {
                if let Some(name) = app.selected_server_name() {
                    app.confirm_remove_server = Some(name);
                }
            }
            Panel::Vhosts => {
                if let Some(name) = app.selected_vhost_name() {
                    app.confirm_remove = Some(name);
                }
            }
            Panel::Php => {
                if let Some(ver) = app.selected_php_version() {
                    app.confirm_remove_php = Some(ver);
                }
            }
        },
        KeyCode::Char('d') if app.focus == Panel::Php => {
            if let Some(ver) = app.selected_php_version() {
                let r = ops::set_default_php(&ver).map(|_| format!("default PHP set to {ver}"));
                app.act("default", r);
            }
        }
        KeyCode::Char('e') => match app.focus {
            Panel::Vhosts => open_edit_wizard(app),
            Panel::Servers => open_edit_server(app),
            Panel::Php => open_ext_modal(app),
        },
        KeyCode::Char('D') => {
            let tlds = app.config.local_tlds.clone();
            let list = tlds
                .iter()
                .map(|t| format!("*.{t}"))
                .collect::<Vec<_>>()
                .join(", ");
            app.message = "requesting admin access for DNS setup…".into();
            let r = Brew::detect()
                .and_then(|brew| crate::dns::setup(&brew, &tlds))
                .map(|ok| {
                    if ok {
                        format!("{list} now resolve system-wide")
                    } else {
                        "dnsmasq running but some /etc/resolver files not set".to_string()
                    }
                });
            app.act("dns setup", r);
            // The admin dialog can disturb the terminal — force a clean repaint.
            app.force_clear = true;
        }
        _ => {}
    }
}

/// Which backends (parallel to `BACKENDS`) have their brew formula installed.
fn backends_installed() -> [bool; 4] {
    let mut out = [false; 4];
    if let Ok(brew) = Brew::detect() {
        for (i, b) in BACKENDS.iter().enumerate() {
            out[i] = brew.is_installed(crate::backends::backend_for(*b).formula());
        }
    }
    out
}

/// Open the server-edit modal for the selected server.
fn open_edit_server(app: &mut App) {
    let Some(s) = app.state.servers.get(app.sel_server).cloned() else {
        return;
    };
    let backend_idx = BACKENDS.iter().position(|b| *b == s.backend).unwrap_or(0);
    app.server_wizard = Some(ServerWizard {
        backend_idx,
        http: s.http_port.to_string(),
        https: s.https_port.to_string(),
        default_site: s.default_site,
        field: 0,
        error: None,
        editing: Some(s.name),
        installed: backends_installed(),
    });
}

/// Open the new-server wizard with sane defaults (caddy on 80/443).
fn open_new_server(app: &mut App) {
    app.server_wizard = Some(ServerWizard {
        backend_idx: 0,
        http: "80".into(),
        https: "443".into(),
        default_site: false,
        field: 0,
        error: None,
        editing: None,
        installed: backends_installed(),
    });
}

/// Derive a unique instance name from the backend (caddy, caddy2, caddy3, …).
fn unique_server_name(state: &State, backend: Backend) -> String {
    let base = backend.to_string();
    if !state.servers.iter().any(|s| s.name == base) {
        return base;
    }
    (2..)
        .map(|n| format!("{base}{n}"))
        .find(|cand| !state.servers.iter().any(|s| &s.name == cand))
        .unwrap_or(base)
}

fn handle_server_wizard_key(app: &mut App, code: KeyCode) {
    let w = app.server_wizard.as_mut().unwrap();
    match code {
        KeyCode::Esc => app.server_wizard = None,
        KeyCode::Enter => submit_server_wizard(app),
        KeyCode::Tab | KeyCode::Down => w.field = (w.field + 1) % SERVER_FIELDS,
        KeyCode::BackTab | KeyCode::Up => w.field = (w.field + SERVER_FIELDS - 1) % SERVER_FIELDS,
        KeyCode::Left if w.field == 0 => {
            w.backend_idx = (w.backend_idx + BACKENDS.len() - 1) % BACKENDS.len()
        }
        KeyCode::Right | KeyCode::Char(' ') if w.field == 0 => {
            w.backend_idx = (w.backend_idx + 1) % BACKENDS.len()
        }
        // Default-site toggle.
        KeyCode::Left | KeyCode::Right | KeyCode::Char(' ') if w.field == 3 => {
            w.default_site = !w.default_site
        }
        KeyCode::Backspace => match w.field {
            1 => {
                w.http.pop();
            }
            2 => {
                w.https.pop();
            }
            _ => {}
        },
        // Ports accept digits only.
        KeyCode::Char(c) if c.is_ascii_digit() => match w.field {
            1 => w.http.push(c),
            2 => w.https.push(c),
            _ => {}
        },
        _ => {}
    }
}

fn submit_server_wizard(app: &mut App) {
    let w = app.server_wizard.as_ref().unwrap();
    let editing = w.editing.clone();
    let backend = BACKENDS[w.backend_idx];
    let default_site = w.default_site;
    let http: Result<u16, _> = w.http.parse();
    let https: Result<u16, _> = w.https.parse();

    let set_err = |app: &mut App, msg: String| {
        if let Some(w) = app.server_wizard.as_mut() {
            w.error = Some(msg);
        }
    };

    let (Ok(http), Ok(https)) = (http, https) else {
        set_err(app, "Ports must be numbers (1-65535)".into());
        return;
    };
    if http == 0 || https == 0 {
        set_err(app, "Ports must be non-zero".into());
        return;
    }

    let result = (|| -> anyhow::Result<String> {
        let mut state = load_state()?;
        match &editing {
            // Edit: update the existing server (conflict-check against others).
            Some(name) => {
                for s in state.servers.iter().filter(|s| &s.name != name) {
                    if [s.http_port, s.https_port]
                        .iter()
                        .any(|p| *p == http || *p == https)
                    {
                        anyhow::bail!("port {http}/{https} conflicts with server '{}'", s.name);
                    }
                }
                let srv = state
                    .servers
                    .iter_mut()
                    .find(|s| &s.name == name)
                    .ok_or_else(|| anyhow::anyhow!("server '{name}' not found"))?;
                srv.backend = backend;
                srv.http_port = http;
                srv.https_port = https;
                srv.default_site = default_site;
                crate::state::save_state(&state)?;
                Ok(format!(
                    "updated '{name}' ({backend} :{http}/:{https}) — press 'r' to apply"
                ))
            }
            // Create: add a new instance (add_server checks dup name + port clash).
            None => {
                let name = unique_server_name(&state, backend);
                state.add_server(crate::state::Server {
                    name: name.clone(),
                    backend,
                    http_port: http,
                    https_port: https,
                    enabled: false,
                    default_site,
                    settings: Default::default(),
                })?;
                crate::state::save_state(&state)?;
                Ok(format!(
                    "added {backend} server '{name}' (:{http}/:{https}) — press enter to start"
                ))
            }
        }
    })();

    match result {
        Ok(msg) => {
            let creating = editing.is_none();
            app.server_wizard = None;
            app.message = format!("{msg}");
            app.refresh();
            // Jump focus to the freshly-added server for an easy start.
            if creating && !app.state.servers.is_empty() {
                app.focus = Panel::Servers;
                app.sel_server = app.state.servers.len() - 1;
            }
        }
        Err(e) => set_err(app, e.to_string()),
    }
}

/// Confirm-key handler for "remove server <name>?".
fn handle_server_confirm_key(app: &mut App, code: KeyCode) {
    match code {
        KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
            if let Some(name) = app.confirm_remove_server.take() {
                let r = remove_server(&name)
                    .map(|n| format!("removed server '{name}' (and {n} vhost(s))"));
                app.act("remove server", r);
            }
        }
        _ => app.confirm_remove_server = None,
    }
}

/// Stop + unmanage a server and drop it (with its vhosts) from state.
/// Returns the number of vhosts removed.
fn remove_server(name: &str) -> Result<usize> {
    let mut state = load_state()?;
    let Some(server) = state.servers.iter().find(|s| s.name == name).cloned() else {
        anyhow::bail!("server '{name}' not found");
    };
    // Tear down its launchd service (best-effort; it may already be stopped).
    daemon::uninstall(&crate::backends::server_service_id(&server)).ok();
    state.servers.retain(|s| s.name != name);
    let before = state.vhosts.len();
    state.vhosts.retain(|v| v.server != name);
    let removed = before - state.vhosts.len();
    crate::state::save_state(&state)?;
    Ok(removed)
}

/// Run every server's native config test, summarizing into the message line.
fn validate_all(app: &mut App) {
    let result = (|| -> anyhow::Result<String> {
        let brew = Brew::detect()?;
        let state = load_state()?;
        if state.servers.is_empty() {
            return Ok("no servers to validate".into());
        }
        let mut failures = Vec::new();
        for s in &state.servers {
            if let Err(e) = crate::backends::backend_for(s.backend).validate(s, &brew) {
                let first = e
                    .to_string()
                    .lines()
                    .next()
                    .unwrap_or("invalid")
                    .to_string();
                failures.push(format!("{}: {first}", s.name));
            }
        }
        if failures.is_empty() {
            Ok(format!(
                "all {} server config(s) valid",
                state.servers.len()
            ))
        } else {
            anyhow::bail!("{}", failures.join("; "))
        }
    })();
    app.act("validate", result);
}

/// Open the PHP extensions manager for the selected version.
fn open_ext_modal(app: &mut App) {
    let Some(ver) = app.selected_php_version() else {
        app.message = "No PHP version selected".into();
        return;
    };
    match Brew::detect().and_then(|brew| php::extensions::list(&brew, &ver)) {
        Ok(mut loaded) => {
            loaded.sort_by_key(|s| s.to_lowercase());
            app.ext_modal = Some(ExtModal {
                version: ver,
                loaded,
                input: String::new(),
                sel: 0,
                error: None,
            });
        }
        Err(e) => app.message = format!("✗ extensions: {e}"),
    }
}

/// Key handling for the extensions modal: type a name + Enter to add; with the
/// input empty, ↑↓ select and Enter/Del remove the highlighted extension.
fn handle_ext_key(app: &mut App, code: KeyCode) {
    let m = app.ext_modal.as_mut().unwrap();
    m.error = None;
    let queue_remove = |app: &mut App| {
        let m = app.ext_modal.as_ref().unwrap();
        if let Some(name) = m.loaded.get(m.sel).cloned() {
            let ver = m.version.clone();
            app.ext_modal = None;
            app.pending_ext = Some(PendingExt {
                version: ver,
                action: ExtAction::Remove(name),
            });
        }
    };
    match code {
        KeyCode::Esc => app.ext_modal = None,
        KeyCode::Up => m.sel = m.sel.saturating_sub(1),
        KeyCode::Down if !m.loaded.is_empty() => {
            m.sel = (m.sel + 1).min(m.loaded.len() - 1);
        }
        KeyCode::Delete => queue_remove(app),
        KeyCode::Enter => {
            let name = m.input.trim().to_string();
            if name.is_empty() {
                // No text typed → remove the highlighted loaded extension.
                queue_remove(app);
            } else if m.loaded.iter().any(|x| x.eq_ignore_ascii_case(&name)) {
                m.error = Some(format!("{name} is already loaded"));
            } else {
                let ver = m.version.clone();
                app.ext_modal = None;
                app.pending_ext = Some(PendingExt {
                    version: ver,
                    action: ExtAction::Add(name),
                });
            }
        }
        KeyCode::Backspace => {
            m.input.pop();
        }
        KeyCode::Char(c) if c.is_ascii_alphanumeric() || c == '_' || c == '-' => m.input.push(c),
        _ => {}
    }
}

/// Open the global preferences modal (local TLD, sites root, default backend).
fn open_config_modal(app: &mut App) {
    let cfg = &app.config;
    let backend_idx = BACKENDS
        .iter()
        .position(|b| b.as_str() == cfg.default_backend)
        .unwrap_or(0);
    let tld = cfg.local_tlds.join(" ");
    app.config_modal = Some(ConfigModal {
        tld: tld.clone(),
        sites_root: cfg.sites_root.clone(),
        backend_idx,
        field: 0,
        error: None,
        orig_tld: tld,
    });
}

fn handle_config_key(app: &mut App, code: KeyCode) {
    let m = app.config_modal.as_mut().unwrap();
    match code {
        KeyCode::Esc => app.config_modal = None,
        KeyCode::Enter => submit_config(app),
        KeyCode::Tab | KeyCode::Down => m.field = (m.field + 1) % CONFIG_FIELDS,
        KeyCode::BackTab | KeyCode::Up => m.field = (m.field + CONFIG_FIELDS - 1) % CONFIG_FIELDS,
        KeyCode::Left if m.field == 2 => {
            m.backend_idx = (m.backend_idx + BACKENDS.len() - 1) % BACKENDS.len()
        }
        KeyCode::Right if m.field == 2 => m.backend_idx = (m.backend_idx + 1) % BACKENDS.len(),
        KeyCode::Backspace => match m.field {
            0 => {
                m.tld.pop();
            }
            1 => {
                m.sites_root.pop();
            }
            _ => {}
        },
        KeyCode::Char(c) => match m.field {
            // TLDs: DNS labels separated by space or comma (e.g. "test lan localhost").
            0 if c.is_ascii_alphanumeric() || c == '-' || c == ' ' || c == ',' => {
                m.tld.push(c.to_ascii_lowercase())
            }
            1 => m.sites_root.push(c),
            2 if c == ' ' => m.backend_idx = (m.backend_idx + 1) % BACKENDS.len(),
            _ => {}
        },
        _ => {}
    }
}

fn submit_config(app: &mut App) {
    let m = app.config_modal.as_ref().unwrap();
    let raw = m.tld.clone();
    let sites_root = m.sites_root.trim().to_string();
    let backend = BACKENDS[m.backend_idx];
    let orig_tld = m.orig_tld.clone();

    let set_err = |app: &mut App, msg: String| {
        if let Some(m) = app.config_modal.as_mut() {
            m.error = Some(msg);
        }
    };

    // Parse space/comma-separated TLDs, each a clean DNS label.
    let mut tlds = Vec::new();
    for tok in raw.split([' ', ',']).filter(|t| !t.is_empty()) {
        let t = tok.trim_matches('.').to_lowercase();
        if t.is_empty() {
            continue;
        }
        if !t.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
            set_err(
                app,
                format!("'{tok}' is not a valid TLD (letters/digits/hyphens)"),
            );
            return;
        }
        if !tlds.contains(&t) {
            tlds.push(t);
        }
    }
    if tlds.is_empty() {
        set_err(
            app,
            "Enter at least one TLD (e.g. test lan localhost)".into(),
        );
        return;
    }
    if sites_root.is_empty() {
        set_err(app, "Sites root is required".into());
        return;
    }

    let changed = tlds.join(" ") != orig_tld;
    let result = (|| -> anyhow::Result<()> {
        let mut cfg = load_config()?;
        cfg.local_tlds = tlds.clone();
        cfg.sites_root = sites_root.clone();
        cfg.default_backend = backend.as_str().to_string();
        save_config(&cfg)
    })();

    match result {
        Ok(()) => {
            app.config_modal = None;
            let list = tlds
                .iter()
                .map(|t| format!(".{t}"))
                .collect::<Vec<_>>()
                .join(" ");
            app.message = if changed {
                format!("✓ config saved — TLDs: {list}; press D to set up DNS")
            } else {
                "✓ config saved".into()
            };
            app.refresh();
        }
        Err(e) => set_err(app, e.to_string()),
    }
}

/// Open the per-backend Settings modal for the selected server.
fn open_settings(app: &mut App) {
    let Some(s) = app.state.servers.get(app.sel_server).cloned() else {
        return;
    };
    let defs = settings_defs(s.backend);
    if defs.is_empty() {
        app.message = format!("{} has no tunable settings yet", s.backend);
        return;
    }
    let values = defs
        .iter()
        .map(|d| s.setting(d.key, d.default).to_string())
        .collect();
    app.settings_modal = Some(SettingsModal {
        server_name: s.name,
        backend: s.backend,
        values,
        field: 0,
        error: None,
    });
}

fn handle_settings_key(app: &mut App, code: KeyCode) {
    let n = app
        .settings_modal
        .as_ref()
        .map(|m| m.values.len())
        .unwrap_or(0)
        .max(1);
    let m = app.settings_modal.as_mut().unwrap();
    match code {
        KeyCode::Esc => app.settings_modal = None,
        KeyCode::Enter => submit_settings(app),
        KeyCode::Tab | KeyCode::Down => m.field = (m.field + 1) % n,
        KeyCode::BackTab | KeyCode::Up => m.field = (m.field + n - 1) % n,
        KeyCode::Backspace => {
            if let Some(v) = m.values.get_mut(m.field) {
                v.pop();
            }
        }
        KeyCode::Char(c) => {
            if let Some(v) = m.values.get_mut(m.field) {
                v.push(c);
            }
        }
        _ => {}
    }
}

fn submit_settings(app: &mut App) {
    let m = app.settings_modal.as_ref().unwrap();
    let name = m.server_name.clone();
    let defs = settings_defs(m.backend);
    let values = m.values.clone();

    let result = (|| -> anyhow::Result<()> {
        let mut state = load_state()?;
        let srv = state
            .servers
            .iter_mut()
            .find(|s| s.name == name)
            .ok_or_else(|| anyhow::anyhow!("server '{name}' not found"))?;
        for (def, val) in defs.iter().zip(values.iter()) {
            let val = val.trim();
            // Store only non-default values to keep state minimal.
            if val.is_empty() || val == def.default {
                srv.settings.remove(def.key);
            } else {
                srv.settings.insert(def.key.to_string(), val.to_string());
            }
        }
        crate::state::save_state(&state)
    })();

    match result {
        Ok(()) => {
            app.settings_modal = None;
            app.message = format!("✓ saved settings for '{name}' — press 'r' to apply");
            app.refresh();
        }
        Err(e) => {
            if let Some(m) = app.settings_modal.as_mut() {
                m.error = Some(e.to_string());
            }
        }
    }
}

fn restart_selected_fpm(app: &mut App) {
    if let Some(ver) = app.selected_php_version() {
        let r = Brew::detect()
            .and_then(|brew| php::ensure_fpm_running(&brew, &ver))
            .map(|_| format!("restarted PHP {ver} FPM"));
        app.act("php restart", r);
    }
}

fn handle_php_install_key(app: &mut App, code: KeyCode) {
    let m = app.php_install.as_mut().unwrap();
    match code {
        KeyCode::Esc => app.php_install = None,
        KeyCode::Enter => {
            let ver = m.version.trim().to_string();
            if ver.is_empty() {
                m.error = Some("Enter a version, e.g. 8.3".into());
            } else if app.state.php_versions.iter().any(|p| p.version == ver) {
                m.error = Some(format!("PHP {ver} is already managed"));
            } else {
                // Defer to run_loop, which suspends the TUI to show brew output.
                app.php_install = None;
                app.pending_install = Some(ver);
            }
        }
        KeyCode::Backspace => {
            m.version.pop();
        }
        // Versions are digits and dots.
        KeyCode::Char(c) if c.is_ascii_digit() || c == '.' => m.version.push(c),
        _ => {}
    }
}

fn handle_php_confirm_key(app: &mut App, code: KeyCode) {
    match code {
        KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
            if let Some(ver) = app.confirm_remove_php.take() {
                let r = ops::remove_php(&ver).map(|_| format!("removed PHP {ver}"));
                app.act("remove php", r);
            }
        }
        _ => app.confirm_remove_php = None,
    }
}

fn handle_confirm_key(app: &mut App, code: KeyCode) {
    match code {
        KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => {
            if let Some(name) = app.confirm_remove.take() {
                let r = remove_vhost(&name).map(|_| format!("removed vhost '{name}'"));
                app.act("remove", r);
            }
        }
        _ => app.confirm_remove = None,
    }
}

/// Remove a vhost from state by host name.
fn remove_vhost(name: &str) -> Result<()> {
    let mut state = load_state()?;
    let before = state.vhosts.len();
    state.vhosts.retain(|v| v.server_name != name);
    if state.vhosts.len() == before {
        anyhow::bail!("vhost '{name}' not found");
    }
    crate::state::save_state(&state)
}

/// Test helper: force the wizard open (on the Doc root field) for a snapshot.
fn open_wizard_for_snapshot(app: &mut App) {
    open_wizard(app);
    if let Some(w) = app.wizard.as_mut() {
        w.field = FIELD_DOCROOT;
    }
}

/// Open the new-vhost wizard, or explain what's missing.
fn open_wizard(app: &mut App) {
    if app.state.php_versions.is_empty() {
        app.message = "Install a PHP version first: `reeve php install 8.3`".into();
        return;
    }
    if app.state.servers.is_empty() {
        app.message = "Add a server first: `reeve server add caddy`".into();
        return;
    }
    // Pre-seed the doc root with the sites root (trailing slash) so the
    // autocomplete dropdown immediately lists projects there.
    let sites_root = format!("{}/", app.config.sites_root.trim_end_matches('/'));
    app.wizard = Some(VhostWizard {
        server_name: String::new(),
        docroot: sites_root,
        php_idx: app.sel_php.min(app.state.php_versions.len() - 1),
        server_idx: app.sel_server.min(app.state.servers.len() - 1),
        ssl: false,
        field: 0,
        error: None,
        editing: None,
        dropdown_open: true,
        path_sel: None,
    });
}

/// Open the wizard pre-filled to edit the selected vhost.
fn open_edit_wizard(app: &mut App) {
    let Some(v) = app.state.vhosts.get(app.sel_vhost).cloned() else {
        return;
    };
    let php_idx = app
        .state
        .php_versions
        .iter()
        .position(|p| p.version == v.php_version)
        .unwrap_or(0);
    let server_idx = app
        .state
        .servers
        .iter()
        .position(|s| s.name == v.server)
        .unwrap_or(0);
    app.wizard = Some(VhostWizard {
        server_name: v.server_name.clone(),
        docroot: v.docroot,
        php_idx,
        server_idx,
        ssl: v.ssl,
        field: 0,
        error: None,
        editing: Some(v.server_name),
        dropdown_open: true,
        path_sel: None,
    });
}

/// The Doc root field index in the wizard.
const FIELD_DOCROOT: usize = 1;

fn handle_wizard_key(app: &mut App, code: KeyCode) {
    let php_len = app.state.php_versions.len();
    let srv_len = app.state.servers.len();
    let w = app.wizard.as_mut().unwrap();

    // ── Doc root with the dropdown OPEN: arrows navigate the list, Esc closes
    // just the dropdown, Tab/Shift-Tab still move fields (reliable escape).
    if w.dropdown_active() {
        let count = w.path_suggestions().len();
        match code {
            KeyCode::Esc => {
                w.dropdown_open = false;
                w.path_sel = None;
            }
            KeyCode::Down if count > 0 => {
                w.path_sel = Some(match w.path_sel {
                    None => 0,
                    Some(i) => (i + 1).min(count - 1),
                });
            }
            KeyCode::Up => match w.path_sel {
                Some(i) if i > 0 => w.path_sel = Some(i - 1),
                _ => w.path_sel = None,
            },
            KeyCode::Enter | KeyCode::Right => commit_highlighted_path(w),
            KeyCode::Tab => tab_complete_path(w),
            KeyCode::BackTab => w.prev_field(),
            KeyCode::Backspace => {
                w.docroot.pop();
                w.path_sel = None;
            }
            KeyCode::Char(c) => {
                w.docroot.push(c);
                w.path_sel = None;
            }
            _ => {}
        }
        return;
    }

    // ── All other fields (and Doc root with a dismissed dropdown).
    match code {
        KeyCode::Esc => app.wizard = None,
        KeyCode::Enter => submit_wizard(app),
        KeyCode::Tab | KeyCode::Down => w.next_field(),
        KeyCode::BackTab | KeyCode::Up => w.prev_field(),
        KeyCode::Left => wizard_adjust(w, php_len, srv_len, false),
        KeyCode::Right => wizard_adjust(w, php_len, srv_len, true),
        KeyCode::Backspace => match w.field {
            0 => {
                w.server_name.pop();
            }
            FIELD_DOCROOT => {
                // Typing on a dismissed dropdown reopens it.
                w.docroot.pop();
                w.dropdown_open = true;
            }
            _ => {}
        },
        KeyCode::Char(' ') => match w.field {
            0 => w.server_name.push(' '),
            2 | 3 => wizard_adjust(w, php_len, srv_len, true),
            4 => w.ssl = !w.ssl,
            _ => {}
        },
        KeyCode::Char(c) => match w.field {
            0 => w.server_name.push(c),
            FIELD_DOCROOT => {
                w.docroot.push(c);
                w.dropdown_open = true;
            }
            _ => {}
        },
        _ => {}
    }
}

/// Commit the highlighted dropdown entry (or the first directory if none is
/// highlighted) into `docroot`, keeping the dropdown open on the new listing.
fn commit_highlighted_path(w: &mut VhostWizard) {
    let sugg = w.path_suggestions();
    let entry = w
        .path_sel
        .and_then(|i| sugg.get(i))
        .or_else(|| sugg.iter().find(|e| e.is_dir));
    if let Some(e) = entry {
        w.docroot = pathpick::commit_entry(&w.docroot, e);
        w.path_sel = None;
    }
}

/// Shell-style Tab completion for the Doc root field.
fn tab_complete_path(w: &mut VhostWizard) {
    let all = pathpick::read_dir_filtered(&w.docroot, usize::MAX);
    if all.is_empty() {
        // Nothing to complete — advance to the next field.
        w.next_field();
        return;
    }
    if all.len() == 1 {
        w.docroot = pathpick::commit_entry(&w.docroot, &all[0]);
        return;
    }
    let names: Vec<&str> = all.iter().map(|e| e.name.as_str()).collect();
    let lcp = pathpick::longest_common_prefix(&names);
    let (dir, prefix) = pathpick::split_path(&w.docroot);
    if lcp.chars().count() > prefix.chars().count() {
        // Extend to the common prefix and stay so the user can keep narrowing.
        w.docroot = format!("{dir}{lcp}");
    } else {
        // Already at the common prefix — nothing more to complete, so move on
        // instead of trapping the user on the field.
        w.next_field();
    }
}

/// Cycle the choice/toggle fields (PHP, Server, SSL).
fn wizard_adjust(w: &mut VhostWizard, php_len: usize, srv_len: usize, forward: bool) {
    let step = |i: usize, len: usize| {
        if len == 0 {
            0
        } else if forward {
            (i + 1) % len
        } else {
            (i + len - 1) % len
        }
    };
    match w.field {
        2 => w.php_idx = step(w.php_idx, php_len),
        3 => w.server_idx = step(w.server_idx, srv_len),
        4 => w.ssl = !w.ssl,
        _ => {}
    }
}

fn submit_wizard(app: &mut App) {
    let w = app.wizard.as_ref().unwrap();
    let name = w.server_name.trim().to_string();
    let php = app
        .state
        .php_versions
        .get(w.php_idx)
        .map(|p| p.version.clone());
    let server = app.state.servers.get(w.server_idx).map(|s| s.name.clone());
    let ssl = w.ssl;
    let raw_root = w.docroot.trim();
    let docroot = if raw_root.is_empty() {
        format!("{}/{}", app.config.sites_root.trim_end_matches('/'), name)
    } else if raw_root.ends_with('/') {
        // Left on a directory — treat it as the parent and use the host as the
        // project folder, e.g. ~/Sites/ + app.test → ~/Sites/app.test.
        format!("{raw_root}{name}")
    } else {
        raw_root.to_string()
    };

    let set_err = |app: &mut App, msg: String| {
        if let Some(w) = app.wizard.as_mut() {
            w.error = Some(msg);
        }
    };

    if name.is_empty() {
        set_err(app, "Hostname is required".into());
        return;
    }
    let (Some(php), Some(server)) = (php, server) else {
        set_err(app, "Pick a PHP version and a server".into());
        return;
    };

    let editing = app.wizard.as_ref().and_then(|w| w.editing.clone());

    let result = (|| -> anyhow::Result<()> {
        let mut state = load_state()?;
        // Editing replaces the original (handles renames too).
        if let Some(orig) = &editing {
            state.vhosts.retain(|v| &v.server_name != orig);
        }
        state.add_vhost(crate::state::Vhost {
            server_name: name.clone(),
            server: server.clone(),
            docroot: docroot.clone(),
            php_version: php.clone(),
            ssl,
        })?;
        crate::state::save_state(&state)
    })();

    match result {
        Ok(()) => {
            app.wizard = None;
            let verb = if editing.is_some() {
                "updated"
            } else {
                "created"
            };
            app.message = format!("{verb} vhost '{name}' on '{server}' (PHP {php}) — press 'r' on the server to apply");
            app.refresh();
        }
        Err(e) => set_err(app, e.to_string()),
    }
}

/// Re-render + restart every enabled server.
fn apply_all() -> Result<usize> {
    let state = load_state()?;
    let mut n = 0;
    for server in state.servers.iter().filter(|s| s.enabled) {
        ops::restart_server(&server.name)?;
        n += 1;
    }
    Ok(n)
}

/// Suspend the TUI, run a (slow) PHP install with visible brew output, wait for
/// a keypress, then resume the dashboard.
fn run_install_suspended(
    terminal: &mut Terminal<CrosstermBackend<Stdout>>,
    app: &mut App,
    version: &str,
) -> Result<()> {
    restore_terminal(terminal)?;
    println!("\n── Installing PHP {version} (this can take a few minutes) ──\n");
    let result = ops::install_php(version);
    match &result {
        Ok(()) => println!("\n✓ PHP {version} installed. Press any key to return…"),
        Err(e) => println!("\n✗ install failed: {e}\nPress any key to return…"),
    }
    // Wait for a keypress so the output stays readable.
    let _ = enable_raw_mode();
    loop {
        if event::poll(Duration::from_millis(500))? {
            if let Event::Key(k) = event::read()? {
                if k.kind == KeyEventKind::Press {
                    break;
                }
            }
        }
    }
    let _ = disable_raw_mode();
    *terminal = setup_terminal()?;
    app.message = match result {
        Ok(()) => format!("✓ installed PHP {version}"),
        Err(e) => format!("✗ install PHP {version}: {e}"),
    };
    app.refresh();
    Ok(())
}

/// Suspend the TUI, run a (slow) pecl add/remove with visible output, wait for
/// a keypress, then resume the dashboard.
fn run_ext_suspended(
    terminal: &mut Terminal<CrosstermBackend<Stdout>>,
    app: &mut App,
    pe: PendingExt,
) -> Result<()> {
    restore_terminal(terminal)?;
    let (verb, name) = match &pe.action {
        ExtAction::Add(n) => ("Installing", n.clone()),
        ExtAction::Remove(n) => ("Removing", n.clone()),
    };
    println!("\n── {verb} {name} for PHP {} ──\n", pe.version);
    let result = run_ext_op(&pe);
    match &result {
        Ok(msg) => println!("\n{msg}. Press any key to return…"),
        Err(e) => println!("\n{e}\nPress any key to return…"),
    }
    let _ = enable_raw_mode();
    loop {
        if event::poll(Duration::from_millis(500))? {
            if let Event::Key(k) = event::read()? {
                if k.kind == KeyEventKind::Press {
                    break;
                }
            }
        }
    }
    let _ = disable_raw_mode();
    *terminal = setup_terminal()?;
    app.message = match result {
        Ok(msg) => format!("{msg}"),
        Err(e) => format!("{e}"),
    };
    app.refresh();
    Ok(())
}

/// The actual pecl call + FPM restart for a queued extension op.
fn run_ext_op(pe: &PendingExt) -> Result<String> {
    let brew = Brew::detect()?;
    match &pe.action {
        ExtAction::Add(name) => {
            php::extensions::add(&brew, &pe.version, name)?;
            php::ensure_fpm_running(&brew, &pe.version)?;
            Ok(format!(
                "{name} installed for PHP {} (FPM restarted)",
                pe.version
            ))
        }
        ExtAction::Remove(name) => {
            php::extensions::remove(&brew, &pe.version, name)?;
            php::ensure_fpm_running(&brew, &pe.version)?;
            Ok(format!(
                "{name} removed from PHP {} (FPM restarted)",
                pe.version
            ))
        }
    }
}

fn setup_terminal() -> Result<Terminal<CrosstermBackend<Stdout>>> {
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    Ok(Terminal::new(CrosstermBackend::new(stdout))?)
}

fn restore_terminal(terminal: &mut Terminal<CrosstermBackend<Stdout>>) -> Result<()> {
    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    terminal.show_cursor()?;
    Ok(())
}