do-next 0.0.0-2026.4.8

Pick your next Jira task & manage it from the terminal
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
pub mod app;
pub mod detail;
pub mod hint_bar;
pub mod list;
pub mod markdown;
pub mod onboarding;
pub mod overlays;
pub mod render;
pub mod views;

use anyhow::Result;
use crossterm::{
    event::EventStream,
    execute,
    terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use futures::StreamExt;
use ratatui::{Terminal, backend::CrosstermBackend, widgets::ListState};
use std::io;
use tokio::sync::mpsc::{UnboundedSender, unbounded_channel};
use tokio::time::{Duration, interval};

use crate::config::LoadedConfig;
use crate::config::hidden::{HiddenState, hidden_path};
use crate::events::{ActionResult, AppEvent};
use crate::jira::JiraClient;
use crate::sources::spawn_fetches;
use crate::tui::app::{
    ActionState, AppState, AttachmentFetchRequest, cache_path_for, compute_completions_for,
    update_state,
};
use crate::tui::render::{RenderOut, render};

/// Entry point for the interactive TUI.
pub async fn run(
    loaded: LoadedConfig,
    clients: std::collections::HashMap<String, JiraClient>,
) -> Result<()> {
    // Terminal setup
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let result = run_inner(&mut terminal, loaded, clients).await;

    // Cleanup
    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;

    result
}

async fn run_inner(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    loaded: LoadedConfig,
    clients: std::collections::HashMap<String, JiraClient>,
) -> Result<()> {
    let (tx, mut rx) = unbounded_channel::<AppEvent>();
    let mut app = AppState::new(loaded.teams.clone());

    // Surface team config load errors as warnings
    if !loaded.load_errors.is_empty() {
        app.update_warnings = loaded.load_errors.clone();
    }

    let client = spawn_initial_tasks(&mut app, &loaded, &clients, &tx)?;

    // Initialize image picker (best-effort; terminal must be in raw mode for query)
    app.image_picker = ratatui_image::picker::Picker::from_query_stdio().ok();

    let team_id = app
        .resolved_teams
        .first()
        .map_or("personal", |t| t.id.as_str());
    let hidden_file = hidden_path(team_id)?;
    let mut hidden = HiddenState::load(&hidden_file)?;

    // Keep the clients map for tab switching.
    let clients_map = clients;

    let mut input_task = spawn_input_task(tx.clone());
    // Tick task is spawned on-demand: only while sources are loading.
    let mut tick_handle: Option<tokio::task::JoinHandle<()>> = Some(spawn_tick_task(tx.clone()));
    let mut list_state = ListState::default();

    // Main event loop
    loop {
        let Some(event) = rx.recv().await else { break };

        update_state(&mut app, event);

        // Handle tab switch: spawn fetches for newly active team
        if app.flags.pending_team_fetch {
            app.flags.pending_team_fetch = false;
            if let Some(team) = app.resolved_teams.get(app.active_team_idx)
                && let Some(team_client) = clients_map.get(&team.jira.base_url)
            {
                spawn_fetches(team_client, app.team_config(), &tx);
                for state in app.sources.values_mut() {
                    if matches!(state, crate::tui::app::SourceState::Pending) {
                        *state = crate::tui::app::SourceState::Loading;
                    }
                }
            }
        }

        // Manage tick task lifecycle: run only while sources are loading
        if app.any_source_loading() {
            if tick_handle
                .as_ref()
                .is_none_or(tokio::task::JoinHandle::is_finished)
            {
                tick_handle = Some(spawn_tick_task(tx.clone()));
            }
        } else if let Some(h) = tick_handle.take() {
            h.abort();
        }

        // Resolve the current team's client for actions
        let active_client_ref = app
            .resolved_teams
            .get(app.active_team_idx)
            .and_then(|t| clients_map.get(&t.jira.base_url))
            .unwrap_or(&client);

        maybe_spawn_field_names_fetch(&mut app, active_client_ref, &tx);

        handle_pending_comment(
            terminal,
            &mut app,
            active_client_ref,
            &tx,
            &mut rx,
            &mut input_task,
        );
        handle_pending_field_edit(terminal, &mut app, &mut rx, &mut input_task, &tx);
        handle_pending_comment_edit(terminal, &mut app, &mut rx, &mut input_task, &tx);

        // Dispatch any pending action signals (transition fetch, hide, assign, move)
        dispatch_action(&mut app, active_client_ref, &tx, &mut hidden, &hidden_file)?;

        if app.should_quit {
            break;
        }

        let mut render_out = RenderOut::default();
        terminal.draw(|f| render(f, &app, &mut list_state, &mut render_out))?;
        app.detail_focus_offsets = std::mem::take(&mut render_out.detail_focus_offsets);
        app.last_detail_viewport_h = render_out.detail_viewport_h;
        app.last_detail_content_h = render_out.detail_content_h;
        app.overlay_content_h = render_out.overlay_content_h;
        app.overlay_viewport_h = render_out.overlay_viewport_h;
        app.overlay_comment_offsets = std::mem::take(&mut render_out.overlay_comment_offsets);
    }

    if let Some(h) = tick_handle {
        h.abort();
    }
    Ok(())
}

/// Spawn background tasks for the active team: user resolution, source fetches,
/// update checks. Returns the active team's `JiraClient`.
fn spawn_initial_tasks(
    app: &mut AppState,
    loaded: &LoadedConfig,
    clients: &std::collections::HashMap<String, JiraClient>,
    tx: &UnboundedSender<AppEvent>,
) -> Result<JiraClient> {
    let active_client = app
        .resolved_teams
        .first()
        .and_then(|t| clients.get(&t.jira.base_url))
        .cloned()
        .ok_or_else(|| anyhow::anyhow!("No teams configured. Run do-next to set up a team."))?;

    // Fetch current user (best-effort; subsource sorting depends on it)
    let user_client = active_client.clone();
    let user_tx = tx.clone();
    tokio::spawn(async move {
        if let Ok(user) = user_client.current_user().await {
            let _ = user_tx.send(AppEvent::CurrentUserResolved(user));
        }
    });

    // Spawn fetch tasks for the active team's sources
    spawn_fetches(&active_client, app.team_config(), tx);
    for state in app.sources.values_mut() {
        *state = crate::tui::app::SourceState::Loading;
    }

    // Spawn background update checks for team config repos
    let teams = loaded.teams.clone();
    let update_tx = tx.clone();
    tokio::task::spawn_blocking(move || {
        let warnings: Vec<String> = teams
            .iter()
            .filter_map(crate::config::updates::check_team_update)
            .collect();
        if !warnings.is_empty() {
            let _ = update_tx.send(AppEvent::UpdateWarnings(warnings));
        }
    });

    Ok(active_client)
}

fn spawn_tick_task(tx: UnboundedSender<AppEvent>) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        let mut ticker = interval(Duration::from_millis(100));
        loop {
            ticker.tick().await;
            if tx.send(AppEvent::Tick).is_err() {
                break;
            }
        }
    })
}

