siggy 1.8.0

Terminal-based Signal messenger client with vim keybindings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
//! First-run wizard.
//!
//! Multi-step flow that detects signal-cli on PATH, prompts for the user's
//! E.164 phone, and hands off to [`crate::link`] for QR-code device
//! linking. Persists the resolved signal-cli path back to [`crate::config`]
//! so subsequent launches skip detection.

use std::io;
use std::time::Duration;

use anyhow::Result;
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use ratatui::{
    Terminal,
    backend::CrosstermBackend,
    layout::{Constraint, Flex, Layout},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Paragraph, Wrap},
};
use tokio::process::Command;

use crate::config::Config;
use crate::link;

pub enum SetupResult {
    /// Wizard finished successfully, use this config.
    Completed(Box<Config>),
    /// User had a valid config, no setup needed.
    Skipped,
    /// User cancelled during setup.
    Cancelled,
}

#[derive(Clone, Copy, PartialEq)]
enum Step {
    SignalCli,
    Account,
    Linking,
    Preferences,
    Done,
}

pub async fn run_setup(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    config: &Config,
    force: bool,
) -> Result<SetupResult> {
    if !force && !config.needs_setup() {
        return Ok(SetupResult::Skipped);
    }

    let mut working_config = config.clone();
    let mut step = Step::SignalCli;
    let mut signal_cli_path = working_config.signal_cli_path.clone();
    let mut phone_input = String::new();
    let mut phone_cursor: usize = 0;
    let mut phone_error: Option<String> = None;
    let mut signal_cli_found = false;
    let mut signal_cli_location = String::new();
    let mut custom_path_mode = false;
    let mut custom_path_input = String::new();
    let mut custom_path_cursor: usize = 0;

    loop {
        match step {
            Step::SignalCli => {
                // Check for signal-cli
                if !signal_cli_found {
                    let (found, location, resolved) = check_signal_cli(&signal_cli_path).await;
                    signal_cli_found = found;
                    signal_cli_location = location;
                    if found {
                        // Persist the invocation that actually worked — `where`/`which`
                        // may have resolved a .bat/.cmd that Rust's Command couldn't
                        // find by bare name.
                        signal_cli_path = resolved;
                    }
                }

                terminal.draw(|frame| {
                    draw_signal_cli_step(
                        frame,
                        signal_cli_found,
                        &signal_cli_location,
                        custom_path_mode,
                        &custom_path_input,
                        custom_path_cursor,
                    );
                })?;

                if signal_cli_found && !custom_path_mode {
                    // Auto-advance after a brief pause
                    tokio::time::sleep(Duration::from_secs(1)).await;
                    working_config.signal_cli_path = signal_cli_path.clone();
                    step = Step::Account;
                    continue;
                }

                // Wait for user input
                if event::poll(Duration::from_millis(50))?
                    && let Event::Key(key) = event::read()?
                {
                    if key.kind != KeyEventKind::Press {
                        continue;
                    }
                    match (key.modifiers, key.code) {
                        (KeyModifiers::CONTROL, KeyCode::Char('c')) => {
                            return Ok(SetupResult::Cancelled);
                        }
                        (_, KeyCode::Esc) if custom_path_mode => {
                            custom_path_mode = false;
                        }
                        (_, KeyCode::Esc) => {
                            return Ok(SetupResult::Cancelled);
                        }
                        _ if custom_path_mode => match key.code {
                            KeyCode::Enter if !custom_path_input.is_empty() => {
                                signal_cli_path = custom_path_input.clone();
                                signal_cli_found = false;
                                custom_path_mode = false;
                                // Will re-check on next loop
                            }
                            KeyCode::Backspace if custom_path_cursor > 0 => {
                                custom_path_cursor -= 1;
                                custom_path_input.remove(custom_path_cursor);
                            }
                            KeyCode::Left => {
                                custom_path_cursor = custom_path_cursor.saturating_sub(1);
                            }
                            KeyCode::Right if custom_path_cursor < custom_path_input.len() => {
                                custom_path_cursor += 1;
                            }
                            KeyCode::Char(c) => {
                                custom_path_input.insert(custom_path_cursor, c);
                                custom_path_cursor += 1;
                            }
                            _ => {}
                        },
                        (_, KeyCode::Enter) => {
                            // Retry check
                            signal_cli_found = false;
                        }
                        (_, KeyCode::Char('p')) => {
                            // Enter custom path mode
                            custom_path_mode = true;
                            custom_path_input.clear();
                            custom_path_cursor = 0;
                        }
                        _ => {}
                    }
                }
            }

            Step::Account => {
                terminal.draw(|frame| {
                    draw_account_step(frame, &phone_input, phone_cursor, phone_error.as_deref());
                })?;

                if event::poll(Duration::from_millis(50))?
                    && let Event::Key(key) = event::read()?
                {
                    if key.kind != KeyEventKind::Press {
                        continue;
                    }
                    match (key.modifiers, key.code) {
                        (KeyModifiers::CONTROL, KeyCode::Char('c')) => {
                            return Ok(SetupResult::Cancelled);
                        }
                        (_, KeyCode::Esc) => {
                            step = Step::SignalCli;
                            signal_cli_found = false;
                            custom_path_mode = false;
                            phone_input.clear();
                            phone_cursor = 0;
                            phone_error = None;
                        }
                        (_, KeyCode::Enter) => match validate_phone(&phone_input) {
                            Ok(()) => {
                                working_config.account = phone_input.clone();
                                phone_error = None;
                                step = Step::Linking;
                            }
                            Err(msg) => {
                                phone_error = Some(msg);
                            }
                        },
                        (_, KeyCode::Backspace) => {
                            if phone_cursor > 0 {
                                phone_cursor -= 1;
                                phone_input.remove(phone_cursor);
                            }
                            phone_error = None;
                        }
                        (_, KeyCode::Left) => {
                            phone_cursor = phone_cursor.saturating_sub(1);
                        }
                        (_, KeyCode::Right) if phone_cursor < phone_input.len() => {
                            phone_cursor += 1;
                        }
                        (_, KeyCode::Char(c)) => {
                            phone_input.insert(phone_cursor, c);
                            phone_cursor += 1;
                            phone_error = None;
                        }
                        _ => {}
                    }
                }
            }

            Step::Linking => {
                // Check if already registered
                let registered = link::check_account_registered(&working_config)
                    .await
                    .unwrap_or(false);
                if registered {
                    // Already registered, skip linking
                    terminal.draw(|frame| {
                        draw_registered_screen(frame, &working_config.account);
                    })?;
                    tokio::time::sleep(Duration::from_secs(1)).await;
                    step = Step::Preferences;
                    continue;
                }

                // Run linking flow
                match link::run_linking_flow(terminal, &working_config).await {
                    Ok(link::LinkResult::Success) => {
                        step = Step::Preferences;
                    }
                    Ok(link::LinkResult::Cancelled) => {
                        step = Step::Account;
                    }
                    Err(e) => {
                        let msg = format!("{e}");
                        {
                            // Show error, let user retry or go back
                            terminal.draw(|frame| {
                                draw_link_error(frame, &msg);
                            })?;
                            loop {
                                if event::poll(Duration::from_millis(50))?
                                    && let Event::Key(key) = event::read()?
                                {
                                    if key.kind != KeyEventKind::Press {
                                        continue;
                                    }
                                    match key.code {
                                        KeyCode::Enter => {
                                            // Retry linking
                                            break;
                                        }
                                        KeyCode::Esc => {
                                            step = Step::Account;
                                            break;
                                        }
                                        _ => {}
                                    }
                                }
                            }
                        }
                    }
                }
            }

            Step::Preferences => {
                terminal.draw(|frame| {
                    draw_preferences_step(frame, &working_config);
                })?;

                if event::poll(Duration::from_millis(50))?
                    && let Event::Key(key) = event::read()?
                {
                    if key.kind != KeyEventKind::Press {
                        continue;
                    }
                    match (key.modifiers, key.code) {
                        (KeyModifiers::CONTROL, KeyCode::Char('c')) => {
                            return Ok(SetupResult::Cancelled);
                        }
                        (_, KeyCode::Char('1')) => {
                            working_config.notify_direct = !working_config.notify_direct;
                        }
                        (_, KeyCode::Char('2')) => {
                            working_config.notify_group = !working_config.notify_group;
                        }
                        (_, KeyCode::Enter) => {
                            step = Step::Done;
                        }
                        (_, KeyCode::Esc) => {
                            // Skip preferences and proceed with defaults
                            step = Step::Done;
                        }
                        _ => {}
                    }
                }
            }

            Step::Done => {
                // Save config and finish
                working_config.save()?;

                terminal.draw(|frame| {
                    draw_done_screen(frame);
                })?;
                tokio::time::sleep(Duration::from_millis(1500)).await;

                return Ok(SetupResult::Completed(Box::new(working_config)));
            }
        }
    }
}

