zim-studio 1.1.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
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
//! Main application state and control flow for the audio player.
//!
//! This module serves as the central coordinator for the terminal-based audio player,
//! managing the interaction between the audio engine, user interface, file browser,
//! and save functionality. It handles the main event loop, keyboard input processing,
//! and state transitions between different modes (playback, browsing, saving).

use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode},
    execute,
    terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use log::info;
use ratatui::{Terminal, backend::CrosstermBackend};
use std::{error::Error, io, time::Duration};

use super::audio::AudioEngine;
use super::browser::Browser;
use super::save_dialog::SaveDialog;
use super::telemetry::{AudioTelemetry, TelemetryConfig};
use super::ui;
use super::waveform::WaveformBuffer;
use std::sync::mpsc;

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ViewMode {
    Player,
    Browser,
}

pub struct App {
    pub should_quit: bool,
    pub current_file: Option<String>,
    pub is_playing: bool,
    pub audio_engine: Option<AudioEngine>,
    pub waveform_buffer: WaveformBuffer,
    samples_rx: Option<mpsc::Receiver<Vec<f32>>>,
    pub left_level: f32,
    pub right_level: f32,
    pub is_stereo: bool,
    pub browser: Browser,
    pub playback_position: f32, // 0.0 to 1.0
    pub duration: Option<std::time::Duration>,
    pub mark_in: Option<f32>,  // 0.0 to 1.0
    pub mark_out: Option<f32>, // 0.0 to 1.0
    edit_counter: u32,         // Track number of edits this session
    pub save_dialog: Option<SaveDialog>,
    pub is_looping: bool, // Whether we're looping the selection
    pub view_mode: ViewMode,
    pub telemetry: AudioTelemetry,
    previous_left_level: f32,  // For slew gate rate calculation
    previous_right_level: f32, // For slew gate rate calculation
}

impl App {
    pub fn new() -> Self {
        Self {
            should_quit: false,
            current_file: None,
            is_playing: false,
            audio_engine: None,
            waveform_buffer: WaveformBuffer::new(4096),
            samples_rx: None,
            left_level: 0.0,
            right_level: 0.0,
            is_stereo: false,
            browser: Browser::new(),
            playback_position: 0.0,
            duration: None,
            mark_in: None,
            mark_out: None,
            edit_counter: 0,
            save_dialog: None,
            is_looping: false,
            view_mode: ViewMode::Player,
            telemetry: AudioTelemetry::new(),
            previous_left_level: 0.0,
            previous_right_level: 0.0,
        }
    }

    pub fn load_file(&mut self, path: &str) -> Result<(), Box<dyn Error>> {
        // Create audio engine if needed
        if self.audio_engine.is_none() {
            let (engine, samples_rx) = AudioEngine::new()?;
            self.audio_engine = Some(engine);
            self.samples_rx = Some(samples_rx);
        }

        // Load the file
        if let Some(engine) = &mut self.audio_engine {
            engine.load_file(std::path::Path::new(path))?;

            // Update channel info and duration
            if let Some(info) = &engine.info {
                self.is_stereo = info.channels > 1;
            }
            self.duration = engine.duration;

            self.current_file = Some(path.to_string());

            // Start playback automatically when file is loaded
            self.is_playing = true;
            engine.play();
        }

        Ok(())
    }

    pub fn load_files(
        &mut self,
        paths: &[String],
        gains: Option<Vec<f32>>,
    ) -> Result<(), Box<dyn Error>> {
        // Create audio engine if needed
        if self.audio_engine.is_none() {
            let (engine, samples_rx) = AudioEngine::new()?;
            self.audio_engine = Some(engine);
            self.samples_rx = Some(samples_rx);
        }

        // Load the files for mixing
        if let Some(engine) = &mut self.audio_engine {
            engine.load_files(paths, gains)?;

            // Update channel info and duration
            if let Some(info) = &engine.info {
                self.is_stereo = info.channels > 1;
            }
            self.duration = engine.duration;

            // Store files info for display
            let display_name = if paths.len() == 1 {
                paths[0].clone()
            } else {
                format!("Mixing {} files", paths.len())
            };
            self.current_file = Some(display_name);

            // Start playback automatically when files are loaded
            self.is_playing = true;
            engine.play();
        }

        Ok(())
    }

    /// Enable telemetry with custom configuration for debugging slew gates and VC control
    #[allow(dead_code)]
    pub fn enable_telemetry(&mut self, config: TelemetryConfig) {
        self.telemetry.update_config(config);
    }

    /// Enable telemetry with default debugging configuration
    pub fn enable_debug_telemetry(&mut self) {
        let config = TelemetryConfig {
            enabled: true,
            debug_audio_levels: true,
            debug_format_info: true,
            capture_interval_ms: 100, // 10Hz for debugging
            output_format: "log".to_string(),
            ..Default::default()
        };
        self.telemetry.update_config(config);
        log::info!("Audio telemetry enabled for slew gate and VC control debugging");
    }

    /// Disable telemetry
    pub fn disable_telemetry(&mut self) {
        let mut config = self.telemetry.config().clone();
        config.enabled = false;
        self.telemetry.update_config(config);
    }

    /// Export telemetry data
    #[allow(dead_code)]
    pub fn export_telemetry(&self, format: &str) -> Result<String, Box<dyn Error>> {
        match format {
            "json" => Ok(self.telemetry.export_json()?),
            "csv" => Ok(self.telemetry.export_csv()),
            _ => Err("Unsupported export format. Use 'json' or 'csv'".into()),
        }
    }