fn handle_pending_comment(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut AppState,
    client: &JiraClient,
    tx: &UnboundedSender<AppEvent>,
    rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
    input_task: &mut tokio::task::JoinHandle<()>,
) {
    let ActionState::PendingComment { ref issue_key } = app.action_state else {
        return;
    };
    let key = issue_key.clone();
    app.action_state = ActionState::None;
    input_task.abort();
    let editor_result = open_editor_for_comment(terminal);
    *input_task = spawn_input_task(tx.clone());
    drain_input_events(rx);
    match editor_result {
        Ok(Some(body)) => {
            app.action_state = ActionState::AwaitingAction {
                description: "Posting comment…".into(),
            };
            let client2 = client.clone();
            let tx2 = tx.clone();
            tokio::spawn(async move {
                match client2.post_comment(&key, &body).await {
                    Ok(new_comment) => {
                        let _ = tx2.send(AppEvent::ActionDone(ActionResult::CommentPosted {
                            issue_key: key,
                            new_comment,
                        }));
                    }
                    Err(e) => {
                        let _ = tx2.send(AppEvent::ActionDone(ActionResult::Error(e)));
                    }
                }
            });
        }
        Ok(None) => {} // empty/cancelled — state already cleared
        Err(e) => {
            app.action_state = ActionState::Error(std::sync::Arc::new(e));
        }
    }
}

