zim-studio 1.5.0

A Terminal-Based Audio Project Scaffold and Metadata System
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
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
//! Terminal user interface rendering for the audio player.
//!
//! This module handles all visual rendering for the player, including the oscilloscope
//! waveform display, LED-style level meters, progress bars with mark indicators,
//! and control hints. It adapts the display based on terminal size, showing more
//! detailed visualizations when space permits.

use ratatui::{
    Frame,
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    symbols,
    text::{Line, Span},
    widgets::{
        Axis, Block, Borders, Chart, Dataset, Gauge, GraphType, Paragraph,
        canvas::{Canvas, Context},
    },
};

use super::app::{App, ViewMode, WaveformDisplayMode};
use super::save_dialog_ui::draw_save_dialog;

// UI Constants
const MIN_HEIGHT_FOR_OSCILLOSCOPE: u16 = 20;
const LED_LEVEL_THRESHOLDS: [(f32, &str); 3] = [
    (0.3, ""),  // Full circle
    (0.05, ""), // Half filled
    (0.0, ""),  // Empty circle
];

// LED color definitions for different levels
const LED_CLIPPING_LEVEL: f32 = 0.9;
const LED_HIGH_LEVEL: f32 = 0.3;
const LED_LOW_LEVEL: f32 = 0.05;

// Grid constants for oscilloscope
const GRID_COLOR: Color = Color::Rgb(0, 60, 30);
const GRID_VERTICAL_STEP: usize = 10;
const GRID_HORIZONTAL_LINES: [f64; 7] = [-0.75, -0.5, -0.25, 0.0, 0.25, 0.5, 0.75];

// Helper functions
fn format_time(seconds: u64) -> String {
    let mins = seconds / 60;
    let secs = seconds % 60;
    format!("{mins:02}:{secs:02}")
}

fn format_duration(duration: std::time::Duration) -> String {
    format_time(duration.as_secs())
}

fn create_control_button(key: &str, style: Style) -> Span<'static> {
    Span::styled(format!("[{key}]"), style)
}

/// Helper to create a control button with label
fn create_control(key: &str, label: &str, style: Style) -> Vec<Span<'static>> {
    vec![
        create_control_button(key, style),
        Span::raw(format!(" {label}  ")),
    ]
}

pub fn draw(f: &mut Frame, app: &App) {
    let size = f.area();

    match app.view_mode {
        ViewMode::Player => {
            // Draw main UI
            draw_main_ui(f, app);
        }
        ViewMode::Browser => {
            // Draw integrated browser view
            draw_integrated_browser(f, app);
        }
    }

    // Draw save dialog if active (always on top)
    if let Some(ref save_dialog) = app.save_dialog {
        draw_save_dialog(f, size, save_dialog);
    }
}