    pub fn toggle_playback(&mut self) {
        if let Some(engine) = &mut self.audio_engine {
            if self.is_playing {
                engine.pause();
                self.is_playing = false;
            } else {
                // If at 100%, restart from beginning
                if self.playback_position >= 0.99 {
                    let _ = engine.seek_relative(-self.duration.unwrap_or_default().as_secs_f32());
                }
                engine.play();
                self.is_playing = true;
            }
        }
    }

    pub fn update_waveform(&mut self) {
        self.process_audio_samples();
        self.update_playback_state();
        self.apply_level_decay();
    }

    fn process_audio_samples(&mut self) {
        let mut samples_to_process = Vec::new();

        if let Some(rx) = &self.samples_rx {
            while let Ok(samples) = rx.try_recv() {
                self.waveform_buffer.push_samples(&samples);
                if !samples.is_empty() {
                    samples_to_process.push(samples);
                }
            }
        }

        for samples in samples_to_process {
            self.calculate_audio_levels(&samples);
        }
    }

    fn calculate_audio_levels(&mut self, samples: &[f32]) {
        // Store previous levels for slew gate calculation
        self.previous_left_level = self.left_level;
        self.previous_right_level = self.right_level;

        if self.is_stereo {
            self.calculate_stereo_levels(samples);
        } else {
            self.calculate_mono_levels(samples);
        }

        // Apply gentler decay for better visibility
        self.left_level = (self.left_level * 0.98).max(self.left_level * 0.8);
        self.right_level = (self.right_level * 0.98).max(self.right_level * 0.8);

        // Capture telemetry data for observability
        let playback_state = if self.is_playing {
            "playing"
        } else {
            "stopped"
        };
        let audio_info = self.audio_engine.as_ref().and_then(|e| e.info.as_ref());

        self.telemetry.maybe_capture(
            self.left_level,
            self.right_level,
            self.previous_left_level,
            self.previous_right_level,
            playback_state,
            self.playback_position,
            Some(samples),
            audio_info,
        );
    }

    fn calculate_stereo_levels(&mut self, samples: &[f32]) {
        let mut left_sum = 0.0;
        let mut right_sum = 0.0;
        let mut left_count = 0;
        let mut right_count = 0;

        for (i, &sample) in samples.iter().enumerate() {
            if i % 2 == 0 {
                left_sum += sample * sample;
                left_count += 1;
            } else {
                right_sum += sample * sample;
                right_count += 1;
            }
        }

        // Amplify the RMS values to make LEDs more responsive
        self.left_level = ((left_sum / left_count.max(1) as f32).sqrt() * 2.0).min(1.0);
        self.right_level = ((right_sum / right_count.max(1) as f32).sqrt() * 2.0).min(1.0);
    }

    fn calculate_mono_levels(&mut self, samples: &[f32]) {
        let sum: f32 = samples.iter().map(|s| s * s).sum();
        // Mono - amplify for better visibility
        let rms = ((sum / samples.len() as f32).sqrt() * 2.0).min(1.0);
        self.left_level = rms;
        self.right_level = rms;
    }

    fn update_playback_state(&mut self) {
        let mut need_loop_seek = None;
        let mut should_stop = false;

        if let Some(engine) = &self.audio_engine {
            self.playback_position = engine.get_progress();

            // Check if we've reached the end (not looping)
            if !self.is_looping && self.is_playing && self.playback_position >= 1.0 {
                should_stop = true;
            }

            // Check if we need to loop
            if self.is_looping && self.is_playing {
                need_loop_seek = self.check_loop_boundaries();
            }
        }

        // Stop playback if we've reached the end
        if should_stop {
            self.is_playing = false;
            if let Some(engine) = &self.audio_engine {
                engine.pause();
            }
        }

        // Apply loop seek if needed
        if let (Some(offset), Some(engine)) = (need_loop_seek, &mut self.audio_engine) {
            let _ = engine.seek_relative(offset);
        }
    }

    fn check_loop_boundaries(&self) -> Option<f32> {
        if let (Some(mark_in), Some(mark_out)) = (self.mark_in, self.mark_out) {
            let loop_start = mark_in.min(mark_out);
            let loop_end = mark_in.max(mark_out);

            // Check if we've reached the end of the loop or are before the start
            if (self.playback_position >= loop_end || self.playback_position < loop_start)
                && let Some(duration) = self.duration
            {
                let current_seconds = duration.as_secs_f32() * self.playback_position;
                let start_seconds = duration.as_secs_f32() * loop_start;
                return Some(start_seconds - current_seconds);
            }
        }
        None
    }

    fn apply_level_decay(&mut self) {
        // Store previous levels for slew gate calculation
        self.previous_left_level = self.left_level;
        self.previous_right_level = self.right_level;

        if self.is_playing {
            self.left_level *= 0.99; // Slower decay for better visibility
            self.right_level *= 0.99;
        } else {
            self.left_level = 0.0;
            self.right_level = 0.0;
        }

        // Capture telemetry for decay behavior (slew gate monitoring)
        let playback_state = if self.is_playing {
            "playing"
        } else {
            "stopped"
        };
        let audio_info = self.audio_engine.as_ref().and_then(|e| e.info.as_ref());

        self.telemetry.maybe_capture(
            self.left_level,
            self.right_level,
            self.previous_left_level,
            self.previous_right_level,
            playback_state,
            self.playback_position,
            None, // No sample data during decay
            audio_info,
        );
    }

    pub fn set_mark_in(&mut self) {
        self.mark_in = Some(self.playback_position);
        info!("Mark in set at {:.1}%", self.playback_position * 100.0);
    }