fn handle_pending_field_edit(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut AppState,
    rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
    input_task: &mut tokio::task::JoinHandle<()>,
    tx: &UnboundedSender<AppEvent>,
) {
    let ActionState::PendingFieldEdit {
        ref issue_key,
        ref field_id,
        ref current_value,
        ref original_json,
    } = app.action_state
    else {
        return;
    };
    let (key, field_id, current_value, original_json) = (
        issue_key.clone(),
        field_id.clone(),
        current_value.clone(),
        original_json.clone(),
    );
    app.action_state = ActionState::None;
    input_task.abort();
    let editor_result = open_editor_with_content(terminal, &current_value);
    *input_task = spawn_input_task(tx.clone());
    drain_input_events(rx);
    match editor_result {
        Ok(Some(new_text)) => {
            if new_text == current_value.trim() {
                // No change — skip Jira update
            } else {
                let new_value = shape_field_value(&new_text, &original_json);
                app.action_state = ActionState::ConfirmingFieldEdit {
                    issue_key: key,
                    field_id,
                    old_text: current_value,
                    new_text,
                    new_value,
                    tab: 0,
                };
            }
        }
        Ok(None) => {} // cancelled
        Err(e) => {
            app.action_state = ActionState::Error(std::sync::Arc::new(e));
        }
    }
}

fn spawn_input_task(tx: UnboundedSender<AppEvent>) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        let mut stream = EventStream::new();
        while let Some(Ok(event)) = stream.next().await {
            if tx.send(AppEvent::Input(event)).is_err() {
                break;
            }
        }
    })
}

/// Discard any input events queued while the editor was blocking the event loop.
fn drain_input_events(rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>) {
    while let Ok(AppEvent::Input(_)) = rx.try_recv() {}
}

/// Dispatch any pending typed action states.
/// Transitions the state to `AwaitingAction` immediately to prevent re-dispatch.
fn dispatch_action(
    app: &mut AppState,
    client: &JiraClient,
    tx: &UnboundedSender<AppEvent>,
    hidden: &mut HiddenState,
    hidden_file: &std::path::PathBuf,
) -> Result<()> {
    dispatch_background_tasks(app, client, tx);

    match app.action_state.clone() {
        ActionState::LoadingTransitions { issue_key } => {
            app.action_state = ActionState::AwaitingAction {
                description: "Fetching transitions…".into(),
            };
            spawn_load_transitions(issue_key, client.clone(), tx.clone());
        }
        ActionState::PendingTransition {
            issue_key,
            transition_id,
        } => {
            app.action_state = ActionState::AwaitingAction {
                description: "Applying transition…".into(),
            };
            spawn_transition(issue_key, transition_id, client.clone(), tx.clone());
        }
        ActionState::PendingHide { issue_key } => {
            dispatch_pending_hide(app, issue_key, tx, hidden, hidden_file)?;
        }
        ActionState::PendingAssign { issue_key } => {
            dispatch_pending_assign(app, issue_key, client, tx);
        }
        ActionState::PendingMove { issue_key } => {
            dispatch_pending_move(app, issue_key, client, tx);
        }
        ActionState::LoadingFieldOptions {
            issue_key,
            field_id,
            label,
            original_json,
            description,
            multi,
        } => {
            dispatch_load_field_options(
                app,
                FieldOptionsRequest {
                    issue_key,
                    field_id,
                    label,
                    original_json,
                    description,
                    multi,
                },
                client,
                tx,
            );
        }
        ActionState::CommittingFieldEdit {
            issue_key,
            field_id,
            new_value,
        } => {
            dispatch_committing_field_edit(app, issue_key, field_id, new_value, client, tx);
        }
        ActionState::CommittingCommentEdit {
            issue_key,
            comment_id,
            new_body,
        } => {
            dispatch_committing_comment_edit(app, issue_key, comment_id, new_body, client, tx);
        }
        ActionState::DeletingComment {
            issue_key,
            comment_id,
        } => {
            dispatch_deleting_comment(app, issue_key, comment_id, client, tx);
        }
        ActionState::DeletingAttachment {
            issue_key,
            attachment_id,
        } => {
            dispatch_deleting_attachment(app, issue_key, attachment_id, client, tx);
        }
        ActionState::OpeningAttachment {
            attachment_id,
            content_url,
            filename,
            issue_key,
        } => {
            dispatch_opening_attachment(
                app,
                attachment_id,
                content_url,
                filename,
                issue_key,
                client,
                tx,
            );
        }
        ActionState::PendingAttachmentUpload {
            issue_key,
            file_path,
        } => {
            dispatch_pending_attachment_upload(app, issue_key, file_path, client, tx);
        }
        _ => {}
    }
    Ok(())
}