fn draw_main_ui(f: &mut Frame, app: &App) {
    let size = f.area();
    let show_oscilloscope = size.height > MIN_HEIGHT_FOR_OSCILLOSCOPE;

    let constraints = if show_oscilloscope {
        vec![
            Constraint::Length(2), // Title (reduced from 3)
            Constraint::Length(3), // File info + LEDs
            Constraint::Length(3), // Progress bar
            Constraint::Min(7),    // Waveform area
            Constraint::Length(4), // Controls (increased for 2 rows)
        ]
    } else {
        vec![
            Constraint::Length(2), // Title (reduced from 3)
            Constraint::Length(3), // File info + LEDs
            Constraint::Length(3), // Progress bar
            Constraint::Length(4), // Controls (increased for 2 rows)
        ]
    };

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .margin(1)
        .constraints(constraints)
        .split(size);

    // Title - show current file or "ZIM Player" if no file
    let title_text = if let Some(file) = &app.current_file {
        let filename = std::path::Path::new(file)
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or(file);

        // Add playlist position if available
        if let Some(position) = app.get_playlist_position() {
            format!("🎵 {filename} ({position})")
        } else {
            format!("🎵 {filename}")
        }
    } else {
        "🎵 ZIM Player".to_string()
    };

    let title = Paragraph::new(title_text)
        .style(
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        )
        .alignment(Alignment::Center);
    f.render_widget(title, chunks[0]);

    // File info with LED indicators
    draw_file_info_with_leds(f, chunks[1], app);

    // Progress bar
    draw_progress_bar(f, chunks[2], app);

    // Oscilloscope visualization (only if window is tall enough)
    if show_oscilloscope {
        draw_oscilloscope(f, chunks[3], app);
    }

    // Controls (two rows)
    let controls_idx = if show_oscilloscope { 4 } else { 3 };

    // Split controls area into two rows
    let control_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(1), Constraint::Length(1)])
        .split(chunks[controls_idx]);

    // First row of controls
    let play_color = if app.is_playing {
        Color::Yellow
    } else {
        Color::Green
    };
    let controls_row1 = vec![
        create_control_button("space", Style::default().fg(play_color)),
        Span::raw(if app.is_playing {
            " pause  "
        } else {
            " play  "
        }),
        create_control_button("←→", Style::default().fg(Color::Magenta)),
        Span::raw(" seek  "),
        create_control_button("/", Style::default().fg(Color::Blue)),
        Span::raw(" browse  "),
        create_control_button("q", Style::default().fg(Color::Red)),
        Span::raw(" quit"),
    ];

    // Second row of controls
    let loop_style = if app.is_looping {
        Style::default().fg(Color::Magenta).bg(Color::DarkGray)
    } else {
        Style::default().fg(Color::Magenta)
    };

    let mut controls_row2 = Vec::new();
    controls_row2.extend(create_control("i", "in", Style::default().fg(Color::Green)));
    controls_row2.extend(create_control(
        "o",
        "out",
        Style::default().fg(Color::Green),
    ));
    controls_row2.extend(create_control(
        "x",
        "clear",
        Style::default().fg(Color::Yellow),
    ));

    // Loop control has dynamic label
    controls_row2.push(create_control_button("l", loop_style));
    controls_row2.push(Span::raw(if app.is_looping {
        " loop ●  "
    } else {
        " loop  "
    }));

    // Waveform view toggle (only when playing and timeline waveform available)
    if app.is_playing && app.timeline_waveform.is_some() {
        let waveform_style = if app.show_timeline_while_playing {
            Style::default().fg(Color::Cyan)
        } else {
            Style::default().fg(Color::DarkGray)
        };
        controls_row2.push(create_control_button("w", waveform_style));
        controls_row2.push(Span::raw(if app.show_timeline_while_playing {
            " timeline ●  "
        } else {
            " timeline  "
        }));
    }

    // Waveform display mode indicator (cycles: line → scatter → vector)
    let mode_style = Style::default().fg(Color::Yellow);
    controls_row2.push(create_control_button("m", mode_style));
    controls_row2.push(Span::raw(format!(
        " {}  ",
        app.waveform_display_mode.label()
    )));

    controls_row2.extend(create_control(
        "s",
        "save",
        Style::default().fg(Color::Cyan),
    ));
    controls_row2.extend(create_control(
        "e",
        "edit",
        Style::default().fg(Color::Magenta),
    ));

    // Add playlist controls if playlist is active
    if app.playlist.is_some() {
        controls_row2.extend(create_control(
            "p",
            "prev",
            Style::default().fg(Color::Blue),
        ));
        controls_row2.extend(create_control(
            "n",
            "next",
            Style::default().fg(Color::Blue),
        ));
    }

    // Telemetry control has dynamic label
    controls_row2.push(create_control_button(
        "t",
        Style::default().fg(Color::Yellow),
    ));
    controls_row2.push(Span::raw(if app.telemetry.config().enabled {
        " telemetry ●"
    } else {
        " telemetry"
    }));

    let controls_widget1 = Paragraph::new(Line::from(controls_row1)).alignment(Alignment::Center);
    let controls_widget2 = Paragraph::new(Line::from(controls_row2)).alignment(Alignment::Center);

    // Add top border only on first row
    let border_widget = Block::default().borders(Borders::TOP);
    f.render_widget(border_widget, chunks[controls_idx]);

    f.render_widget(controls_widget1, control_chunks[0]);
    f.render_widget(controls_widget2, control_chunks[1]);
}