/// Check whether signal-cli can be invoked at `path`.
///
/// Returns `(found, display_location, resolved_path)`:
/// - `found`: whether a working invocation was discovered
/// - `display_location`: a pretty string for the wizard UI
/// - `resolved_path`: the invocation the caller should store in config
///
/// On Windows, `Command::new("foo")` only searches for `foo.exe` in PATH, while
/// `where foo` also matches `.bat`/`.cmd` via PATHEXT. That asymmetry used to
/// let the wizard report success via the `where` fallback and then fail at the
/// linking step when it re-tried the unspawnable bare name. We now verify that
/// whatever path we return can actually be spawned.
async fn check_signal_cli(path: &str) -> (bool, String, String) {
    // Try the path as given.
    if let Some(display) = try_spawn_version(path).await {
        return (true, display, path.to_string());
    }

    // Windows: try batch-file extensions before falling back to `where`. Rust's
    // Command invokes `.bat`/`.cmd` via cmd.exe when given the explicit extension,
    // but it does not search PATHEXT for them by bare name. Scoop and manual
    // installs commonly place `signal-cli.bat` in PATH without a matching `.exe`.
    // `.exe` is intentionally omitted: the bare-name probe above already finds
    // `.exe` via PATH, and `.ps1` is omitted because Rust's Command cannot spawn
    // PowerShell scripts directly.
    #[cfg(windows)]
    for ext in [".bat", ".cmd"] {
        let candidate = format!("{path}{ext}");
        if let Some(display) = try_spawn_version(&candidate).await {
            return (true, display, candidate);
        }
    }

    // Fallback: use `where`/`which` to resolve a full path, then verify it works.
    let which_cmd = if cfg!(windows) { "where" } else { "which" };
    if let Ok(output) = Command::new(which_cmd)
        .arg(path)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .output()
        .await
        && output.status.success()
    {
        let raw = String::from_utf8_lossy(&output.stdout);
        for candidate in raw.lines() {
            let candidate = candidate.trim();
            if candidate.is_empty() {
                continue;
            }
            if let Some(display) = try_spawn_version(candidate).await {
                return (true, display, candidate.to_string());
            }
        }
    }

    (false, String::new(), path.to_string())
}