fn dispatch_background_tasks(
    app: &mut AppState,
    client: &JiraClient,
    tx: &UnboundedSender<AppEvent>,
) {
    // Silent background attachment fetch (not ActionState-driven)
    if let Some(req) = app.pending_attachment_fetch.take() {
        spawn_cache_attachment(req, false, client.clone(), tx.clone());
    }

    // Debounced path completion fetch
    spawn_debounced_completions(app, tx);
}

fn spawn_debounced_completions(app: &mut AppState, tx: &UnboundedSender<AppEvent>) {
    if let Some(g) = app.pending_completion_fetch.take()
        && let ActionState::TypingAttachmentPath { ref path, .. } = app.action_state
    {
        let path = path.clone();
        let tx2 = tx.clone();
        tokio::spawn(async move {
            tokio::time::sleep(std::time::Duration::from_millis(300)).await;
            let completions = compute_completions_for(&path);
            let _ = tx2.send(AppEvent::PathCompletions {
                generation: g,
                completions,
            });
        });
    }
}

fn dispatch_pending_hide(
    app: &mut AppState,
    issue_key: String,
    tx: &UnboundedSender<AppEvent>,
    hidden: &mut HiddenState,
    hidden_file: &std::path::PathBuf,
) -> Result<()> {
    app.action_state = ActionState::AwaitingAction {
        description: "Hiding…".into(),
    };
    let duration = app.team_config().hide_for_a_day.duration_hours();
    hidden.hide_for(&issue_key, duration);
    hidden.save(hidden_file)?;
    let _ = tx.send(AppEvent::ActionDone(ActionResult::Hidden { issue_key }));
    Ok(())
}

fn dispatch_pending_assign(
    app: &mut AppState,
    issue_key: String,
    client: &JiraClient,
    tx: &UnboundedSender<AppEvent>,
) {
    app.action_state = ActionState::AwaitingAction {
        description: "Assigning…".into(),
    };
    let username = app
        .current_user
        .clone()
        .unwrap_or_else(|| "currentUser()".into());
    spawn_assign(issue_key, username, client.clone(), tx.clone());
}

fn dispatch_pending_move(
    app: &mut AppState,
    issue_key: String,
    client: &JiraClient,
    tx: &UnboundedSender<AppEvent>,
) {
    app.action_state = ActionState::AwaitingAction {
        description: "Moving…".into(),
    };
    let target = app.team_jira().default_project.clone();
    spawn_move(issue_key, target, client.clone(), tx.clone());
}