fn draw_file_info_with_leds(f: &mut Frame, area: Rect, app: &App) {
    // Show waveform calculation progress if present
    if let Some(ref progress) = app.waveform_progress {
        let progress_text = format!("Calculating waveform... {:.0}%", progress.percentage);
        let progress_style = Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::ITALIC);
        let progress_widget = Paragraph::new(progress_text)
            .style(progress_style)
            .alignment(Alignment::Center);
        f.render_widget(progress_widget, area);
        return;
    }

    // Show editor message if present
    if let Some(ref message) = app.editor_message {
        let msg_style = Style::default()
            .fg(Color::Yellow)
            .bg(Color::Black)
            .add_modifier(Modifier::ITALIC);
        let msg = Paragraph::new(message.as_str())
            .style(msg_style)
            .alignment(Alignment::Center);
        f.render_widget(msg, area);
        return;
    }

    // Split area horizontally for file info and LEDs
    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Min(20),    // File info
            Constraint::Length(12), // LED indicators
        ])
        .split(area);

    // File info - simplified since title now shows filename and position
    let file_info = if app.current_file.is_some() {
        "Ready".to_string()
    } else {
        "No file selected - Pass a file path to play".to_string()
    };

    let file_widget = Paragraph::new(file_info).style(Style::default().fg(Color::White));
    f.render_widget(file_widget, chunks[0]);

    // LED indicators
    draw_leds(f, chunks[1], app);

    // Bottom border
    let border = Block::default().borders(Borders::BOTTOM);
    f.render_widget(border, area);
}

fn draw_leds(f: &mut Frame, area: Rect, app: &App) {
    let led_text = if app.current_file.is_some() {
        let l_char = get_led_char(app.left_level);
        let r_char = get_led_char(app.right_level);
        let l_color = get_led_color(app.left_level, true);
        let r_color = get_led_color(app.right_level, false);

        vec![
            Span::raw("L"),
            Span::styled(l_char, Style::default().fg(l_color)),
            Span::raw(" R"),
            Span::styled(r_char, Style::default().fg(r_color)),
        ]
    } else {
        vec![
            Span::raw("L"),
            Span::styled("", Style::default().fg(Color::DarkGray)),
            Span::raw(" R"),
            Span::styled("", Style::default().fg(Color::DarkGray)),
        ]
    };

    let led_widget = Paragraph::new(Line::from(led_text)).alignment(Alignment::Right);
    f.render_widget(led_widget, area);
}

fn get_led_char(level: f32) -> &'static str {
    for (threshold, symbol) in LED_LEVEL_THRESHOLDS.iter() {
        if level >= *threshold {
            return symbol;
        }
    }
    "" // Default to empty circle
}

fn get_led_color(level: f32, is_left: bool) -> Color {
    match (is_left, level) {
        // Clipping (both channels show red)
        (_, l) if l > LED_CLIPPING_LEVEL => Color::Rgb(255, 100, 100),
        // Left channel (green)
        (true, l) if l > LED_HIGH_LEVEL => Color::Rgb(100, 255, 100),
        (true, l) if l > LED_LOW_LEVEL => Color::Rgb(50, 200, 50),
        (true, _) => Color::Rgb(20, 100, 20),
        // Right channel (orange/red)
        (false, l) if l > LED_HIGH_LEVEL => Color::Rgb(255, 150, 0),
        (false, l) if l > LED_LOW_LEVEL => Color::Rgb(200, 100, 0),
        (false, _) => Color::Rgb(100, 50, 0),
    }
}

fn draw_oscilloscope(f: &mut Frame, area: Rect, app: &App) {
    match app.waveform_display_mode {
        WaveformDisplayMode::Vectorscope => {
            draw_vectorscope(f, area, app);
        }
        _ => {
            // Line or Scatter mode - draw oscilloscope with grid
            let grid_canvas = Canvas::default()
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_style(Style::default().fg(Color::Cyan)),
                )
                .paint(|ctx| {
                    draw_grid(ctx, area);
                })
                .x_bounds([0.0, area.width as f64])
                .y_bounds([-1.0, 1.0]);

            f.render_widget(grid_canvas, area);

            // Calculate inner area (inside borders)
            let inner_area = area.inner(ratatui::layout::Margin {
                horizontal: 1,
                vertical: 1,
            });

            // Draw the waveform using Chart with braille/scatter markers
            draw_waveform_chart(f, inner_area, app);
        }
    }
}

