tsk-bin 0.1.5

tsk — work with a clear context
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
use clap::{Parser, Subcommand};
use std::path::PathBuf;
use tsk_core::{send_request, socket_path, Priority, Thread, ThreadState};

// ---------------------------------------------------------------------------
// CLI argument schema
// ---------------------------------------------------------------------------

#[derive(Parser)]
#[command(name = "tsk", about = "tsk — work with a clear context", version = env!("CARGO_PKG_VERSION"))]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Manage work threads
    Thread {
        #[command(subcommand)]
        action: ThreadCommands,
    },
    /// Manage tasks within a thread
    Task {
        #[command(subcommand)]
        action: TaskCommands,
    },
    /// Print agent context: conceptual overview, commands, and current thread state
    Context,
}

#[derive(Subcommand)]
enum ThreadCommands {
    /// Create a new work thread (starts paused; use switch-to to activate)
    Create {
        /// Unique slug identifier (e.g. fix-login)
        slug: String,
        /// Priority: BG (background), PRIO (priority), INC (incident)
        priority: String,
        /// Short description
        description: String,
    },
    /// List all threads
    List,
    /// Switch to a thread by its short ID or slug (makes it active, pauses others)
    SwitchTo {
        /// Short hash ID or slug of the thread to activate
        id: String,
    },
    /// Mark a thread as waiting on an external dependency
    Wait {
        /// ID or slug of the thread
        id: String,
        /// Optional reason (what are you waiting for?)
        reason: Option<String>,
    },
    /// Resume a waiting thread, restoring its previous state
    Resume {
        /// ID or slug of the thread
        id: String,
        /// Optional note (e.g. what unblocked it)
        note: Option<String>,
    },
    /// Update metadata on an existing thread (all flags optional)
    Update {
        /// ID or slug of the thread to update
        id: String,
        /// New slug (renames the thread directory)
        #[arg(long)]
        slug: Option<String>,
        /// New description
        #[arg(long)]
        description: Option<String>,
        /// New priority: BG, PRIO, or INC
        #[arg(long)]
        priority: Option<String>,
    },
}

#[derive(Subcommand)]
enum TaskCommands {
    /// Create a new task on the active thread (or a named thread with --thread)
    Create {
        /// Task description
        description: String,
        /// Optional due date (ISO 8601, e.g. 2026-03-15)
        #[arg(long)]
        due_by: Option<String>,
        /// Target thread id or slug (defaults to active thread)
        #[arg(long)]
        thread: Option<String>,
    },
    /// List tasks on the active thread (or a named thread with --thread)
    List {
        /// Target thread id or slug (defaults to active thread)
        #[arg(long)]
        thread: Option<String>,
    },
    /// Start a task (not-started or blocked → in-progress)
    Start {
        /// Task id (e.g. TSK-0001-0001)
        id: String,
        /// Target thread id or slug (defaults to active thread)
        #[arg(long)]
        thread: Option<String>,
    },
    /// Block a task (in-progress → blocked); requires a reason
    Block {
        /// Task id (e.g. TSK-0001-0001)
        id: String,
        /// Reason the task is blocked
        reason: String,
        /// Target thread id or slug (defaults to active thread)
        #[arg(long)]
        thread: Option<String>,
    },
    /// Mark a task as done
    Complete {
        /// Task id (e.g. TSK-0001-0001)
        id: String,
        /// Target thread id or slug (defaults to active thread)
        #[arg(long)]
        thread: Option<String>,
    },
    /// Cancel a task (any state → cancelled)
    Cancel {
        /// Task id (e.g. TSK-0001-0001)
        id: String,
        /// Target thread id or slug (defaults to active thread)
        #[arg(long)]
        thread: Option<String>,
    },
    /// Update task fields (all flags optional)
    Update {
        /// Task id (e.g. TSK-0001-0001)
        id: String,
        /// New description
        #[arg(long)]
        description: Option<String>,
        /// New due date (ISO 8601)
        #[arg(long)]
        due_by: Option<String>,
        /// New sequence number (for manual ordering)
        #[arg(long)]
        seq: Option<u32>,
        /// Target thread id or slug (defaults to active thread)
        #[arg(long)]
        thread: Option<String>,
    },
}

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------