fn dispatch_pending_attachment_upload(
    app: &mut AppState,
    issue_key: String,
    file_path: String,
    client: &JiraClient,
    tx: &UnboundedSender<AppEvent>,
) {
    app.action_state = ActionState::AwaitingAction {
        description: "Uploading…".into(),
    };
    let client2 = client.clone();
    let tx2 = tx.clone();
    tokio::spawn(async move {
        let path = std::path::PathBuf::from(&file_path);
        match client2.upload_attachment(&issue_key, &path).await {
            Ok(mut attachments) if !attachments.is_empty() => {
                let _ = tx2.send(AppEvent::ActionDone(ActionResult::AttachmentUploaded {
                    issue_key,
                    new_attachment: attachments.remove(0),
                }));
            }
            Ok(_) => {
                let _ = tx2.send(AppEvent::ActionDone(ActionResult::Error(anyhow::anyhow!(
                    "Upload succeeded but Jira returned no attachment data"
                ))));
            }
            Err(e) => {
                let _ = tx2.send(AppEvent::ActionDone(ActionResult::Error(e)));
            }
        }
    });
}

fn dispatch_opening_attachment(
    app: &mut AppState,
    attachment_id: String,
    content_url: String,
    filename: String,
    issue_key: String,
    client: &JiraClient,
    tx: &UnboundedSender<AppEvent>,
) {
    app.action_state = ActionState::AwaitingAction {
        description: "Fetching attachment…".into(),
    };
    let req = AttachmentFetchRequest {
        attachment_id,
        content_url,
        filename,
        issue_key,
    };
    spawn_cache_attachment(req, true, client.clone(), tx.clone());
}

fn dispatch_committing_field_edit(
    app: &mut AppState,
    issue_key: String,
    field_id: String,
    new_value: serde_json::Value,
    client: &JiraClient,
    tx: &UnboundedSender<AppEvent>,
) {
    app.action_state = ActionState::AwaitingAction {
        description: "Updating field…".into(),
    };
    spawn_commit_field_edit(issue_key, field_id, new_value, client.clone(), tx.clone());
}

fn dispatch_committing_comment_edit(
    app: &mut AppState,
    issue_key: String,
    comment_id: String,
    new_body: String,
    client: &JiraClient,
    tx: &UnboundedSender<AppEvent>,
) {
    app.action_state = ActionState::AwaitingAction {
        description: "Updating comment…".into(),
    };
    spawn_commit_comment_edit(issue_key, comment_id, new_body, client.clone(), tx.clone());
}

fn dispatch_deleting_comment(
    app: &mut AppState,
    issue_key: String,
    comment_id: String,
    client: &JiraClient,
    tx: &UnboundedSender<AppEvent>,
) {
    app.action_state = ActionState::AwaitingAction {
        description: "Deleting comment…".into(),
    };
    spawn_delete_comment(issue_key, comment_id, client.clone(), tx.clone());
}

fn spawn_cache_attachment(
    req: AttachmentFetchRequest,
    open_after: bool,
    client: JiraClient,
    tx: UnboundedSender<AppEvent>,
) {
    tokio::spawn(async move {
        let cache_path = cache_path_for(&req.issue_key, &req.attachment_id, &req.filename);
        if !cache_path.exists() {
            if let Some(parent) = cache_path.parent()
                && let Err(e) = tokio::fs::create_dir_all(parent).await
            {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::Error(e.into())));
                return;
            }
            match client.download_attachment(&req.content_url).await {
                Ok(bytes) => {
                    if let Err(e) = tokio::fs::write(&cache_path, &bytes).await {
                        let _ = tx.send(AppEvent::ActionDone(ActionResult::Error(e.into())));
                        return;
                    }
                }
                Err(e) => {
                    let _ = tx.send(AppEvent::ActionDone(ActionResult::Error(e)));
                    return;
                }
            }
        }
        let _ = tx.send(AppEvent::ActionDone(ActionResult::AttachmentCached {
            attachment_id: req.attachment_id,
            cache_path,
            open_after,
        }));
    });
}