/// Draw vectorscope visualization (X/Y plot of left vs right channel)
fn draw_vectorscope(f: &mut Frame, area: Rect, app: &App) {
    // Draw vectorscope grid (crosshairs and circular guides)
    let grid_canvas = Canvas::default()
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(Style::default().fg(Color::Magenta))
                .title(" Vectorscope (L/R) "),
        )
        .paint(|ctx| {
            draw_vectorscope_grid(ctx, area);
        })
        .x_bounds([-1.0, 1.0])
        .y_bounds([-1.0, 1.0]);

    f.render_widget(grid_canvas, area);

    // Calculate inner area
    let inner_area = area.inner(ratatui::layout::Margin {
        horizontal: 1,
        vertical: 1,
    });

    // Get vectorscope points (left, right pairs)
    let points = app
        .waveform_buffer
        .get_vectorscope_points(inner_area.width as usize * 4);

    if points.is_empty() {
        return;
    }

    // Create dataset for the vectorscope plot
    let datasets = vec![
        Dataset::default()
            .marker(symbols::Marker::Braille)
            .graph_type(GraphType::Scatter)
            .style(Style::default().fg(Color::Rgb(0, 255, 150)))
            .data(&points),
    ];

    let chart = Chart::new(datasets)
        .x_axis(
            Axis::default()
                .bounds([-1.0, 1.0])
                .labels::<Vec<Span>>(vec![]),
        )
        .y_axis(
            Axis::default()
                .bounds([-1.0, 1.0])
                .labels::<Vec<Span>>(vec![]),
        );

    f.render_widget(chart, inner_area);
}

/// Draw vectorscope grid with crosshairs
fn draw_vectorscope_grid(ctx: &mut Context, _area: Rect) {
    let center_x = 0.0;
    let center_y = 0.0;

    // Vertical center line (mono signal appears here)
    ctx.draw(&ratatui::widgets::canvas::Line {
        x1: center_x,
        y1: -1.0,
        x2: center_x,
        y2: 1.0,
        color: Color::Rgb(60, 60, 80),
    });

    // Horizontal center line
    ctx.draw(&ratatui::widgets::canvas::Line {
        x1: -1.0,
        y1: center_y,
        x2: 1.0,
        y2: center_y,
        color: Color::Rgb(60, 60, 80),
    });

    // Diagonal lines (45 degree stereo spread guides)
    // These show +/- 45 degree phase relationships
    ctx.draw(&ratatui::widgets::canvas::Line {
        x1: -0.9,
        y1: -0.9,
        x2: 0.9,
        y2: 0.9,
        color: Color::Rgb(40, 40, 60),
    });
    ctx.draw(&ratatui::widgets::canvas::Line {
        x1: -0.9,
        y1: 0.9,
        x2: 0.9,
        y2: -0.9,
        color: Color::Rgb(40, 40, 60),
    });

    // Reference circles at 0.5 and 1.0 radius would be nice but Canvas
    // doesn't have circle primitive, so we skip for now
}

fn draw_grid(ctx: &mut Context, area: Rect) {
    // Vertical grid lines
    for x in (0..area.width).step_by(GRID_VERTICAL_STEP) {
        ctx.draw(&ratatui::widgets::canvas::Line {
            x1: x as f64,
            y1: -1.0,
            x2: x as f64,
            y2: 1.0,
            color: GRID_COLOR,
        });
    }

    // Horizontal grid lines
    for y in GRID_HORIZONTAL_LINES {
        ctx.draw(&ratatui::widgets::canvas::Line {
            x1: 0.0,
            y1: y,
            x2: area.width as f64,
            y2: y,
            color: GRID_COLOR,
        });
    }
}