    pub fn set_mark_out(&mut self) {
        self.mark_out = Some(self.playback_position);
        info!("Mark out set at {:.1}%", self.playback_position * 100.0);
    }

    pub fn clear_marks(&mut self) {
        self.mark_in = None;
        self.mark_out = None;
        self.is_looping = false; // Stop looping when marks are cleared
        info!("Marks cleared");
    }

    pub fn toggle_loop(&mut self) {
        if self.mark_in.is_some() && self.mark_out.is_some() {
            self.is_looping = !self.is_looping;
            info!(
                "Loop {}",
                if self.is_looping {
                    "enabled"
                } else {
                    "disabled"
                }
            );

            // If starting loop, jump to mark in position
            if self.is_looping
                && let (Some(mark_in), Some(duration), Some(engine)) =
                    (self.mark_in, self.duration, &mut self.audio_engine)
            {
                let start_seconds = duration.as_secs_f32() * mark_in;
                let current_seconds = duration.as_secs_f32() * self.playback_position;
                let offset = start_seconds - current_seconds;
                let _ = engine.seek_relative(offset);
            }
        } else {
            info!("Cannot loop without both marks set");
        }
    }

    pub fn get_selection_duration(&self) -> Option<std::time::Duration> {
        if let (Some(mark_in), Some(mark_out), Some(duration)) =
            (self.mark_in, self.mark_out, self.duration)
        {
            let start_secs = duration.as_secs_f32() * mark_in;
            let end_secs = duration.as_secs_f32() * mark_out;
            let selection_secs = (end_secs - start_secs).abs();
            Some(std::time::Duration::from_secs_f32(selection_secs))
        } else {
            None
        }
    }

    pub fn open_save_dialog(&mut self) {
        if let Some(current_file) = &self.current_file {
            let path = std::path::Path::new(current_file);
            let parent = path.parent().unwrap_or(std::path::Path::new("."));

            // Generate suggested filename
            let base_name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("audio");
            let source_extension = path.extension().and_then(|s| s.to_str()).unwrap_or("wav");

            // Always suggest WAV for selections (since we convert FLAC to WAV)
            // For full file saves, keep original extension
            let has_selection = self.mark_in.is_some() && self.mark_out.is_some();
            let extension = if has_selection {
                "wav" // Always WAV for selections
            } else {
                source_extension // Keep original for full file copies
            };

            let suggested_name = if has_selection {
                if self.edit_counter == 0 {
                    format!("{base_name}_edit.{extension}")
                } else {
                    format!("{}_edit_{}.{}", base_name, self.edit_counter + 1, extension)
                }
            } else {
                format!("{base_name}.{extension}")
            };

            self.save_dialog = Some(SaveDialog::new(
                parent.to_path_buf(),
                suggested_name,
                has_selection,
            ));

            info!(
                "Opened save dialog with filename: {}",
                self.save_dialog.as_ref().unwrap().filename
            );
        }
    }

    pub fn save_audio(
        &self,
        path: std::path::PathBuf,
        save_selection: bool,
    ) -> Result<(), Box<dyn Error>> {
        if let Some(current_file) = &self.current_file {
            if save_selection && self.mark_in.is_some() && self.mark_out.is_some() {
                // Save selection
                self.save_selection(current_file, path)
            } else {
                // Save full file (just copy)
                std::fs::copy(current_file, &path)?;
                info!("Copied full file to: {path:?}");
                Ok(())
            }
        } else {
            Err("No file loaded".into())
        }
    }

    fn save_selection(
        &self,
        source_path: &str,
        dest_path: std::path::PathBuf,
    ) -> Result<(), Box<dyn Error>> {
        let (mark_in, mark_out) = match (self.mark_in, self.mark_out) {
            (Some(a), Some(b)) => (a.min(b), a.max(b)),
            _ => return Err("No selection marks set".into()),
        };

        // Determine SOURCE format from extension
        let source_ext = std::path::Path::new(source_path)
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_lowercase())
            .unwrap_or_default();

        // Save the audio selection first
        let audio_result = match source_ext.as_str() {
            "wav" => self.save_wav_selection(source_path, dest_path.clone(), mark_in, mark_out),
            "flac" => {
                self.save_flac_to_wav_selection(source_path, dest_path.clone(), mark_in, mark_out)
            }
            _ => Err(format!("Unsupported source format: {source_ext}").into()),
        };

        // If audio save succeeded, try to clone and modify the sidecar file
        if audio_result.is_ok()
            && let Err(e) =
                self.clone_sidecar_for_selection(source_path, &dest_path, mark_in, mark_out)
        {
            log::warn!("Failed to create sidecar file: {e}");
            // Don't fail the entire operation if sidecar creation fails
        }