/// Try to run `<path> --version`. Returns a pretty display string on success.
async fn try_spawn_version(path: &str) -> Option<String> {
    let output = Command::new(path)
        .arg("--version")
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .output()
        .await
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if version.is_empty() {
        Some(path.to_string())
    } else {
        Some(format!("{path} ({version})"))
    }
}

fn validate_phone(input: &str) -> Result<(), String> {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return Err("Phone number cannot be empty".to_string());
    }
    if !trimmed.starts_with('+') {
        return Err("Must start with + (E.164 format)".to_string());
    }
    if trimmed.len() < 8 {
        return Err("Phone number too short".to_string());
    }
    if !trimmed[1..].chars().all(|c| c.is_ascii_digit()) {
        return Err("Only digits allowed after +".to_string());
    }
    Ok(())
}

fn step_label(current: Step) -> &'static str {
    match current {
        Step::SignalCli => "Step 1 of 4",
        Step::Account => "Step 2 of 4",
        Step::Linking => "Step 3 of 4",
        Step::Preferences => "Step 4 of 4",
        Step::Done => "Complete",
    }
}

fn draw_signal_cli_step(
    frame: &mut ratatui::Frame,
    found: bool,
    location: &str,
    custom_path_mode: bool,
    custom_path_input: &str,
    custom_path_cursor: usize,
) {
    let area = frame.area();

    let [_, content_area, _] = Layout::vertical([
        Constraint::Min(1),
        Constraint::Length(18),
        Constraint::Min(1),
    ])
    .flex(Flex::Center)
    .areas(area);

    let [content] = Layout::horizontal([Constraint::Percentage(60)])
        .flex(Flex::Center)
        .areas(content_area);

    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(Color::Cyan))
        .title(" Setup ")
        .title_style(
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        );
    let inner = block.inner(content);
    frame.render_widget(block, content);

    let mut lines = vec![
        Line::from(""),
        Line::from(Span::styled(
            "  Welcome to siggy!",
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        )),
        Line::from(""),
        Line::from(Span::styled(
            "  Let's get you set up.",
            Style::default().fg(Color::Gray),
        )),
        Line::from(""),
        Line::from(Span::styled(
            format!("  {}: Signal-CLI", step_label(Step::SignalCli)),
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        )),
    ];

    let mut input_line_idx: Option<usize> = None;

    if found {
        lines.push(Line::from(vec![
            Span::styled("  ", Style::default()),
            Span::styled(
                "V ",
                Style::default()
                    .fg(Color::Green)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                format!("Found signal-cli at {location}"),
                Style::default().fg(Color::Green),
            ),
        ]));
    } else if custom_path_mode {
        lines.push(Line::from(Span::styled(
            "  Enter path to signal-cli:",
            Style::default().fg(Color::Yellow),
        )));
        lines.push(Line::from(""));
        input_line_idx = Some(lines.len());
        lines.push(Line::from(vec![
            Span::styled("  > ", Style::default().fg(Color::Cyan)),
            Span::raw(custom_path_input),
        ]));
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            "  Enter to confirm | Esc to go back",
            Style::default().fg(Color::DarkGray),
        )));
    } else {
        lines.push(Line::from(vec![
            Span::styled("  ", Style::default()),
            Span::styled(
                "X ",
                Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
            ),
            Span::styled("signal-cli not found", Style::default().fg(Color::Red)),
        ]));
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            "  Install: https://github.com/AsamK/signal-cli",
            Style::default().fg(Color::Gray),
        )));
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            "  Enter to retry | p for custom path | Esc to quit",
            Style::default().fg(Color::DarkGray),
        )));
    }

    let paragraph = Paragraph::new(lines).wrap(Wrap { trim: false });
    frame.render_widget(paragraph, inner);

    if let Some(idx) = input_line_idx {
        let cursor_x = inner.x + 4 + custom_path_cursor as u16;
        let cursor_y = inner.y + idx as u16;
        frame.set_cursor_position((cursor_x, cursor_y));
    }
}