/// Draw waveform using Chart widget with braille markers for smoother rendering
fn draw_waveform_chart(f: &mut Frame, area: Rect, app: &App) {
    // Use timeline waveform when: paused OR (playing AND user toggled timeline view)
    let use_timeline =
        (!app.is_playing || app.show_timeline_while_playing) && app.timeline_waveform.is_some();

    let peaks = if use_timeline {
        // Get peaks from the full-timeline waveform (no trigger needed)
        app.timeline_waveform
            .as_ref()
            .unwrap()
            .get_display_peaks(area.width as usize)
    } else {
        // Get peak pairs from the live waveform buffer with trigger stabilization
        app.waveform_buffer
            .get_triggered_display_peaks(area.width as usize)
    };

    let has_signal = peaks.iter().any(|(min, max)| *min != 0.0 || *max != 0.0);

    // Choose colors based on mode
    let (upper_color, lower_color) = if use_timeline {
        (Color::Rgb(100, 150, 255), Color::Rgb(60, 100, 200)) // Blue tones for timeline
    } else {
        (Color::Rgb(0, 255, 100), Color::Rgb(0, 200, 80)) // Green tones for live
    };

    // Build data points for the waveform
    #[allow(clippy::complexity)]
    let (upper_data, lower_data): (Vec<(f64, f64)>, Vec<(f64, f64)>) = if has_signal {
        // Create upper envelope (max values) and lower envelope (min values)
        let upper: Vec<(f64, f64)> = peaks
            .iter()
            .enumerate()
            .map(|(i, (_min, max))| {
                let x = i as f64;
                let y = (*max * 1.5).clamp(-0.95, 0.95) as f64;
                (x, y)
            })
            .collect();

        let lower: Vec<(f64, f64)> = peaks
            .iter()
            .enumerate()
            .map(|(i, (min, _max))| {
                let x = i as f64;
                let y = (*min * 1.5).clamp(-0.95, 0.95) as f64;
                (x, y)
            })
            .collect();

        (upper, lower)
    } else {
        // Demo sine wave when no audio loaded
        let time_offset = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_millis() as f64
            / 1000.0;

        let demo: Vec<(f64, f64)> = (0..area.width)
            .map(|x| {
                let t = x as f64 / area.width as f64 * 4.0 * std::f64::consts::PI;
                let y1 = (t + time_offset * 0.5).sin() * 0.8;
                let y2 = ((t * 2.0) + time_offset).sin() * 0.4;
                let y = (y1 + y2).clamp(-0.95, 0.95);
                (x as f64, y)
            })
            .collect();

        (demo.clone(), demo)
    };

    // Choose marker and graph type based on display mode
    let (marker, graph_type) = match app.waveform_display_mode {
        WaveformDisplayMode::Scatter => (symbols::Marker::Dot, GraphType::Scatter), // Vintage look
        _ => (symbols::Marker::Braille, GraphType::Line), // Smooth connected lines
    };

    // Create datasets
    let mut datasets = vec![
        Dataset::default()
            .marker(marker)
            .graph_type(graph_type)
            .style(Style::default().fg(upper_color))
            .data(&upper_data),
        Dataset::default()
            .marker(marker)
            .graph_type(graph_type)
            .style(Style::default().fg(lower_color))
            .data(&lower_data),
    ];

    // Add playback position marker for timeline view
    let position_data: Vec<(f64, f64)>;
    if use_timeline && has_signal {
        let position_x = (app.playback_position * area.width as f32) as f64;
        position_data = vec![(position_x, -0.95), (position_x, 0.95)];
        datasets.push(
            Dataset::default()
                .marker(symbols::Marker::Braille)
                .graph_type(GraphType::Line)
                .style(Style::default().fg(Color::Rgb(255, 200, 0)))
                .data(&position_data),
        );
    }

    // Create the chart (no visible axes - we have our own grid)
    let chart = Chart::new(datasets)
        .x_axis(
            Axis::default()
                .bounds([0.0, area.width as f64])
                .labels::<Vec<Span>>(vec![]),
        )
        .y_axis(
            Axis::default()
                .bounds([-1.0, 1.0])
                .labels::<Vec<Span>>(vec![]),
        );

    f.render_widget(chart, area);
}

fn draw_progress_bar(f: &mut Frame, area: Rect, app: &App) {
    let progress = app.playback_position;

    // Format time display
    let time_info = if let Some(duration) = app.duration {
        let current_secs = (duration.as_secs() as f32 * progress) as u64;
        let current_time = format_time(current_secs);
        let total_time = format_duration(duration);

        let mut time_str = format!("{current_time} / {total_time}");

        // Add selection duration if marks are set
        if let Some(selection_duration) = app.get_selection_duration() {
            let sel_secs = selection_duration.as_secs_f32();
            time_str.push_str(&format!(" [{sel_secs:.1}s]"));
        }

        time_str
    } else {
        "00:00 / 00:00".to_string()
    };

    // Create layout for time and progress
    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Min(10),    // Progress bar
            Constraint::Length(20), // Time display (increased for selection info)
        ])
        .split(area);

    // Draw custom progress bar with markers
    draw_progress_with_marks(f, chunks[0], app);

    // Time display
    let time_widget = Paragraph::new(time_info)
        .style(Style::default().fg(Color::White))
        .alignment(Alignment::Center)
        .block(Block::default().borders(Borders::ALL));

    f.render_widget(time_widget, chunks[1]);
}