        audio_result
    }

    fn clone_sidecar_for_selection(
        &self,
        source_path: &str,
        dest_path: &std::path::Path,
        mark_in: f32,
        mark_out: f32,
    ) -> Result<(), Box<dyn Error>> {
        use std::fs;
        use std::path::PathBuf;

        // Construct source sidecar path (source_file.ext.md)
        let mut source_sidecar = PathBuf::from(source_path);
        source_sidecar.as_mut_os_string().push(".md");

        // Construct destination sidecar path (dest_file.ext.md)
        let mut dest_sidecar = dest_path.to_path_buf();
        dest_sidecar.as_mut_os_string().push(".md");

        // Calculate time ranges for documentation
        let duration_seconds = if let Some(duration) = self.duration {
            duration.as_secs_f32()
        } else {
            0.0
        };

        let start_time = (mark_in * duration_seconds) as u32;
        let end_time = (mark_out * duration_seconds) as u32;
        let selection_duration = end_time - start_time;

        let start_mins = start_time / 60;
        let start_secs = start_time % 60;
        let end_mins = end_time / 60;
        let end_secs = end_time % 60;
        let sel_mins = selection_duration / 60;
        let sel_secs = selection_duration % 60;
        let selection_duration_f32 = selection_duration as f32;

        // Simple ISO 8601 timestamp (approximate, good enough for this use case)
        let timestamp = {
            use std::process::Command;

            // Use system `date` command for proper ISO 8601 formatting
            if let Ok(output) = Command::new("date")
                .arg("-u")
                .arg("+%Y-%m-%dT%H:%M:%SZ")
                .output()
            {
                String::from_utf8_lossy(&output.stdout).trim().to_string()
            } else {
                // Fallback to basic format if date command fails
                let secs = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_secs())
                    .unwrap_or(0);
                format!("unix-{secs}")
            }
        };

        let content = if source_sidecar.exists() {
            // Clone existing sidecar and add provenance fields to YAML frontmatter
            let original_content = fs::read_to_string(&source_sidecar)?;

            if let Some(frontmatter_end) = original_content.find("\n---\n") {
                // Has YAML frontmatter - update duration and insert our fields
                let yaml_section = &original_content[..frontmatter_end];
                let markdown_section = &original_content[frontmatter_end + 5..]; // Skip "\n---\n"

                // Update duration field if it exists, otherwise add it
                let updated_yaml = if let Some(duration_start) = yaml_section.find("duration:") {
                    // Find the end of the duration line
                    let after_duration = &yaml_section[duration_start..];
                    let duration_end = after_duration.find('\n').unwrap_or(after_duration.len());

                    // Replace the duration line
                    let before = &yaml_section[..duration_start];
                    let after = &yaml_section[duration_start + duration_end..];
                    format!("{before}duration: {selection_duration_f32:.2}{after}")
                } else {
                    // Add duration field
                    format!("{yaml_section}\nduration: {selection_duration_f32:.2}")
                };

                format!(
                    "{updated_yaml}\nsource_file: \"{source_path}\"\nsource_time_start: {start_mins}:{start_secs:02}\nsource_time_end: {end_mins}:{end_secs:02}\nsource_duration: {sel_mins}:{sel_secs:02}\nextracted_at: {timestamp}\nextraction_type: \"selection\"\n---\n{markdown_section}"
                )
            } else {
                // No YAML frontmatter - add it
                let dest_filename = dest_path
                    .file_name()
                    .and_then(|f| f.to_str())
                    .unwrap_or("Unknown");

                format!(
                    "---\ntitle: \"{dest_filename}\"\nduration: {selection_duration_f32:.2}\nsource_file: \"{source_path}\"\nsource_time_start: {start_mins}:{start_secs:02}\nsource_time_end: {end_mins}:{end_secs:02}\nsource_duration: {sel_mins}:{sel_secs:02}\nextracted_at: {timestamp}\nextraction_type: \"selection\"\n---\n\n{}",
                    original_content.trim()
                )
            }
        } else {
            // Create new sidecar with gentle reminder about missing source metadata
            let dest_filename = dest_path
                .file_name()
                .and_then(|f| f.to_str())
                .unwrap_or("Unknown");

            format!(
                r#"---
title: "{dest_filename}"
duration: {selection_duration_f32:.2}
tags: ["excerpt"]
source_file: "{source_path}"
source_time_start: {start_mins}:{start_secs:02}
source_time_end: {end_mins}:{end_secs:02}
source_duration: {sel_mins}:{sel_secs:02}
extracted_at: {timestamp}
extraction_type: "selection"
---

# {dest_filename}

**⚠️ Source file had no metadata**

This audio excerpt was extracted from a source file that did not have an associated sidecar (.md) file. Consider adding metadata to your source files for better organization and searchability.

## Notes

Add your notes and tags here to document this excerpt.
"#
            )
        };

        fs::write(&dest_sidecar, content)?;
        log::info!("Created sidecar file: {}", dest_sidecar.display());

        Ok(())
    }

    fn save_wav_selection(
        &self,
        source_path: &str,
        dest_path: std::path::PathBuf,
        start: f32,
        end: f32,
    ) -> Result<(), Box<dyn Error>> {
        use hound::{WavReader, WavWriter};
        use std::fs::File;
        use std::io::BufReader;

        // Open source file
        let reader = WavReader::new(BufReader::new(File::open(source_path)?))?;
        let spec = reader.spec();

        // Calculate sample range
        let (start_sample, samples_to_write) = self.calculate_sample_range(&reader, start, end);

        // Create output file
        let mut writer = WavWriter::create(&dest_path, spec)?;

        // Read and write samples based on bit depth
        self.copy_wav_samples(
            reader,
            &mut writer,
            spec.bits_per_sample,
            start_sample,
            samples_to_write,
        )?;

        writer.finalize()?;
        info!("Saved WAV selection to: {dest_path:?}");
        Ok(())
    }

    fn calculate_sample_range(
        &self,
        reader: &hound::WavReader<std::io::BufReader<std::fs::File>>,
        start: f32,
        end: f32,
    ) -> (usize, usize) {
        let total_samples = reader.len() as usize;
        let start_sample = (start * total_samples as f32) as usize;
        let end_sample = (end * total_samples as f32) as usize;
        let samples_to_write = end_sample - start_sample;
        (start_sample, samples_to_write)
    }

    fn copy_wav_samples<W: std::io::Write + std::io::Seek>(
        &self,
        mut reader: hound::WavReader<std::io::BufReader<std::fs::File>>,
        writer: &mut hound::WavWriter<W>,
        bits_per_sample: u16,
        start_sample: usize,
        samples_to_write: usize,
    ) -> Result<(), Box<dyn Error>> {
        match bits_per_sample {
            16 => self.copy_samples::<i16, _>(&mut reader, writer, start_sample, samples_to_write),
            24 | 32 => {
                self.copy_samples::<i32, _>(&mut reader, writer, start_sample, samples_to_write)
            }
            8 => self.copy_samples::<i8, _>(&mut reader, writer, start_sample, samples_to_write),
            _ => Err(format!("Unsupported bit depth: {bits_per_sample}").into()),
        }
    }

    fn copy_samples<T, W>(
        &self,
        reader: &mut hound::WavReader<std::io::BufReader<std::fs::File>>,
        writer: &mut hound::WavWriter<W>,
        start_sample: usize,
        samples_to_write: usize,
    ) -> Result<(), Box<dyn Error>>
    where
        T: hound::Sample + std::fmt::Debug,
        W: std::io::Write + std::io::Seek,
    {
        let samples: Vec<T> = reader
            .samples::<T>()
            .skip(start_sample)
            .take(samples_to_write)
            .collect::<Result<Vec<_>, _>>()?;

        for sample in samples {
            writer.write_sample(sample)?;
        }

        Ok(())
    }

    fn save_flac_to_wav_selection(
        &self,
        source_path: &str,
        dest_path: std::path::PathBuf,
        start: f32,
        end: f32,
    ) -> Result<(), Box<dyn Error>> {
        use claxon::FlacReader;
        use hound::{WavSpec, WavWriter};

        // Open FLAC file
        let reader = FlacReader::open(source_path)?;
        let info = reader.streaminfo();

        // Calculate sample range
        let total_samples = info.samples.unwrap_or(0) as usize;
        let start_sample = (start * total_samples as f32) as usize;
        let end_sample = (end * total_samples as f32) as usize;

        // Create WAV spec from FLAC info
        let spec = WavSpec {
            channels: info.channels as u16,
            sample_rate: info.sample_rate,
            bits_per_sample: 16, // Convert to 16-bit for compatibility
            sample_format: hound::SampleFormat::Int,
        };

        // Create output WAV file
        let mut writer = WavWriter::create(&dest_path, spec)?;

        // Read and convert samples
        self.convert_flac_samples(
            reader,
            &mut writer,
            info.bits_per_sample,
            start_sample,
            end_sample,
        )?;

        writer.finalize()?;
        info!("Saved FLAC selection as WAV to: {dest_path:?}");
        Ok(())
    }

    fn convert_flac_samples<W: std::io::Write + std::io::Seek>(
        &self,
        mut reader: claxon::FlacReader<std::fs::File>,
        writer: &mut hound::WavWriter<W>,
        bits_per_sample: u32,
        start_sample: usize,
        end_sample: usize,
    ) -> Result<(), Box<dyn Error>> {
        let mut sample_count = 0;

        for sample in reader.samples() {
            if sample_count >= start_sample && sample_count < end_sample {
                let sample = sample?;
                let sample_i16 = self.convert_sample_to_16bit(sample, bits_per_sample);
                writer.write_sample(sample_i16)?;
            }

            sample_count += 1;
            if sample_count >= end_sample {
                break;
            }
        }

        Ok(())
    }

    fn convert_sample_to_16bit(&self, sample: i32, bits_per_sample: u32) -> i16 {
        match bits_per_sample {
            16 => sample as i16,
            24 => (sample >> 8) as i16,
            32 => (sample >> 16) as i16,
            _ => (sample >> (bits_per_sample - 16)) as i16,
        }
    }
}