fn dispatch_load_field_options(
    app: &mut AppState,
    req: FieldOptionsRequest,
    client: &JiraClient,
    tx: &UnboundedSender<AppEvent>,
) {
    app.action_state = ActionState::AwaitingAction {
        description: "Fetching options…".into(),
    };
    spawn_load_field_options(req, client.clone(), tx.clone());
}

struct FieldOptionsRequest {
    issue_key: String,
    field_id: String,
    label: String,
    original_json: serde_json::Value,
    description: Option<String>,
    multi: bool,
}

fn spawn_load_transitions(issue_key: String, client: JiraClient, tx: UnboundedSender<AppEvent>) {
    tokio::spawn(async move {
        match client.get_transitions(&issue_key).await {
            Ok(transitions) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::TransitionsLoaded {
                    issue_key,
                    transitions,
                }));
            }
            Err(e) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::Error(e)));
            }
        }
    });
}

fn spawn_assign(
    issue_key: String,
    username: String,
    client: JiraClient,
    tx: UnboundedSender<AppEvent>,
) {
    tokio::spawn(async move {
        match client.set_assignee(&issue_key, &username).await {
            Ok(()) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::AssignedToMe {
                    issue_key,
                }));
            }
            Err(e) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::Error(e)));
            }
        }
    });
}

fn spawn_move(
    issue_key: String,
    target: String,
    client: JiraClient,
    tx: UnboundedSender<AppEvent>,
) {
    tokio::spawn(async move {
        match client.move_issue(&issue_key, &target).await {
            Ok(()) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::MovedToProject {
                    issue_key,
                    project: target,
                }));
            }
            Err(e) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::Error(e)));
            }
        }
    });
}

fn spawn_load_field_options(
    req: FieldOptionsRequest,
    client: JiraClient,
    tx: UnboundedSender<AppEvent>,
) {
    tokio::spawn(async move {
        match client
            .get_field_options(&req.issue_key, &req.field_id)
            .await
        {
            Ok(options) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::FieldOptionsLoaded {
                    issue_key: req.issue_key,
                    field_id: req.field_id,
                    label: req.label,
                    original_json: req.original_json,
                    options,
                    description: req.description,
                    multi: req.multi,
                }));
            }
            Err(e) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::Error(e)));
            }
        }
    });
}

fn spawn_commit_field_edit(
    issue_key: String,
    field_id: String,
    new_value: serde_json::Value,
    client: JiraClient,
    tx: UnboundedSender<AppEvent>,
) {
    tokio::spawn(async move {
        match client
            .update_field(&issue_key, &field_id, new_value.clone())
            .await
        {
            Ok(()) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::FieldUpdated {
                    issue_key,
                    field_id,
                    new_value,
                }));
            }
            Err(e) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::Error(e)));
            }
        }
    });
}

fn spawn_transition(key: String, tid: String, client: JiraClient, tx: UnboundedSender<AppEvent>) {
    tokio::spawn(async move {
        // Fetch transitions to get the target status name for the result
        let name = client
            .get_transitions(&key)
            .await
            .ok()
            .and_then(|ts| ts.into_iter().find(|t| t.id == tid).map(|t| t.to.name))
            .unwrap_or_default();
        match client.post_transition(&key, &tid).await {
            Ok(()) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::TransitionApplied {
                    issue_key: key,
                    new_status: name,
                }));
            }
            Err(e) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::Error(e)));
            }
        }
    });
}

fn handle_pending_comment_edit(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut AppState,
    rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
    input_task: &mut tokio::task::JoinHandle<()>,
    tx: &UnboundedSender<AppEvent>,
) {
    let ActionState::PendingCommentEdit {
        ref issue_key,
        ref comment_id,
        ref original_body,
    } = app.action_state
    else {
        return;
    };
    let (key, cid, original) = (issue_key.clone(), comment_id.clone(), original_body.clone());
    app.action_state = ActionState::None;
    input_task.abort();
    let editor_result = open_editor_with_content(terminal, &original);
    *input_task = spawn_input_task(tx.clone());
    drain_input_events(rx);
    match editor_result {
        Ok(Some(new_text)) => {
            if new_text == original.trim() {
                // No change
            } else {
                app.action_state = ActionState::ConfirmingCommentEdit {
                    issue_key: key,
                    comment_id: cid,
                    old_text: original,
                    new_text,
                    tab: 0,
                };
            }
        }
        Ok(None) => {}
        Err(e) => {
            app.action_state = ActionState::Error(std::sync::Arc::new(e));
        }
    }
}