fn draw_progress_with_marks(f: &mut Frame, area: Rect, app: &App) {
    let progress = app.playback_position;
    let progress_percent = (progress * 100.0) as u16;

    // First draw the gauge
    let label_style = if progress_percent >= 50 {
        Style::default()
            .fg(Color::Black)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::White)
    };

    let progress_widget = Gauge::default()
        .block(Block::default().borders(Borders::ALL))
        .gauge_style(Style::default().fg(Color::Cyan))
        .percent(progress_percent)
        .label(Span::styled(format!("{progress_percent}%"), label_style));

    f.render_widget(progress_widget, area);

    // Now overlay the markers
    let inner_area = area.inner(ratatui::layout::Margin {
        horizontal: 1,
        vertical: 1,
    });
    let bar_width = inner_area.width;

    // Draw mark in
    if let Some(mark_in) = app.mark_in {
        let mark_x = inner_area.x + (mark_in * bar_width as f32) as u16;
        if mark_x < inner_area.x + bar_width {
            let marker = Paragraph::new("").style(
                Style::default()
                    .fg(Color::Green)
                    .add_modifier(Modifier::BOLD),
            );
            let marker_area = Rect {
                x: mark_x,
                y: inner_area.y,
                width: 1,
                height: 1,
            };
            f.render_widget(marker, marker_area);
        }
    }

    // Draw mark out
    if let Some(mark_out) = app.mark_out {
        let mark_x = inner_area.x + (mark_out * bar_width as f32) as u16;
        if mark_x < inner_area.x + bar_width {
            let marker = Paragraph::new("")
                .style(Style::default().fg(Color::Red).add_modifier(Modifier::BOLD));
            let marker_area = Rect {
                x: mark_x,
                y: inner_area.y,
                width: 1,
                height: 1,
            };
            f.render_widget(marker, marker_area);
        }
    }

    // Highlight selection region if both marks are set
    if let (Some(mark_in), Some(mark_out)) = (app.mark_in, app.mark_out) {
        let start = mark_in.min(mark_out);
        let end = mark_in.max(mark_out);

        let start_x = (start * bar_width as f32) as u16;
        let end_x = (end * bar_width as f32) as u16;
        let selection_width = end_x.saturating_sub(start_x).max(1);

        if start_x < bar_width {
            let selection_area = Rect {
                x: inner_area.x + start_x,
                y: inner_area.y,
                width: selection_width.min(bar_width - start_x),
                height: 1,
            };

            // Draw selection highlight
            let selection = Block::default().style(Style::default().bg(Color::DarkGray));
            f.render_widget(selection, selection_area);
        }
    }
}

fn draw_integrated_browser(f: &mut Frame, app: &App) {
    let size = f.area();

    // Layout: file list with preview, mini player, help (no search bar by default)
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .margin(1)
        .constraints([
            Constraint::Min(10),   // File browser
            Constraint::Length(1), // Mini player - just one line
            Constraint::Length(1), // Help hint
        ])
        .split(size);

    // Draw file browser with preview
    draw_browser_content(f, chunks[0], &app.browser);

    // Draw mini player
    draw_mini_player(f, chunks[1], app);

    // Draw help hint
    draw_browser_help(f, chunks[2], &app.browser);

    // Draw floating search bar if visible (overlay on top)
    if app.browser.search_visible {
        draw_floating_search_bar(f, size, &app.browser);
    }
}

fn draw_floating_search_bar(f: &mut Frame, area: Rect, browser: &super::browser::Browser) {
    // Calculate floating position - centered horizontally, near top
    let width = area.width.min(60); // Max width of 60 chars
    let height = 3;
    let x = (area.width.saturating_sub(width)) / 2;
    let y = 2; // Near the top

    let search_area = Rect {
        x: area.x + x,
        y: area.y + y,
        width,
        height,
    };

    // Use Clear widget to properly clear the area underneath
    f.render_widget(ratatui::widgets::Clear, search_area);

    // Then render a solid background block
    let clear_block = Block::default().style(Style::default().bg(Color::Black));
    f.render_widget(clear_block, search_area);

    let search_text = if browser.search_query.is_empty() {
        "Type to search or use 'title:' or 'tag:'...".to_string()
    } else {
        // Debug: Log what we're about to display
        log::debug!("Search query to display: {:?}", browser.search_query);
        browser.search_query.clone()
    };

    let title = "Search (Enter or Esc to close)";

    let border_style = Style::default().fg(Color::Yellow).bg(Color::Black);

    let search = Paragraph::new(search_text)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(title)
                .border_style(border_style)
                .style(Style::default().bg(Color::Black)),
        )
        .style(if browser.search_query.is_empty() {
            Style::default().fg(Color::DarkGray).bg(Color::Black)
        } else {
            Style::default().fg(Color::White).bg(Color::Black)
        });

    f.render_widget(search, search_area);
}