fn main() {
    let args: Vec<String> = std::env::args().collect();

    // No args → TUI mode
    if args.len() == 1 {
        if let Err(e) = tui::run() {
            eprintln!("TUI error: {}", e);
            std::process::exit(1);
        }
        return;
    }

    // All other args (subcommands, --version, --help) → clap
    let cli = Cli::parse();
    if let Err(e) = run_cli(cli) {
        eprintln!("{}", e);
        std::process::exit(1);
    }
}

// ---------------------------------------------------------------------------
// Project root resolution
//
// Uses TSK_PROJECT_ROOT env var if set (useful for tests and scripting),
// otherwise falls back to the current directory.
// ---------------------------------------------------------------------------

fn project_root() -> PathBuf {
    std::env::var("TSK_PROJECT_ROOT")
        .map(PathBuf::from)
        .unwrap_or_else(|_| std::env::current_dir().expect("Cannot determine current directory"))
}

// ---------------------------------------------------------------------------
// CLI mode
// ---------------------------------------------------------------------------

fn run_cli(cli: Cli) -> Result<(), String> {
    let root = project_root();
    let sock = socket_path(&root);

    match cli.command {
        Some(Commands::Thread { action }) => match action {
            ThreadCommands::Create {
                slug,
                priority,
                description,
            } => {
                let _: Priority = priority.parse()?;
                let result = send_request(
                    &sock,
                    "thread.create",
                    serde_json::json!({
                        "slug": slug,
                        "priority": priority,
                        "description": description,
                    }),
                )?;
                println!("{}", serde_json::to_string_pretty(&result).unwrap());
                Ok(())
            }
            ThreadCommands::List => {
                let result = send_request(&sock, "thread.list", serde_json::json!({}))?;
                println!("{}", serde_json::to_string_pretty(&result).unwrap());
                Ok(())
            }
            ThreadCommands::SwitchTo { id } => {
                let result = send_request(
                    &sock,
                    "thread.switch_to",
                    serde_json::json!({ "id": id }),
                )?;
                println!("{}", serde_json::to_string_pretty(&result).unwrap());
                Ok(())
            }
            ThreadCommands::Wait { id, reason } => {
                let mut params = serde_json::json!({ "id": id });
                if let Some(r) = reason { params["reason"] = r.into(); }
                let result = send_request(&sock, "thread.wait", params)?;
                println!("{}", serde_json::to_string_pretty(&result).unwrap());
                Ok(())
            }
            ThreadCommands::Resume { id, note } => {
                let mut params = serde_json::json!({ "id": id });
                if let Some(n) = note { params["note"] = n.into(); }
                let result = send_request(&sock, "thread.resume", params)?;
                println!("{}", serde_json::to_string_pretty(&result).unwrap());
                Ok(())
            }
            ThreadCommands::Update { id, slug, description, priority } => {
                if let Some(ref p) = priority {
                    let _: Priority = p.parse()?;
                }
                let mut params = serde_json::json!({ "id": id });
                if let Some(s) = slug        { params["slug"]        = s.into(); }
                if let Some(d) = description { params["description"] = d.into(); }
                if let Some(p) = priority    { params["priority"]    = p.into(); }
                let result = send_request(&sock, "thread.update", params)?;
                println!("{}", serde_json::to_string_pretty(&result).unwrap());
                Ok(())
            }
        },
        Some(Commands::Task { action }) => match action {
            TaskCommands::Create { description, due_by, thread } => {
                let mut params = serde_json::json!({ "description": description });
                if let Some(d) = due_by   { params["due_by"] = d.into(); }
                if let Some(t) = thread   { params["thread"] = t.into(); }
                let result = send_request(&sock, "task.create", params)?;
                println!("{}", serde_json::to_string_pretty(&result).unwrap());
                Ok(())
            }
            TaskCommands::List { thread } => {
                let mut params = serde_json::json!({});
                if let Some(t) = thread { params["thread"] = t.into(); }
                let result = send_request(&sock, "task.list", params)?;
                println!("{}", serde_json::to_string_pretty(&result).unwrap());
                Ok(())
            }
            TaskCommands::Start { id, thread } => {
                let mut params = serde_json::json!({ "id": id });
                if let Some(t) = thread { params["thread"] = t.into(); }
                let result = send_request(&sock, "task.start", params)?;
                println!("{}", serde_json::to_string_pretty(&result).unwrap());
                Ok(())
            }
            TaskCommands::Block { id, reason, thread } => {
                let mut params = serde_json::json!({ "id": id, "reason": reason });
                if let Some(t) = thread { params["thread"] = t.into(); }
                let result = send_request(&sock, "task.block", params)?;
                println!("{}", serde_json::to_string_pretty(&result).unwrap());
                Ok(())
            }
            TaskCommands::Complete { id, thread } => {
                let mut params = serde_json::json!({ "id": id });
                if let Some(t) = thread { params["thread"] = t.into(); }
                let result = send_request(&sock, "task.complete", params)?;
                println!("{}", serde_json::to_string_pretty(&result).unwrap());
                Ok(())
            }
            TaskCommands::Cancel { id, thread } => {
                let mut params = serde_json::json!({ "id": id });
                if let Some(t) = thread { params["thread"] = t.into(); }
                let result = send_request(&sock, "task.cancel", params)?;
                println!("{}", serde_json::to_string_pretty(&result).unwrap());
                Ok(())
            }
            TaskCommands::Update { id, description, due_by, seq, thread } => {
                let mut params = serde_json::json!({ "id": id });
                if let Some(d) = description { params["description"] = d.into(); }
                if let Some(d) = due_by      { params["due_by"]      = d.into(); }
                if let Some(s) = seq         { params["seq"]         = s.into(); }
                if let Some(t) = thread      { params["thread"]      = t.into(); }
                let result = send_request(&sock, "task.update", params)?;
                println!("{}", serde_json::to_string_pretty(&result).unwrap());
                Ok(())
            }
        },
        Some(Commands::Context) => {
            const AGENT_CONTEXT: &str = include_str!("agent-context.md");
            print!("{}", AGENT_CONTEXT);

            // Append live thread state if the daemon is running
            match send_request(&sock, "thread.list", serde_json::json!({})) {
                Ok(result) => {
                    let threads = result["threads"].as_array().cloned().unwrap_or_default();
                    if threads.is_empty() {
                        println!("No threads exist yet.");
                    } else {
                        for t in &threads {
                            let id = t["id"].as_u64().unwrap_or(0);
                            let slug = t["slug"].as_str().unwrap_or("?");
                            let state = t["state"].as_str().unwrap_or("?");
                            let priority = t["priority"].as_str().unwrap_or("?");
                            let description = t["description"].as_str().unwrap_or("");
                            println!(
                                "- {:04} {:20} {:6} {:6} {}",
                                id, slug, priority, state, description
                            );
                        }
                    }
                }
                Err(_) => {
                    println!("(tskd is not running — start it with: tskd)");
                }
            }
            Ok(())
        }
        None => Ok(()),
    }
}