fn draw_account_step(
    frame: &mut ratatui::Frame,
    phone_input: &str,
    phone_cursor: usize,
    error: Option<&str>,
) {
    let area = frame.area();

    let [_, content_area, _] = Layout::vertical([
        Constraint::Min(1),
        Constraint::Length(16),
        Constraint::Min(1),
    ])
    .flex(Flex::Center)
    .areas(area);

    let [content] = Layout::horizontal([Constraint::Percentage(60)])
        .flex(Flex::Center)
        .areas(content_area);

    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(Color::Cyan))
        .title(" Setup ")
        .title_style(
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        );
    let inner = block.inner(content);
    frame.render_widget(block, content);

    let mut lines = vec![
        Line::from(""),
        Line::from(Span::styled(
            format!("  {}: Phone Number", step_label(Step::Account)),
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        )),
        Line::from(""),
        Line::from(Span::styled(
            "  Enter your Signal phone number (E.164 format):",
            Style::default().fg(Color::Gray),
        )),
        Line::from(Span::styled(
            "  e.g. +15551234567",
            Style::default().fg(Color::DarkGray),
        )),
        Line::from(""),
    ];

    let input_line_idx = lines.len();
    lines.push(Line::from(vec![
        Span::styled("  > ", Style::default().fg(Color::Cyan)),
        Span::raw(phone_input),
    ]));

    if let Some(err) = error {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            format!("  {err}"),
            Style::default().fg(Color::Red),
        )));
    }

    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "  Enter to confirm | Esc to go back",
        Style::default().fg(Color::DarkGray),
    )));

    let paragraph = Paragraph::new(lines).wrap(Wrap { trim: false });
    frame.render_widget(paragraph, inner);

    // Position cursor
    let cursor_x = inner.x + 4 + phone_cursor as u16;
    let cursor_y = inner.y + input_line_idx as u16;
    frame.set_cursor_position((cursor_x, cursor_y));
}