pub fn run_with_file(
    file_path: Option<&str>,
    _gains: Option<Vec<f32>>,
) -> Result<(), Box<dyn Error>> {
    // Initialize logging
    init_logging()?;
    info!("Starting ZIM Audio Player");

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

    // Create app and load file if provided
    let mut app = App::new();

    // Scan current directory for audio files
    info!("Scanning directory for audio files...");
    if let Err(e) = app.browser.scan_directory(std::path::Path::new(".")) {
        log::error!("Could not scan directory: {e}");
    }

    if let Some(path) = file_path
        && let Err(e) = app.load_file(path)
    {
        // Clean up terminal before showing error
        disable_raw_mode()?;
        execute!(
            terminal.backend_mut(),
            LeaveAlternateScreen,
            DisableMouseCapture
        )?;
        terminal.show_cursor()?;
        return Err(e);
    }

    let res = run_app(&mut terminal, app);

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

    if let Err(err) = res {
        eprintln!("Error: {err}");
    }

    Ok(())
}

pub fn run_with_files(
    file_paths: &[String],
    gains: Option<Vec<f32>>,
) -> Result<(), Box<dyn Error>> {
    // Initialize logging
    init_logging()?;
    info!("Starting ZIM Audio Player in mixing mode");

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

    // Create app and load files for mixing
    let mut app = App::new();

    // Load multiple files
    if let Err(e) = app.load_files(file_paths, gains) {
        // Clean up terminal before showing error
        disable_raw_mode()?;
        execute!(
            terminal.backend_mut(),
            LeaveAlternateScreen,
            DisableMouseCapture
        )?;
        terminal.show_cursor()?;
        return Err(e);
    }

    let res = run_app(&mut terminal, app);

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

    if let Err(err) = res {
        eprintln!("Error: {err}");
    }

    Ok(())
}