// ---------------------------------------------------------------------------
// TUI mode
// ---------------------------------------------------------------------------

mod tui {
    use super::*;
    use crossterm::{
        event::{
            self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind,
            KeyModifiers, MouseEventKind,
        },
        execute,
        terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
    };
    use ratatui::{
        layout::{Constraint, Direction, Layout},
        prelude::*,
        widgets::{Clear, Paragraph},
    };
    use std::io;
    use std::time::{Duration, Instant};

    pub fn run() -> Result<(), Box<dyn std::error::Error>> {
        let root = project_root();
        let sock = socket_path(&root);

        // Ensure the terminal is restored even if a panic occurs inside the event loop.
        let original_hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |info| {
            let _ = disable_raw_mode();
            let _ = execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture);
            original_hook(info);
        }));

        enable_raw_mode()?;
        let mut stdout = io::stdout();
        execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
        let backend = CrosstermBackend::new(stdout);
        let mut terminal = Terminal::new(backend)?;

        let result = event_loop(&mut terminal, &sock);

        let _ = std::panic::take_hook(); // restore default hook
        disable_raw_mode()?;
        execute!(terminal.backend_mut(), LeaveAlternateScreen, DisableMouseCapture)?;
        terminal.show_cursor()?;

        result
    }

    fn fetch_threads(sock: &std::path::Path) -> Result<Vec<Thread>, String> {
        let result = send_request(sock, "thread.list", serde_json::json!({}))?;
        let threads: Vec<Thread> = serde_json::from_value(result["threads"].clone())
            .map_err(|e| format!("Failed to parse threads: {}", e))?;
        Ok(threads)
    }

    const POLL_INTERVAL: Duration = Duration::from_millis(500);

    fn event_loop(
        terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
        sock: &std::path::Path,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let mut threads: Vec<Thread> = fetch_threads(sock).unwrap_or_default();
        let mut error_msg: Option<String> = if !sock.exists() {
            Some("tskd is not running. Start it with: tskd".to_string())
        } else {
            None
        };
        let mut last_poll = Instant::now();
        let mut scroll: usize = 0;
        let mut last_g = false; // for gg detection
        let mut show_help = false;

        loop {
            // Reserve 1 row for the status bar
            let height = terminal.size().map(|r| r.height.saturating_sub(1) as usize).unwrap_or(23);
            let row_count = count_rows(&threads);
            terminal.draw(|frame| render(frame, &threads, error_msg.as_deref(), scroll, show_help))?;

            // Poll daemon for state changes every 500ms
            if last_poll.elapsed() >= POLL_INTERVAL {
                match fetch_threads(sock) {
                    Ok(t) => { threads = t; error_msg = None; }
                    Err(e) => { error_msg = Some(e); }
                }
                last_poll = Instant::now();
            }

            // Block briefly for a keypress or mouse event
            if event::poll(Duration::from_millis(100))? {
                match event::read()? {
                    Event::Key(key) if key.kind == KeyEventKind::Press => {
                        // Any key closes the help popup
                        if show_help {
                            show_help = false;
                            continue;
                        }

                        let g_pressed = last_g;
                        last_g = false;

                        match key.code {
                            KeyCode::Char('q') | KeyCode::Esc => break,
                            KeyCode::Char('?') => show_help = true,

                            KeyCode::Char('j') | KeyCode::Down => {
                                scroll = scroll_down(scroll, row_count, height, 1);
                            }
                            KeyCode::Char('k') | KeyCode::Up => {
                                scroll = scroll.saturating_sub(1);
                            }
                            KeyCode::Char('d')
                                if key.modifiers.contains(KeyModifiers::CONTROL) =>
                            {
                                let page = (height / 2).max(1);
                                scroll = scroll_down(scroll, row_count, height, page);
                            }
                            KeyCode::Char('u')
                                if key.modifiers.contains(KeyModifiers::CONTROL) =>
                            {
                                let page = (height / 2).max(1);
                                scroll = scroll.saturating_sub(page);
                            }
                            KeyCode::Char('g') => {
                                if g_pressed {
                                    scroll = 0; // gg → top
                                } else {
                                    last_g = true;
                                }
                            }
                            KeyCode::Char('G') => {
                                scroll = scroll_bottom(row_count, height);
                            }
                            _ => {}
                        }
                    }
                    Event::Mouse(mouse) => {
                        match mouse.kind {
                            MouseEventKind::ScrollDown => {
                                scroll = scroll_down(scroll, row_count, height, 3);
                            }
                            MouseEventKind::ScrollUp => {
                                scroll = scroll.saturating_sub(3);
                            }
                            _ => {}
                        }
                    }
                    _ => {}
                }
            }
        }

        Ok(())
    }

    /// Total rendered lines for the current thread list, matching what render() produces.
    /// Each non-empty section: title + top border + N thread rows + bottom border.
    /// Sections are separated by one blank line.
    pub fn count_rows(threads: &[Thread]) -> usize {
        let is_inactive = |t: &&Thread| matches!(t.state, ThreadState::Paused | ThreadState::Waiting { .. });
        let active = threads.iter().filter(|t| t.state == ThreadState::Active).count();
        let focus = threads.iter().filter(|t| {
            is_inactive(t) && matches!(t.priority, Priority::Incident | Priority::Priority)
        }).count();
        let bg = threads.iter().filter(|t| {
            is_inactive(t) && matches!(t.priority, Priority::Background)
        }).count();

        let counts = [active, focus, bg];
        let non_empty = counts.iter().filter(|&&n| n > 0).count();
        let separators = non_empty.saturating_sub(1); // one blank line between sections

        let mut rows = separators;
        for n in counts {
            if n > 0 {
                rows += 1 + 1 + n + 1; // title + top border + thread rows + bottom border
            }
        }
        rows
    }

    pub fn scroll_down(scroll: usize, row_count: usize, height: usize, amount: usize) -> usize {
        let max = row_count.saturating_sub(height);
        (scroll + amount).min(max)
    }

    pub fn scroll_bottom(row_count: usize, height: usize) -> usize {
        row_count.saturating_sub(height)
    }

    // -----------------------------------------------------------------------
    // Rendering
    // -----------------------------------------------------------------------

    // Fixed column widths (inner content, excluding borders and leading spaces).
    // Column order: ID | SLUG | STATE | PRIO | DESC
    // As the terminal narrows, columns are hidden right-to-left: desc first, then prio, then state.
    const W_ID: u16 = 6;
    const W_STATE: u16 = 9;
    const W_PRIO: u16 = 6;
    // Slug is always at SLUG_FULL when any optional column is visible.
    // Optional columns appear in order (state, prio, desc) as space allows.
    // Below SLUG_FULL, slug expands to fill and all optional columns are hidden.
    const SLUG_FULL: u16 = 40;

    struct ColWidths {
        id: u16,
        slug: u16,
        state: u16,  // 0 = hidden
        prio: u16,   // 0 = hidden
        desc: u16,   // 0 = hidden
    }

    impl ColWidths {
        fn from_area(w: u16) -> Self {
            // overhead = 2 outer borders + N-1 inner separators
            let try5 = 2 + 4 + W_ID + W_STATE + W_PRIO; // all 5 columns
            let try4 = 2 + 3 + W_ID + W_STATE + W_PRIO; // no desc
            let try3 = 2 + 2 + W_ID + W_STATE;           // no desc, no prio
            let try2 = 2 + 1 + W_ID;                     // id + slug only

            // Each optional column only appears once slug is already at SLUG_FULL.
            // Surplus beyond SLUG_FULL goes to desc.
            if w > try5 + SLUG_FULL {
                let desc = w - try5 - SLUG_FULL;
                return Self { id: W_ID, slug: SLUG_FULL, state: W_STATE, prio: W_PRIO, desc };
            }

            if w > try4 + SLUG_FULL {
                return Self { id: W_ID, slug: SLUG_FULL, state: W_STATE, prio: W_PRIO, desc: 0 };
            }

            if w > try3 + SLUG_FULL {
                return Self { id: W_ID, slug: SLUG_FULL, state: W_STATE, prio: 0, desc: 0 };
            }

            let slug = w.saturating_sub(try2).max(1);
            Self { id: W_ID, slug, state: 0, prio: 0, desc: 0 }
        }

        fn active_widths(&self) -> Vec<u16> {
            [self.id, self.slug, self.state, self.prio, self.desc]
                .iter()
                .copied()
                .filter(|&w| w > 0)
                .collect()
        }
    }

    fn pad(s: &str, width: u16) -> String {
        let w = width as usize;
        let char_count = s.chars().count();
        if char_count >= w {
            s.chars().take(w).collect()
        } else {
            format!("{}{}", s, " ".repeat(w - char_count))
        }
    }

    fn top_border(ws: &ColWidths) -> Line<'static> {
        let inner: Vec<String> = ws.active_widths().iter()
            .map(|&w| "─".repeat(w as usize))
            .collect();
        let line = format!("┌{}┐", inner.join("┬"));
        Line::from(Span::raw(line))
    }

    fn bottom_border(ws: &ColWidths) -> Line<'static> {
        let inner: Vec<String> = ws.active_widths().iter()
            .map(|&w| "─".repeat(w as usize))
            .collect();
        let line = format!("└{}┘", inner.join("┴"));
        Line::from(Span::raw(line))
    }

    fn data_line<'a>(
        id: &str,
        slug: &str,
        state: &str,
        prio: &str,
        desc: &str,
        ws: &ColWidths,
        style: Style,
    ) -> Line<'a> {
        let mut cells: Vec<String> = vec![
            format!(" {}", pad(id,   ws.id.saturating_sub(1))),
            format!(" {}", pad(slug, ws.slug.saturating_sub(1))),
        ];
        if ws.state > 0 { cells.push(format!(" {}", pad(state, ws.state.saturating_sub(1)))); }
        if ws.prio  > 0 { cells.push(format!(" {}", pad(prio,  ws.prio.saturating_sub(1)))); }
        if ws.desc  > 0 { cells.push(format!(" {}", pad(desc,  ws.desc.saturating_sub(1)))); }
        let line = format!("│{}│", cells.join("│"));
        Line::from(Span::styled(line, style))
    }

    fn section_lines(title: &str, threads: &[&Thread], ws: &ColWidths) -> Vec<Line<'static>> {
        if threads.is_empty() {
            return vec![];
        }
        let mut lines: Vec<Line<'static>> = Vec::new();
        lines.push(Line::from(Span::styled(
            format!("> {}", title),
            Style::default().bold(),
        )));
        lines.push(top_border(ws));
        for t in threads {
            lines.push(data_line(
                &t.id_str(),
                &t.slug,
                &t.state.to_string(),
                &t.priority.to_string(),
                &t.description,
                ws,
                Style::default(),
            ));
        }
        lines.push(bottom_border(ws));
        lines
    }

    fn render(frame: &mut Frame, threads: &[Thread], error: Option<&str>, scroll: usize, show_help: bool) {
        let area = frame.area();

        // Split into main area + 1-row status bar at bottom
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Min(0), Constraint::Length(1)])
            .split(area);
        let main_area = chunks[0];
        let status_area = chunks[1];

        // --- Main area ---
        if let Some(msg) = error {
            frame.render_widget(Paragraph::new(msg), main_area);
        } else {
            let ws = ColWidths::from_area(main_area.width);

            let active: Vec<&Thread> = threads
                .iter()
                .filter(|t| t.state == ThreadState::Active)
                .collect();

            let is_inactive = |t: &&Thread| matches!(t.state, ThreadState::Paused | ThreadState::Waiting { .. });

            let mut focus: Vec<&Thread> = threads
                .iter()
                .filter(|t| {
                    is_inactive(t) && matches!(t.priority, Priority::Incident | Priority::Priority)
                })
                .collect();
            focus.sort_by_key(|t| match t.priority {
                Priority::Incident => 0u8,
                _ => 1,
            });

            let background: Vec<&Thread> = threads
                .iter()
                .filter(|t| {
                    is_inactive(t) && matches!(t.priority, Priority::Background)
                })
                .collect();

            let mut lines: Vec<Line> = Vec::new();
            let sections = [
                ("Active", active.as_slice()),
                ("Priority & Incidents", focus.as_slice()),
                ("Background", background.as_slice()),
            ];

            for (i, (title, section_threads)) in sections.iter().enumerate() {
                let s = section_lines(title, section_threads, &ws);
                if s.is_empty() { continue; }
                if i > 0 && !lines.is_empty() { lines.push(Line::from("")); }
                lines.extend(s);
            }

            frame.render_widget(Paragraph::new(lines).scroll((scroll as u16, 0)), main_area);
        }

        // --- Status bar ---
        let active_thread = threads.iter().find(|t| t.state == ThreadState::Active);
        let status_text = match active_thread {
            Some(t) => format!("  #{} {}   |   ? help", t.id_str(), t.slug),
            None    => "  (no active thread)   |   ? help".to_string(),
        };
        frame.render_widget(
            Paragraph::new(status_text).style(Style::default().bg(Color::DarkGray)),
            status_area,
        );

        // --- Help popup overlay ---
        if show_help {
            render_help_popup(frame, area);
        }
    }

    fn render_help_popup(frame: &mut Frame, area: Rect) {
        const POPUP_W: u16 = 36;
        const POPUP_H: u16 = 14;

        // Centre the popup
        let x = area.x + area.width.saturating_sub(POPUP_W) / 2;
        let y = area.y + area.height.saturating_sub(POPUP_H) / 2;
        let popup_area = Rect::new(x, y, POPUP_W.min(area.width), POPUP_H.min(area.height));

        let popup_style = Style::default();
        let key_style   = Style::default().bold();
        let desc_style  = Style::default();

        let bindings: &[(&str, &str)] = &[
            ("j / ↓",    "scroll down"),
            ("k / ↑",    "scroll up"),
            ("ctrl-d",   "page down"),
            ("ctrl-u",   "page up"),
            ("gg",       "jump to top"),
            ("G",        "jump to bottom"),
            ("?",        "toggle this help"),
            ("q / esc",  "quit"),
        ];

        let rows: Vec<Line> = bindings
            .iter()
            .map(|(key, desc)| {
                Line::from(vec![
                    Span::raw("  "),
                    Span::styled(format!("{:<10}", key), key_style),
                    Span::raw("  "),
                    Span::styled(*desc, desc_style),
                ])
            })
            .collect();

        use ratatui::widgets::{Block, BorderType, Borders};
        let block = Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default());

        frame.render_widget(Clear, popup_area);
        frame.render_widget(Paragraph::new(rows).block(block).style(popup_style), popup_area);
    }
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn no_args_would_launch_tui() {
        let cli = Cli::try_parse_from(["tsk", "thread", "list"]);
        assert!(cli.is_ok());

        let cli = Cli::try_parse_from(["tsk", "thread", "create", "fix-login", "PRIO", "Fix it"]);
        assert!(cli.is_ok());

        let cli = Cli::try_parse_from(["tsk", "thread", "switch-to", "a3f1b2c"]);
        assert!(cli.is_ok());
    }

    #[test]
    fn cli_validates_priority() {
        assert!("BG".parse::<Priority>().is_ok());
        assert!("PRIO".parse::<Priority>().is_ok());
        assert!("INC".parse::<Priority>().is_ok());
        assert!("NORMAL".parse::<Priority>().is_err());
    }

    // --- TUI scroll helpers ---

    #[test]
    fn scroll_down_clamps_to_max() {
        // 10 rows, 24 height → can't scroll (all fits)
        assert_eq!(tui::scroll_down(0, 10, 24, 5), 0);
        // 30 rows, 24 height → max scroll is 6
        assert_eq!(tui::scroll_down(0, 30, 24, 10), 6);
        assert_eq!(tui::scroll_down(4, 30, 24, 10), 6);
    }

    #[test]
    fn scroll_down_advances_by_amount() {
        assert_eq!(tui::scroll_down(0, 30, 24, 3), 3);
        assert_eq!(tui::scroll_down(2, 30, 24, 3), 5);
    }

    #[test]
    fn scroll_bottom_goes_to_last_page() {
        assert_eq!(tui::scroll_bottom(30, 24), 6);
        assert_eq!(tui::scroll_bottom(10, 24), 0); // fits entirely
    }

    #[test]
    fn count_rows_empty_threads() {
        assert_eq!(tui::count_rows(&[]), 0);
    }

    #[test]
    fn count_rows_one_active() {
        let t = Thread {
            id: 1,
            slug: "foo".to_string(),
            state: ThreadState::Active,
            priority: Priority::Priority,
            description: "".to_string(),
        };
        // 1 section: title + top border + 1 row + bottom border = 4
        assert_eq!(tui::count_rows(&[t]), 4);
    }

    #[test]
    fn count_rows_two_sections() {
        let active = Thread {
            id: 1, slug: "a".to_string(), state: ThreadState::Active,
            priority: Priority::Priority, description: "".to_string(),
        };
        let paused = Thread {
            id: 2, slug: "b".to_string(), state: ThreadState::Paused,
            priority: Priority::Background, description: "".to_string(),
        };
        // active section: 4 rows; blank separator: 1; bg section: 4 rows = 9
        assert_eq!(tui::count_rows(&[active, paused]), 9);
    }
}