fn draw_registered_screen(frame: &mut ratatui::Frame, account: &str) {
    let area = frame.area();

    let [_, content_area, _] = Layout::vertical([
        Constraint::Min(1),
        Constraint::Length(8),
        Constraint::Min(1),
    ])
    .flex(Flex::Center)
    .areas(area);

    let [content] = Layout::horizontal([Constraint::Percentage(60)])
        .flex(Flex::Center)
        .areas(content_area);

    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(Color::Green));
    let inner = block.inner(content);
    frame.render_widget(block, content);

    let lines = vec![
        Line::from(""),
        Line::from(vec![
            Span::styled(
                "  V ",
                Style::default()
                    .fg(Color::Green)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                format!("Account {account} is already registered"),
                Style::default().fg(Color::Green),
            ),
        ]),
        Line::from(""),
        Line::from(Span::styled(
            "  Skipping device linking...",
            Style::default().fg(Color::Gray),
        )),
    ];

    let paragraph = Paragraph::new(lines).wrap(Wrap { trim: false });
    frame.render_widget(paragraph, inner);
}

fn draw_link_error(frame: &mut ratatui::Frame, error: &str) {
    let area = frame.area();

    let [_, content_area, _] = Layout::vertical([
        Constraint::Min(1),
        Constraint::Length(10),
        Constraint::Min(1),
    ])
    .flex(Flex::Center)
    .areas(area);

    let [content] = Layout::horizontal([Constraint::Percentage(60)])
        .flex(Flex::Center)
        .areas(content_area);

    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(Color::Red))
        .title(" Linking Error ")
        .title_style(Style::default().fg(Color::Red).add_modifier(Modifier::BOLD));
    let inner = block.inner(content);
    frame.render_widget(block, content);

    let lines = vec![
        Line::from(""),
        Line::from(Span::styled(
            format!("  {error}"),
            Style::default().fg(Color::Red),
        )),
        Line::from(""),
        Line::from(""),
        Line::from(Span::styled(
            "  Enter to retry | Esc to go back",
            Style::default().fg(Color::DarkGray),
        )),
    ];

    let paragraph = Paragraph::new(lines).wrap(Wrap { trim: false });
    frame.render_widget(paragraph, inner);
}