fn spawn_commit_comment_edit(
    issue_key: String,
    comment_id: String,
    new_body: String,
    client: JiraClient,
    tx: UnboundedSender<AppEvent>,
) {
    tokio::spawn(async move {
        match client
            .update_comment(&issue_key, &comment_id, &new_body)
            .await
        {
            Ok(updated) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::CommentEdited {
                    issue_key,
                    updated_comment: updated,
                }));
            }
            Err(e) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::Error(e)));
            }
        }
    });
}

fn spawn_delete_comment(
    issue_key: String,
    comment_id: String,
    client: JiraClient,
    tx: UnboundedSender<AppEvent>,
) {
    tokio::spawn(async move {
        match client.delete_comment(&issue_key, &comment_id).await {
            Ok(()) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::CommentDeleted {
                    issue_key,
                    comment_id,
                }));
            }
            Err(e) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::Error(e)));
            }
        }
    });
}

fn dispatch_deleting_attachment(
    app: &mut AppState,
    issue_key: String,
    attachment_id: String,
    client: &JiraClient,
    tx: &UnboundedSender<AppEvent>,
) {
    app.action_state = ActionState::AwaitingAction {
        description: "Deleting attachment…".into(),
    };
    spawn_delete_attachment(issue_key, attachment_id, client.clone(), tx.clone());
}

fn spawn_delete_attachment(
    issue_key: String,
    attachment_id: String,
    client: JiraClient,
    tx: UnboundedSender<AppEvent>,
) {
    tokio::spawn(async move {
        match client.delete_attachment(&attachment_id).await {
            Ok(()) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::AttachmentDeleted {
                    issue_key,
                    attachment_id,
                }));
            }
            Err(e) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::Error(e)));
            }
        }
    });
}

/// Open $EDITOR with optional initial content, then return the edited text.
/// This suspends the TUI.
fn open_editor_with_content(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    initial_content: &str,
) -> Result<Option<String>> {
    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;

    let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vi".into());
    let tmp = tempfile_path();
    if !initial_content.is_empty() {
        std::fs::write(&tmp, initial_content)?;
    }

    let status = std::process::Command::new(&editor).arg(&tmp).status();

    enable_raw_mode()?;
    execute!(terminal.backend_mut(), EnterAlternateScreen)?;
    terminal.clear()?;

    match status {
        Ok(s) if s.success() => {
            let content = std::fs::read_to_string(&tmp).unwrap_or_default();
            let _ = std::fs::remove_file(&tmp);
            let trimmed = content.trim().to_string();
            if trimmed.is_empty() {
                Ok(None)
            } else {
                Ok(Some(trimmed))
            }
        }
        _ => Ok(None),
    }
}

/// Open $EDITOR for the user to write a comment, then return the text.
/// This suspends the TUI.
#[allow(dead_code)]
pub fn open_editor_for_comment(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
) -> Result<Option<String>> {
    open_editor_with_content(terminal, "")
}