fn draw_browser_content(f: &mut Frame, area: Rect, browser: &super::browser::Browser) {
    use super::browser::BrowserFocus;

    // Split horizontally for file list and preview
    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(40), // File list
            Constraint::Percentage(60), // Preview
        ])
        .split(area);

    // File list
    let filtered_items = browser.get_filtered_items();
    let files: Vec<Line> = filtered_items
        .iter()
        .enumerate()
        .map(|(i, (item, _))| {
            let style = if i == browser.selected {
                Style::default().bg(Color::Blue).fg(Color::White)
            } else {
                Style::default()
            };

            let prefix = if i == browser.selected { "> " } else { "  " };
            let filename = item
                .audio_path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("Unknown");

            // Include project name if available
            let display_text = if let Some(ref project) = item.metadata.project {
                format!("{prefix}{filename} [{project}]")
            } else {
                format!("{prefix}{filename}")
            };

            Line::from(display_text).style(style)
        })
        .collect();

    let title = if browser.search_visible && browser.focus == BrowserFocus::Search {
        "Files - Press Esc to return"
    } else {
        "Files - j/k to navigate, Enter to select, / to search"
    };

    let border_style = if browser.focus == BrowserFocus::Files {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default().fg(Color::DarkGray)
    };

    let file_list = Paragraph::new(files)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(title)
                .border_style(border_style),
        )
        .scroll((browser.selected.saturating_sub(10) as u16, 0));

    f.render_widget(file_list, chunks[0]);

    // Preview
    // Calculate how much text we can actually display in the preview area
    // Account for borders (2 lines) and wrapping
    let preview_area = chunks[1];
    let usable_width = preview_area.width.saturating_sub(2) as usize; // Subtract border width
    let usable_height = preview_area.height.saturating_sub(2) as usize; // Subtract border height
    let max_chars = usable_width * usable_height; // Maximum characters that can fit

    let preview_content = if browser.selected < filtered_items.len() {
        let (item, _context) = filtered_items[browser.selected];
        // Always show the full metadata content for preview, not just the search context
        if !item.metadata.content.is_empty() {
            // Use a reasonable default (2000 chars) or the calculated max, whichever is smaller
            // This prevents showing too much text on very large terminals
            let limit = max_chars.min(2000);
            let content: String = item.metadata.content.chars().take(limit).collect();
            if item.metadata.content.len() > limit {
                content + "..."
            } else {
                content
            }
        } else {
            "No preview available".to_string()
        }
    } else {
        "No preview available".to_string()
    };

    // Build preview title with project name if available
    let preview_title = if browser.selected < filtered_items.len() {
        let (item, _) = filtered_items[browser.selected];
        if let Some(ref project) = item.metadata.project {
            format!("Preview - Project: {project}")
        } else {
            "Preview".to_string()
        }
    } else {
        "Preview".to_string()
    };

    let preview = Paragraph::new(preview_content)
        .block(Block::default().borders(Borders::ALL).title(preview_title))
        .wrap(ratatui::widgets::Wrap { trim: true });

    f.render_widget(preview, chunks[1]);
}

fn draw_mini_player(f: &mut Frame, area: Rect, app: &App) {
    // Create a more compact single-line layout
    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Length(3),  // Play/pause icon
            Constraint::Min(20),    // Progress bar with embedded percentage
            Constraint::Length(12), // Time
            Constraint::Length(8),  // LEDs
        ])
        .split(area);

    // Play/pause icon
    let play_icon = if app.is_playing { "" } else { "" };
    let play_widget = Paragraph::new(play_icon).style(Style::default().fg(if app.is_playing {
        Color::Green
    } else {
        Color::Yellow
    }));
    f.render_widget(play_widget, chunks[0]);

    // Progress bar with inline percentage text
    let progress = (app.playback_position * 100.0) as u16;

    // Change label style when progress bar passes over the percentage text
    let label_style = if progress >= 50 {
        Style::default()
            .fg(Color::Black)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::White)
    };

    let progress_bar = Gauge::default()
        .percent(progress)
        .label(Span::styled(format!("{progress}%"), label_style))
        .style(Style::default().fg(Color::DarkGray))
        .gauge_style(Style::default().fg(Color::Cyan));
    f.render_widget(progress_bar, chunks[1]);

    // Time display
    let time_text = if let Some(duration) = app.duration {
        let current = duration.as_secs_f32() * app.playback_position;
        let total = duration.as_secs_f32();
        format!("{current:.0}/{total:.0}s")
    } else {
        "--/--".to_string()
    };
    let time_widget = Paragraph::new(time_text)
        .alignment(Alignment::Center)
        .style(Style::default().fg(Color::White));
    f.render_widget(time_widget, chunks[2]);

    // LED meters - more compact
    let left_led = get_led_char(app.left_level);
    let right_led = get_led_char(app.right_level);
    let left_color = get_led_color(app.left_level, true);
    let right_color = get_led_color(app.right_level, false);

    let leds = Line::from(vec![
        Span::styled(left_led, Style::default().fg(left_color)),
        Span::raw(" "),
        Span::styled(right_led, Style::default().fg(right_color)),
    ]);

    let led_widget = Paragraph::new(leds).alignment(Alignment::Center);
    f.render_widget(led_widget, chunks[3]);
}