fn draw_preferences_step(frame: &mut ratatui::Frame, config: &Config) {
    let area = frame.area();

    let [_, content_area, _] = Layout::vertical([
        Constraint::Min(1),
        Constraint::Length(16),
        Constraint::Min(1),
    ])
    .flex(Flex::Center)
    .areas(area);

    let [content] = Layout::horizontal([Constraint::Percentage(60)])
        .flex(Flex::Center)
        .areas(content_area);

    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(Color::Cyan))
        .title(" Setup ")
        .title_style(
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        );
    let inner = block.inner(content);
    frame.render_widget(block, content);

    let on = Style::default().fg(Color::Green);
    let off = Style::default().fg(Color::Red);

    let direct_state = if config.notify_direct {
        ("on", on)
    } else {
        ("off", off)
    };
    let group_state = if config.notify_group {
        ("on", on)
    } else {
        ("off", off)
    };

    let lines = vec![
        Line::from(""),
        Line::from(Span::styled(
            format!("  {}: Notifications", step_label(Step::Preferences)),
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        )),
        Line::from(""),
        Line::from(Span::styled(
            "  Terminal bell when messages arrive in background chats.",
            Style::default().fg(Color::Gray),
        )),
        Line::from(Span::styled(
            "  You can change these later with /bell and /mute.",
            Style::default().fg(Color::DarkGray),
        )),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                "  1 ",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("Direct messages  ", Style::default().fg(Color::White)),
            Span::styled(direct_state.0, direct_state.1),
        ]),
        Line::from(vec![
            Span::styled(
                "  2 ",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("Group messages   ", Style::default().fg(Color::White)),
            Span::styled(group_state.0, group_state.1),
        ]),
        Line::from(""),
        Line::from(Span::styled(
            "  Press 1/2 to toggle | Enter/Esc to continue",
            Style::default().fg(Color::DarkGray),
        )),
    ];

    let paragraph = Paragraph::new(lines).wrap(Wrap { trim: false });
    frame.render_widget(paragraph, inner);
}

fn draw_done_screen(frame: &mut ratatui::Frame) {
    let area = frame.area();

    let [_, content_area, _] = Layout::vertical([
        Constraint::Min(1),
        Constraint::Length(8),
        Constraint::Min(1),
    ])
    .flex(Flex::Center)
    .areas(area);

    let [content] = Layout::horizontal([Constraint::Percentage(60)])
        .flex(Flex::Center)
        .areas(content_area);

    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(Color::Green));
    let inner = block.inner(content);
    frame.render_widget(block, content);

    let lines = vec![
        Line::from(""),
        Line::from(Span::styled(
            "  All set! Starting siggy...",
            Style::default()
                .fg(Color::Green)
                .add_modifier(Modifier::BOLD),
        )),
        Line::from(""),
        Line::from(Span::styled(
            "  Config saved. You can re-run setup anytime with --setup",
            Style::default().fg(Color::Gray),
        )),
    ];

    let paragraph = Paragraph::new(lines).wrap(Wrap { trim: false });
    frame.render_widget(paragraph, inner);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn check_signal_cli_detects_known_command() {
        // `cargo` is always available in our Rust test environment and supports `--version`.
        let (found, location, resolved) = check_signal_cli("cargo").await;
        assert!(found, "expected cargo to be detected");
        assert!(
            location.contains("cargo"),
            "display location should mention the binary, got: {location}"
        );
        assert_eq!(
            resolved, "cargo",
            "resolved path should equal input when the direct spawn works"
        );
    }

    #[tokio::test]
    async fn check_signal_cli_reports_missing_for_fake_command() {
        let (found, location, resolved) =
            check_signal_cli("siggy-fake-binary-does-not-exist-xyz-9999").await;
        assert!(!found, "fake command must not be detected");
        assert!(location.is_empty());
        assert_eq!(resolved, "siggy-fake-binary-does-not-exist-xyz-9999");
    }

    #[tokio::test]
    async fn try_spawn_version_returns_none_for_missing_binary() {
        assert!(
            try_spawn_version("siggy-fake-binary-does-not-exist-xyz-9999")
                .await
                .is_none()
        );
    }

    #[tokio::test]
    async fn try_spawn_version_returns_some_for_working_binary() {
        let display = try_spawn_version("cargo").await;
        assert!(display.is_some());
        let display = display.unwrap();
        assert!(display.starts_with("cargo"));
    }
}