fn run_app<B: ratatui::backend::Backend>(
    terminal: &mut Terminal<B>,
    mut app: App,
) -> Result<(), Box<dyn Error>> {
    loop {
        // Update waveform data
        app.update_waveform();

        terminal.draw(|f| ui::draw(f, &app))?;

        // Poll for events with a short timeout to allow continuous rendering
        if event::poll(Duration::from_millis(50))?
            && let Event::Key(key) = event::read()?
        {
            handle_key_event(&mut app, key)?;
        }

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

fn handle_key_event(app: &mut App, key: event::KeyEvent) -> Result<(), Box<dyn Error>> {
    if app.save_dialog.is_some() {
        handle_save_dialog_keys(app, key)
    } else {
        match app.view_mode {
            ViewMode::Player => handle_player_keys(app, key),
            ViewMode::Browser => handle_integrated_browser_keys(app, key),
        }
    }
}

fn handle_save_dialog_keys(app: &mut App, key: event::KeyEvent) -> Result<(), Box<dyn Error>> {
    use super::save_dialog::SaveDialogFocus;

    let save_dialog = app.save_dialog.as_mut().unwrap();

    match key.code {
        KeyCode::Esc => {
            app.save_dialog = None;
        }
        KeyCode::Tab => {
            save_dialog.toggle_focus();
        }
        KeyCode::Up => {
            if save_dialog.focus == SaveDialogFocus::DirectoryList {
                save_dialog.navigate_up();
            }
        }
        KeyCode::Down => {
            if save_dialog.focus == SaveDialogFocus::DirectoryList {
                save_dialog.navigate_down();
            }
        }
        KeyCode::Enter => {
            if save_dialog.focus == SaveDialogFocus::DirectoryList {
                save_dialog.enter_directory();
            } else {
                execute_save(app)?;
            }
        }
        KeyCode::Backspace => {
            save_dialog.pop_char();
        }
        KeyCode::Char(c) => {
            save_dialog.push_char(c);
        }
        _ => {}
    }
    Ok(())
}

fn execute_save(app: &mut App) -> Result<(), Box<dyn Error>> {
    if let Some(save_dialog) = &app.save_dialog {
        let save_path = save_dialog.get_full_path();
        let has_selection = save_dialog.has_selection;
        info!("Saving to: {save_path:?}");

        // Perform the save
        if let Err(e) = app.save_audio(save_path, has_selection) {
            log::error!("Failed to save audio: {e}");
            return Err(e);
        } else {
            app.edit_counter += 1;
        }
    }

    app.save_dialog = None;
    Ok(())
}

fn handle_integrated_browser_keys(
    app: &mut App,
    key: event::KeyEvent,
) -> Result<(), Box<dyn Error>> {
    use super::browser::BrowserFocus;

    // Universal keys that work regardless of focus
    match key.code {
        KeyCode::Esc => {
            app.view_mode = ViewMode::Player;
            return Ok(());
        }
        KeyCode::Tab => {
            app.browser.toggle_focus();
            return Ok(());
        }
        KeyCode::Left => {
            // Seek backward (works regardless of focus)
            if app.current_file.is_some() {
                if key.modifiers.contains(event::KeyModifiers::SHIFT) {
                    seek_audio_percentage(app, -0.2); // Jump back 20%
                } else {
                    seek_audio(app, -5.0); // Normal 5-second seek
                }
            }
            return Ok(());
        }
        KeyCode::Right => {
            // Seek forward (works regardless of focus)
            if app.current_file.is_some() {
                if key.modifiers.contains(event::KeyModifiers::SHIFT) {
                    seek_audio_percentage(app, 0.2); // Jump forward 20%
                } else {
                    seek_audio(app, 5.0); // Normal 5-second seek
                }
            }
            return Ok(());
        }
        _ => {}
    }

    // Focus-specific keys
    match app.browser.focus {
        BrowserFocus::Search => match key.code {
            KeyCode::Backspace => app.browser.pop_char(),
            KeyCode::Char('c' | 'k') if key.modifiers.contains(event::KeyModifiers::CONTROL) => {
                app.browser.clear_search(); // Ctrl+C or Ctrl+K to clear search
            }
            KeyCode::Char(c) => app.browser.push_char(c),
            _ => {}
        },
        BrowserFocus::Files => {
            match key.code {
                KeyCode::Up | KeyCode::Char('k') => {
                    app.browser.select_previous();
                    // Auto-load the selected file for preview
                    preview_selected_file(app)?;
                }
                KeyCode::Down | KeyCode::Char('j') => {
                    app.browser.select_next();
                    // Auto-load the selected file for preview
                    preview_selected_file(app)?;
                }
                KeyCode::Char('h') => {
                    // Seek backward
                    if app.current_file.is_some() {
                        if key.modifiers.contains(event::KeyModifiers::SHIFT) {
                            seek_audio_percentage(app, -0.2); // Jump back 20%
                        } else {
                            seek_audio(app, -5.0); // Normal 5-second seek
                        }
                    }
                }
                KeyCode::Char('l') => {
                    // Seek forward
                    if app.current_file.is_some() {
                        if key.modifiers.contains(event::KeyModifiers::SHIFT) {
                            seek_audio_percentage(app, 0.2); // Jump forward 20%
                        } else {
                            seek_audio(app, 5.0); // Normal 5-second seek
                        }
                    }
                }
                KeyCode::Char(' ') => {
                    // Toggle play/pause (only in Files focus)
                    // First ensure we have the selected file loaded
                    if let Some(path) = app.browser.get_selected_path() {
                        let path_str = path.to_string_lossy().to_string();

                        // If no file is loaded or it's different from the selected one, load it
                        if app.current_file.as_ref() != Some(&path_str) {
                            preview_selected_file(app)?;
                        }

                        // Now toggle playback
                        app.toggle_playback();
                    }
                }
                KeyCode::Enter => {
                    // Load file and return to player
                    if let Some(path) = app.browser.get_selected_path() {
                        let path_str = path.to_string_lossy().to_string();

                        // Check if we're already playing this file
                        let was_playing_this_file = app.current_file.as_ref() == Some(&path_str);
                        let current_position = if was_playing_this_file {
                            Some(app.playback_position)
                        } else {
                            None
                        };
                        let was_playing = app.is_playing;

                        // Load the file (this resets position to 0)
                        app.load_file(&path_str)?;

                        // If we were previewing this file, restore the position
                        if let Some(position) = current_position {
                            // Seek to the previous position
                            if let Some(duration) = app.duration
                                && let Some(engine) = &mut app.audio_engine
                            {
                                // Since load_file resets to position 0, we need to seek forward
                                // by the absolute amount
                                let target_seconds = duration.as_secs_f32() * position;
                                engine.seek_relative(target_seconds)?;
                                // Note: playback_position will be updated by the next update_waveform call
                            }

                            // Restore play state if it was playing
                            if was_playing {
                                app.is_playing = true;
                                if let Some(engine) = &app.audio_engine {
                                    engine.play();
                                }
                            }
                        }

                        app.view_mode = ViewMode::Player;
                    }
                }
                _ => {}
            }
        }
    }

    Ok(())
}

fn preview_selected_file(app: &mut App) -> Result<(), Box<dyn Error>> {
    // Clone the path to avoid borrow issues
    let selected_path = app
        .browser
        .get_selected_path()
        .map(|p| p.to_string_lossy().to_string());

    if let Some(path_str) = selected_path {
        // Only load if it's an audio file and different from current
        if (path_str.ends_with(".wav")
            || path_str.ends_with(".flac")
            || path_str.ends_with(".aiff")
            || path_str.ends_with(".aif"))
            && app.current_file.as_ref() != Some(&path_str)
        {
            app.load_file(&path_str)?;
            // Don't auto-play, let user control with space
            app.is_playing = false;
            if let Some(engine) = &app.audio_engine {
                engine.pause();
            }
        }
    }
    Ok(())
}

fn handle_player_keys(app: &mut App, key: event::KeyEvent) -> Result<(), Box<dyn Error>> {
    match key.code {
        KeyCode::Char('q') => app.should_quit = true,
        KeyCode::Char(' ') => app.toggle_playback(),
        KeyCode::Char('b') => {
            app.view_mode = ViewMode::Browser;
            app.browser.focus = super::browser::BrowserFocus::Files;
            // Initialize browser with current directory
            app.browser.scan_directory(std::path::Path::new("."))?;
        }
        KeyCode::Char('/') => {
            app.view_mode = ViewMode::Browser;
            app.browser.focus = super::browser::BrowserFocus::Search;
            // Initialize browser with current directory (preserves existing search)
            app.browser.scan_directory(std::path::Path::new("."))?;
        }
        KeyCode::Left => {
            if key.modifiers.contains(event::KeyModifiers::SHIFT) {
                seek_audio_percentage(app, -0.2); // Jump back 20%
            } else {
                seek_audio(app, -5.0); // Normal 5-second seek
            }
        }
        KeyCode::Right => {
            if key.modifiers.contains(event::KeyModifiers::SHIFT) {
                seek_audio_percentage(app, 0.2); // Jump forward 20%
            } else {
                seek_audio(app, 5.0); // Normal 5-second seek
            }
        }
        KeyCode::Char('[') | KeyCode::Char('i') => app.set_mark_in(),
        KeyCode::Char(']') | KeyCode::Char('o') => app.set_mark_out(),
        KeyCode::Char('x') => app.clear_marks(),
        KeyCode::Char('s') => app.open_save_dialog(),
        KeyCode::Char('l') => app.toggle_loop(),
        KeyCode::Char('t') => {
            if app.telemetry.config().enabled {
                app.disable_telemetry();
                info!("Audio telemetry disabled");
            } else {
                app.enable_debug_telemetry();
                info!("Audio telemetry enabled - press 't' again to disable");
            }
        }
        _ => {}
    }
    Ok(())
}

fn seek_audio(app: &mut App, seconds: f32) {
    if let Some(engine) = &mut app.audio_engine {
        let _ = engine.seek_relative(seconds);
    }
}

fn seek_audio_percentage(app: &mut App, percentage: f32) {
    if let (Some(engine), Some(duration)) = (&mut app.audio_engine, app.duration) {
        let seconds = duration.as_secs_f32() * percentage;
        let _ = engine.seek_relative(seconds);
    }
}

fn init_logging() -> Result<(), Box<dyn Error>> {
    use simplelog::*;
    use std::fs::File;

    let log_file = "/tmp/zim-player.log";
    CombinedLogger::init(vec![WriteLogger::new(
        LevelFilter::Debug,
        Config::default(),
        File::create(log_file)?,
    )])?;

    Ok(())
}

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

    #[test]
    fn test_new_app_initial_state() {
        let app = App::new();

        assert!(!app.should_quit);
        assert!(app.current_file.is_none());
        assert!(!app.is_playing);
        assert!(app.audio_engine.is_none());
        assert_eq!(app.left_level, 0.0);
        assert_eq!(app.right_level, 0.0);
        assert!(!app.is_stereo);
        assert_eq!(app.playback_position, 0.0);
        assert!(app.duration.is_none());
        assert!(app.mark_in.is_none());
        assert!(app.mark_out.is_none());
        assert!(app.save_dialog.is_none());
        assert!(!app.is_looping);
        assert_eq!(app.view_mode, ViewMode::Player);
    }

    #[test]
    fn test_set_mark_in() {
        let mut app = App::new();
        app.playback_position = 0.5;

        app.set_mark_in();

        assert_eq!(app.mark_in, Some(0.5));
    }

    #[test]
    fn test_set_mark_out() {
        let mut app = App::new();
        app.playback_position = 0.8;

        app.set_mark_out();

        assert_eq!(app.mark_out, Some(0.8));
    }

    #[test]
    fn test_clear_marks() {
        let mut app = App::new();
        app.mark_in = Some(0.2);
        app.mark_out = Some(0.8);
        app.is_looping = true;

        app.clear_marks();

        assert!(app.mark_in.is_none());
        assert!(app.mark_out.is_none());
        assert!(!app.is_looping);
    }

    #[test]
    fn test_get_selection_duration_no_marks() {
        let app = App::new();

        assert!(app.get_selection_duration().is_none());
    }

    #[test]
    fn test_get_selection_duration_with_marks() {
        let mut app = App::new();
        app.mark_in = Some(0.2);
        app.mark_out = Some(0.8);
        app.duration = Some(Duration::from_secs(10));

        let selection = app.get_selection_duration();

        assert!(selection.is_some());
        let duration = selection.unwrap();
        assert_eq!(duration.as_secs_f32(), 6.0); // (0.8 - 0.2) * 10
    }

    #[test]
    fn test_get_selection_duration_invalid_range() {
        let mut app = App::new();
        app.mark_in = Some(0.8);
        app.mark_out = Some(0.2); // Invalid: out before in
        app.duration = Some(Duration::from_secs(10));

        let selection = app.get_selection_duration();

        // The function uses abs() so it still returns a valid duration
        assert!(selection.is_some());
        let duration = selection.unwrap();
        assert_eq!(duration.as_secs_f32(), 6.0); // abs(0.2 - 0.8) * 10
    }

    #[test]
    fn test_toggle_playback_initial_state() {
        let mut app = App::new();

        // Without audio engine, toggle should not crash
        app.toggle_playback();

        assert!(!app.is_playing);
    }

    #[test]
    fn test_toggle_loop_without_marks() {
        let mut app = App::new();

        app.toggle_loop();

        // Should not enable looping without marks
        assert!(!app.is_looping);
    }

    #[test]
    fn test_toggle_loop_with_marks() {
        let mut app = App::new();
        app.mark_in = Some(0.2);
        app.mark_out = Some(0.8);

        app.toggle_loop();
        assert!(app.is_looping);

        app.toggle_loop();
        assert!(!app.is_looping);
    }

    #[test]
    fn test_open_save_dialog_without_file() {
        let mut app = App::new();

        app.open_save_dialog();

        // Dialog is only created when there's a current file
        assert!(app.save_dialog.is_none());
    }

    #[test]
    fn test_open_save_dialog_with_selection() {
        let mut app = App::new();
        app.current_file = Some("/path/to/audio.wav".to_string());
        app.mark_in = Some(0.2);
        app.mark_out = Some(0.8);
        app.edit_counter = 1;

        app.open_save_dialog();

        assert!(app.save_dialog.is_some());
        let dialog = app.save_dialog.as_ref().unwrap();
        assert!(dialog.has_selection);
        assert!(dialog.filename.contains("_edit"));
    }

    #[test]
    fn test_check_loop_boundaries_no_marks() {
        let app = App::new();
        assert!(app.check_loop_boundaries().is_none());
    }

    #[test]
    fn test_check_loop_boundaries_within_bounds() {
        let mut app = App::new();
        app.mark_in = Some(0.2);
        app.mark_out = Some(0.8);
        app.playback_position = 0.5;
        app.duration = Some(Duration::from_secs(10));

        assert!(app.check_loop_boundaries().is_none());
    }

    #[test]
    fn test_check_loop_boundaries_at_end() {
        let mut app = App::new();
        app.mark_in = Some(0.2);
        app.mark_out = Some(0.8);
        app.playback_position = 0.9; // Past the end
        app.duration = Some(Duration::from_secs(10));

        let seek = app.check_loop_boundaries();
        assert!(seek.is_some());
        assert!(seek.unwrap() < 0.0); // Should seek backwards
    }

    #[test]
    fn test_convert_sample_to_16bit() {
        let app = App::new();

        // Test 16-bit (no conversion)
        assert_eq!(app.convert_sample_to_16bit(1000, 16), 1000);

        // Test 24-bit conversion
        assert_eq!(app.convert_sample_to_16bit(256000, 24), 1000);

        // Test 32-bit conversion
        assert_eq!(app.convert_sample_to_16bit(65536000, 32), 1000);
    }

    #[test]
    fn test_apply_level_decay_playing() {
        let mut app = App::new();
        app.is_playing = true;
        app.left_level = 1.0;
        app.right_level = 1.0;

        app.apply_level_decay();

        assert!(app.left_level < 1.0);
        assert!(app.right_level < 1.0);
        assert_eq!(app.left_level, 0.99);
        assert_eq!(app.right_level, 0.99);
    }

    #[test]
    fn test_apply_level_decay_stopped() {
        let mut app = App::new();
        app.is_playing = false;
        app.left_level = 0.5;
        app.right_level = 0.5;

        app.apply_level_decay();

        assert_eq!(app.left_level, 0.0);
        assert_eq!(app.right_level, 0.0);
    }
}