/// Spawn a fetch for field display names if needed (for both default and custom views).
fn maybe_spawn_field_names_fetch(
    app: &mut AppState,
    client: &JiraClient,
    tx: &UnboundedSender<AppEvent>,
) {
    use crate::tui::app::{FieldNamesState, ViewMode};
    if !matches!(app.view_mode, ViewMode::Default | ViewMode::Custom(_)) {
        return;
    }
    if app.flags.field_names == FieldNamesState::Loading {
        return;
    }

    if let ViewMode::Custom(id) = &app.view_mode {
        let Some(issue) = app.selected_issue() else {
            return;
        };
        let Some(cfg) = app.team_config().views.get(id.as_str()) else {
            return;
        };
        // Only fetch names for fields that don't have a name override and aren't cached yet
        let field_ids: Vec<String> = cfg
            .sections
            .iter()
            .flat_map(|s| s.fields.iter())
            .filter(|f| f.name.is_none())
            .filter(|f| {
                !app.field_names.contains_key(&f.field_id)
                    || !app.field_schemas.contains_key(&f.field_id)
            })
            .map(|f| f.field_id.clone())
            .collect();
        if field_ids.is_empty() {
            return;
        }
        let issue_key = issue.key.clone();
        app.flags.field_names = FieldNamesState::Loading;
        spawn_load_field_names_editmeta(issue_key, field_ids, client.clone(), tx.clone());
    } else {
        // Default view: use the global field registry to get names for all fields.
        // This covers readonly fields that don't appear in editmeta.
        if app.flags.field_names == FieldNamesState::AllLoaded {
            return;
        }
        app.flags.field_names = FieldNamesState::Loading;
        spawn_load_all_field_names(client.clone(), tx.clone());
    }
}

/// Fetch field names via editmeta (issue-specific; returns names + schema types for editable fields).
/// Used by custom views to also obtain schema types for the datetime picker.
fn spawn_load_field_names_editmeta(
    issue_key: String,
    field_ids: Vec<String>,
    client: JiraClient,
    tx: UnboundedSender<AppEvent>,
) {
    tokio::spawn(async move {
        let ids_ref: Vec<&str> = field_ids.iter().map(String::as_str).collect();
        match client.get_field_labels(&issue_key, &ids_ref).await {
            Ok((names, schemas)) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::FieldNamesLoaded {
                    names,
                    schemas,
                    all_fields: false,
                }));
            }
            Err(_) => {
                // Best-effort: silently ignore failures, field IDs will be shown as fallback
                let _ = tx.send(AppEvent::ActionDone(ActionResult::FieldNamesLoaded {
                    names: std::collections::HashMap::new(),
                    schemas: std::collections::HashMap::new(),
                    all_fields: false,
                }));
            }
        }
    });
}

/// Fetch field names from the global Jira field registry (`GET /rest/api/2/field`).
/// Returns names for ALL fields including readonly ones. Used by the default view.
fn spawn_load_all_field_names(client: JiraClient, tx: UnboundedSender<AppEvent>) {
    tokio::spawn(async move {
        match client.get_all_fields().await {
            Ok(fields) => {
                let names = fields.into_iter().map(|f| (f.id, f.name)).collect();
                let _ = tx.send(AppEvent::ActionDone(ActionResult::FieldNamesLoaded {
                    names,
                    schemas: std::collections::HashMap::new(),
                    all_fields: true,
                }));
            }
            Err(_) => {
                let _ = tx.send(AppEvent::ActionDone(ActionResult::FieldNamesLoaded {
                    names: std::collections::HashMap::new(),
                    schemas: std::collections::HashMap::new(),
                    all_fields: true,
                }));
            }
        }
    });
}

/// Shape the user's edited text into the correct JSON value for a Jira field update.
/// Object fields with a "value" key are Jira select fields; all others are plain strings.
fn shape_field_value(user_text: &str, original: &serde_json::Value) -> serde_json::Value {
    // ADF document — convert markdown back to ADF
    if original.get("type").and_then(|t| t.as_str()) == Some("doc") {
        return crate::jira::adf::markdown_to_adf(user_text);
    }
    if let serde_json::Value::Object(map) = original
        && map.contains_key("value")
    {
        return serde_json::json!({ "value": user_text });
    }
    serde_json::Value::String(user_text.to_string())
}

#[allow(dead_code)]
fn tempfile_path() -> std::path::PathBuf {
    std::env::temp_dir().join(format!("do-next-comment-{}.txt", std::process::id()))
}