fn draw_browser_help(f: &mut Frame, area: Rect, browser: &super::browser::Browser) {
    use super::browser::BrowserFocus;

    let help_text = if browser.search_visible {
        match browser.focus {
            BrowserFocus::Search => {
                "Type to search | Try: 'title: my song' or 'tag: ambient' | Enter/Esc: Hide search | ←→: Seek"
            }
            BrowserFocus::Files => {
                "j/k or ↑↓: Navigate | Enter: Select | /: Search | Esc: Back | Space: Play/Pause | h/l or ←→: Seek"
            }
        }
    } else {
        "j/k or ↑↓: Navigate | Enter: Select | /: Search | Esc: Back | Space: Play/Pause | h/l or ←→: Seek"
    };

    let help_style = Style::default().fg(Color::DarkGray);
    let help = Paragraph::new(help_text)
        .style(help_style)
        .alignment(Alignment::Center);

    f.render_widget(help, area);
}

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

    #[test]
    fn test_format_time() {
        assert_eq!(format_time(0), "00:00");
        assert_eq!(format_time(59), "00:59");
        assert_eq!(format_time(60), "01:00");
        assert_eq!(format_time(3661), "61:01");
    }

    #[test]
    fn test_format_duration() {
        assert_eq!(format_duration(std::time::Duration::from_secs(0)), "00:00");
        assert_eq!(
            format_duration(std::time::Duration::from_secs(125)),
            "02:05"
        );
    }

    #[test]
    fn test_get_led_char() {
        assert_eq!(get_led_char(0.0), "");
        assert_eq!(get_led_char(0.04), "");
        assert_eq!(get_led_char(0.05), "");
        assert_eq!(get_led_char(0.2), "");
        assert_eq!(get_led_char(0.3), "");
        assert_eq!(get_led_char(1.0), "");
    }

    #[test]
    fn test_get_led_color_left_channel() {
        // Test left channel colors
        assert_eq!(get_led_color(0.01, true), Color::Rgb(20, 100, 20));
        assert_eq!(get_led_color(0.1, true), Color::Rgb(50, 200, 50));
        assert_eq!(get_led_color(0.5, true), Color::Rgb(100, 255, 100));
        assert_eq!(get_led_color(0.95, true), Color::Rgb(255, 100, 100));
    }

    #[test]
    fn test_get_led_color_right_channel() {
        // Test right channel colors
        assert_eq!(get_led_color(0.01, false), Color::Rgb(100, 50, 0));
        assert_eq!(get_led_color(0.1, false), Color::Rgb(200, 100, 0));
        assert_eq!(get_led_color(0.5, false), Color::Rgb(255, 150, 0));
        assert_eq!(get_led_color(0.95, false), Color::Rgb(255, 100, 100));
    }

    #[test]
    fn test_led_clipping_color() {
        // Both channels should show red when clipping
        assert_eq!(
            get_led_color(LED_CLIPPING_LEVEL + 0.01, true),
            Color::Rgb(255, 100, 100)
        );
        assert_eq!(
            get_led_color(LED_CLIPPING_LEVEL + 0.01, false),
            Color::Rgb(255, 100, 100)
        );
    }

    #[test]
    fn test_create_control_button() {
        let button = create_control_button("q", Style::default().fg(Color::Red));
        assert_eq!(button.content, "[q]");
        assert_eq!(button.style.fg, Some(Color::Red));
    }
}