nooise 1.5.2

Ambient music generator for the terminal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
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
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
use std::collections::BTreeSet;

use super::*;

const SAVE_MESSAGE_TTL: std::time::Duration = std::time::Duration::from_secs(3);

/// Chords tab's local navigation depth: base params, drilled into the
/// active slots' Root list, or drilled into one slot's secondary fields.
#[derive(Clone, Copy, PartialEq, Default)]
pub(crate) enum ChordDrill {
    #[default]
    None,
    Progression,
    Slot(usize),
}

/// Translates a Chords-tab visible-row index to its real `CHORDS_CONTROLS`
/// index for the positional registry setters; a no-op on every other tab.
fn chords_selected_index(tab: Tab, chord_drill: ChordDrill, selected: usize) -> usize {
    if tab == Tab::Chords {
        chords_flat_index(chord_drill, selected)
    } else {
        selected
    }
}

pub(crate) fn ui_loop(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    controls: Arc<ArcSwap<FluidControls>>,
    automation_shared: Arc<ArcSwap<AutomationState>>,
    telemetry: Arc<FluidTelemetry>,
    initial_automation: AutomationState,
    updates: UpdateNotice,
) -> Result<(), Box<dyn Error>> {
    let mut tab = Tab::Master;
    let mut selected = 0usize;
    let mut lfo_selected = 0usize;
    let mut chord_drill = ChordDrill::None;
    let mut flipped = FlippedUnits::new();
    let mut numeric_entry: Option<NumericEntry> = None;
    let mut fluid = FluidState::new();
    let mut last = Instant::now();
    let started = Instant::now();
    let mut save_message: Option<(String, Instant)> = None;
    let mut automation = PublishedAutomation::new(initial_automation, automation_shared);

    'ui: loop {
        let c = FluidControls::clone(&controls.load());
        if save_message
            .as_ref()
            .is_some_and(|(_, shown_at)| shown_at.elapsed() >= SAVE_MESSAGE_TTL)
        {
            save_message = None;
        }
        let update_message = updates.message();
        let automation_message = automation_footer(automation.state());
        let chords_message = chords_footer(tab, chord_drill);
        let footer_message = save_message
            .as_ref()
            .map(|(message, _)| message.as_str())
            .or(automation_message.as_deref())
            .or(chords_message.as_deref())
            .or(update_message.as_deref());
        let items = if tab == Tab::Chords {
            chords_tab_controls(&c, chord_drill)
        } else {
            tab_controls(tab, &c)
        };
        let items_len = items.len();
        selected = selected.min(items_len.saturating_sub(1));

        let now = Instant::now();
        let dt = (now - last).as_secs_f32().min(0.05);
        last = now;
        fluid.tick(dt, &telemetry);

        let cursor_visible = (started.elapsed().as_millis() / 400).is_multiple_of(2);
        let beat = telemetry.beat();
        terminal.draw(|f| {
            render(
                f,
                &items,
                tab,
                selected,
                lfo_selected,
                beat,
                NumericDisplay {
                    entry: numeric_entry.as_ref().map(|entry| entry.buffer.as_str()),
                    cursor_visible,
                },
                &fluid,
                automation.state(),
                &c,
                footer_message,
                &flipped,
                chord_drill,
            )
        })?;

        // Drain every queued key event before the next draw so a held key
        // never falls behind the frame rate; the first poll doubles as the
        // ~16 ms frame pacing wait.
        let mut pending = event::poll(std::time::Duration::from_millis(16))?;
        while pending {
            let event = event::read()?;
            pending = event::poll(std::time::Duration::ZERO)?;
            let Event::Key(key) = event else {
                continue;
            };
            if key.kind != KeyEventKind::Press {
                continue;
            }
            if let Some(entry) = numeric_entry.as_mut() {
                match key.code {
                    KeyCode::Esc => numeric_entry = None,
                    KeyCode::Enter => {
                        if entry.is_complete_number()
                            && let Ok(value) = entry.buffer.parse::<f32>()
                        {
                            set_modulator_or_control(
                                &mut automation,
                                lfo_selected,
                                &controls,
                                tab,
                                chords_selected_index(tab, chord_drill, selected),
                                value,
                                beat,
                                &flipped,
                            );
                        }
                        numeric_entry = None;
                    }
                    KeyCode::Backspace => {
                        entry.buffer.pop();
                    }
                    KeyCode::Char(c) => entry.push(c),
                    _ => {}
                }
                continue;
            }
            match key.code {
                KeyCode::Char('s') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                    save_message = Some(match copy_launch_line(&controls, automation.state()) {
                        Ok(()) => ("nooise copied to clipboard".to_string(), Instant::now()),
                        Err(err) => (format!("Save failed: {err}"), Instant::now()),
                    });
                }
                // Esc only ever drills out one level (nested field-macro
                // editor, then the modulator editor, then nothing) — it
                // never quits, so escaping a deep edit can't risk exiting
                // the app. Only q and Ctrl+C do that.
                KeyCode::Esc if automation.state().is_editor_open() => {
                    close_one_level(&mut automation, &mut lfo_selected);
                }
                KeyCode::Esc if tab == Tab::Chords && chord_drill != ChordDrill::None => {
                    selected = match chord_drill {
                        ChordDrill::Slot(n) => n,
                        _ => 4,
                    };
                    chord_drill = match chord_drill {
                        ChordDrill::Slot(_) => ChordDrill::Progression,
                        _ => ChordDrill::None,
                    };
                }
                KeyCode::Esc => {}
                KeyCode::Char('q') => break 'ui,
                KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => break 'ui,
                KeyCode::Tab | KeyCode::BackTab => {
                    if automation.state().is_editor_open() {
                        automation.edit(AutomationState::close_editor);
                    }
                    tab = if key.code == KeyCode::Tab {
                        tab.next()
                    } else {
                        tab.previous()
                    };
                    selected = 0;
                    lfo_selected = 0;
                    chord_drill = ChordDrill::None;
                }
                KeyCode::Up | KeyCode::Char('k') => {
                    if automation.state().is_editor_open() {
                        if lfo_selected <= 1 {
                            automation.edit(AutomationState::close_editor);
                            lfo_selected = 0;
                        } else {
                            lfo_selected -= 1;
                        }
                    } else {
                        selected = selected.saturating_sub(1);
                    }
                }
                KeyCode::Down | KeyCode::Char('j') => {
                    if automation.state().is_editor_open() {
                        if lfo_selected >= active_field_count(automation.state()) {
                            automation.edit(AutomationState::close_editor);
                            selected = selected.saturating_add(1).min(items_len.saturating_sub(1));
                            lfo_selected = 0;
                        } else {
                            lfo_selected += 1;
                        }
                    } else {
                        selected = selected.saturating_add(1).min(items_len.saturating_sub(1));
                    }
                }
                KeyCode::Char('H') => {
                    reset_lfo_or_control(
                        &mut automation,
                        lfo_selected,
                        &controls,
                        tab,
                        chords_selected_index(tab, chord_drill, selected),
                        beat,
                    );
                }
                KeyCode::Left | KeyCode::Char('h')
                    if key.modifiers.contains(KeyModifiers::SHIFT) =>
                {
                    reset_lfo_or_control(
                        &mut automation,
                        lfo_selected,
                        &controls,
                        tab,
                        chords_selected_index(tab, chord_drill, selected),
                        beat,
                    );
                }
                KeyCode::Left | KeyCode::Char('h') => {
                    adjust_lfo_or_control(
                        &mut automation,
                        lfo_selected,
                        &controls,
                        tab,
                        chords_selected_index(tab, chord_drill, selected),
                        -1.0,
                        beat,
                        &flipped,
                    );
                }
                KeyCode::Right | KeyCode::Char('l') => {
                    adjust_lfo_or_control(
                        &mut automation,
                        lfo_selected,
                        &controls,
                        tab,
                        chords_selected_index(tab, chord_drill, selected),
                        1.0,
                        beat,
                        &flipped,
                    );
                }
                KeyCode::Char('f') => {
                    open_modulator(&mut automation, &items, selected, ModKind::Lfo, &mut lfo_selected);
                }
                KeyCode::Char('e') => {
                    open_modulator(
                        &mut automation,
                        &items,
                        selected,
                        ModKind::Envelope,
                        &mut lfo_selected,
                    );
                }
                KeyCode::Char('v') => {
                    match active_field(automation.state(), lfo_selected) {
                        // On an LFO field row: stack (or un-stack) a macro
                        // onto that specific field, never on by default.
                        ActiveField::Lfo(address, field)
                            if !is_macro_id(address.id()) && field.macro_key().is_some() =>
                        {
                            let key = unit_key(address.id(), field.macro_key());
                            let was_open = automation.state().open_field() == Some(key.as_str());
                            automation.edit(|state| state.toggle_open_field(key));
                            let base = field_row_index(automation.state(), address, field);
                            lfo_selected = if was_open { base } else { base + 1 };
                        }
                        // Already inside a field's nested macro rows: v
                        // closes just that, same as Esc — never hijacks the
                        // parent LFO editor into swapping to a top-level
                        // Macro editor.
                        ActiveField::LfoMacro(..) => {
                            close_one_level(&mut automation, &mut lfo_selected);
                        }
                        // Discrete fields (Shape) carry no macro_key and
                        // can't take a stacked macro — a continuous -1..1
                        // contribution has no defined meaning against an
                        // enum index. A true no-op, same as v being refused
                        // on a macro slider's own rows, not a fallthrough
                        // into hijacking the parent LFO editor.
                        ActiveField::Lfo(_, field) if field.macro_key().is_none() => {}
                        // Anywhere else (including already inside the
                        // top-level Macro editor, where this closes it): v
                        // opens the Macro editor for the selected control,
                        // for any slider.
                        _ => {
                            open_modulator(
                                &mut automation,
                                &items,
                                selected,
                                ModKind::Macro,
                                &mut lfo_selected,
                            );
                        }
                    }
                }
                KeyCode::Char('x') | KeyCode::Char('X') => {
                    match active_field(automation.state(), lfo_selected) {
                        // On an open field-macro row: remove just that
                        // stacked macro, keep the parent LFO editor open.
                        ActiveField::LfoMacro(address, field, _) => {
                            let key = unit_key(address.id(), field.macro_key());
                            automation.edit(|state| state.remove_field_macro(&key));
                            lfo_selected = field_row_index(automation.state(), address, field);
                        }
                        _ if automation.state().is_editor_open() => {
                            automation.edit(AutomationState::remove_open_route);
                            lfo_selected = 0;
                        }
                        _ => {
                            if let Some(item) = items.get(selected) {
                                let address = ControlAddress::new(item.id);
                                automation.edit(|state| state.clear_control(address));
                            }
                        }
                    }
                }
                KeyCode::Enter => {
                    if !automation.state().is_editor_open() {
                        if tab == Tab::Chords {
                            match (chord_drill, items.get(selected).map(|i| i.id)) {
                                (ChordDrill::None, Some("pad.progression"))
                                    if is_custom_progression(progression_index(
                                        c.pad.progression,
                                    )) =>
                                {
                                    chord_drill = ChordDrill::Progression;
                                    selected = 0;
                                }
                                (ChordDrill::Progression, Some(_)) => {
                                    chord_drill = ChordDrill::Slot(selected);
                                    selected = 0;
                                }
                                _ => {}
                            }
                        } else if let Some(item) = items.get(selected)
                            && let Some(owner) = tab_owning_control(item.id)
                            && owner != tab
                        {
                            tab = owner;
                            selected = 0;
                            lfo_selected = 0;
                            chord_drill = ChordDrill::None;
                        }
                    }
                }
                KeyCode::Char('t') | KeyCode::Char('T') => {
                    if let Some(key) =
                        unit_toggle_key(automation.state(), lfo_selected, &items, selected)
                    {
                        let now_flipped = !flipped.remove(&key);
                        if now_flipped {
                            flipped.insert(key);
                        }
                        snap_after_unit_flip(
                            &mut automation,
                            lfo_selected,
                            &controls,
                            tab,
                            chords_selected_index(tab, chord_drill, selected),
                            now_flipped,
                            beat,
                        );
                    }
                }
                KeyCode::Char('r') | KeyCode::Char('R') => {
                    if let Some(address) = automation.state().active_address()
                        && automation.state().active_kind() == Some(ModKind::Lfo)
                    {
                        automation.edit(|state| {
                            if let Some(route) = state.route_mut(address)
                                && route.shape.is_random()
                            {
                                route.reseed();
                            }
                        });
                    }
                }
                KeyCode::Char(c) if c.is_ascii_digit() || c == '.' || c == '-' => {
                    let mut entry = NumericEntry::default();
                    entry.push(c);
                    numeric_entry = Some(entry);
                }
                _ => {}
            }
        }
    }

    Ok(())
}

/// Submenu row 0 is the parent slider; rows 1.. map onto the modulator fields.
/// Fields whose display and numeric entry have been flipped to the opposite
/// time base (beats <-> ms) by pressing T on that row. Keyed per field, so
/// each slider carries its own unit; stepping always stays on the native
/// grid and conversion happens at the current BPM.
pub(crate) type FlippedUnits = BTreeSet<String>;

/// Stable key for a flippable field: the control id, plus a submenu field
/// qualifier for modulator rows (e.g. "kick.level#lfo.interval").
pub(crate) fn unit_key(id: &str, field: Option<&str>) -> String {
    match field {
        Some(field) => format!("{id}#{field}"),
        None => id.to_string(),
    }
}

pub(crate) fn beats_to_ms(beats: f32, bpm: f32) -> f32 {
    beats * 60_000.0 / bpm.max(1.0)
}

pub(crate) fn ms_to_beats(ms: f32, bpm: f32) -> f32 {
    ms * bpm.max(1.0) / 60_000.0
}

fn fmt_ms(ms: f32) -> String {
    if ms >= 1000.0 {
        format!("{:.2} s", ms / 1000.0)
    } else {
        format!("{ms:.0} ms")
    }
}

fn fmt_beats(beats: f32) -> String {
    format!("{beats:.3} beats")
}

/// Cross-base display for a flipped time field; None when the field has no
/// time base to flip.
fn flip_display(base: TimeBase, value: f32, bpm: f32) -> Option<String> {
    match base {
        TimeBase::Beats => Some(fmt_ms(beats_to_ms(value, bpm))),
        TimeBase::Ms => Some(fmt_beats(ms_to_beats(value, bpm))),
        TimeBase::None => None,
    }
}

/// Numeric entry typed in a flipped field's display unit, converted back to
/// the native base before snapping.
fn flip_entry(base: TimeBase, value: f32, bpm: f32) -> f32 {
    match base {
        TimeBase::Beats => ms_to_beats(value, bpm),
        TimeBase::Ms => beats_to_ms(value, bpm),
        TimeBase::None => value,
    }
}

/// Step grids for a flipped time field: native-beats fields move on a 10 ms
/// grid, native-ms fields on the 0.125-beat grid.
const FLIP_MS_STEP: f32 = 10.0;
const FLIP_BEAT_STEP: f32 = 0.125;

/// One h/l step for a flipped time field, taken in its display unit and
/// returned in the native unit (unclamped; the setter clamps).
fn flipped_step(native: TimeBase, value: f32, dir: f32, bpm: f32) -> f32 {
    match native {
        TimeBase::Beats => ms_to_beats(
            snap_step(beats_to_ms(value, bpm) + dir * FLIP_MS_STEP, FLIP_MS_STEP),
            bpm,
        ),
        TimeBase::Ms => beats_to_ms(
            snap_step(ms_to_beats(value, bpm) + dir * FLIP_BEAT_STEP, FLIP_BEAT_STEP),
            bpm,
        ),
        TimeBase::None => value,
    }
}

/// Landing rule for the unit toggle: flipping a field so it displays beats
/// rounds its value onto the beat grid; flipping to ms keeps the exact
/// equivalent so the value can then move freely in time.
pub(crate) fn snap_after_unit_flip(
    automation: &mut PublishedAutomation,
    lfo_selected: usize,
    controls: &Arc<ArcSwap<FluidControls>>,
    tab: Tab,
    selected: usize,
    now_flipped: bool,
    beat: f64,
) {
    let bpm = controls.load().master.bpm;
    match active_field(automation.state(), lfo_selected) {
        // Modulator time fields are native beats: un-flipping lands back on
        // their own grid via the snapping setter.
        ActiveField::Lfo(address, field) if !now_flipped => automation.edit(|state| {
            if let Some(route) = state.route_mut(address) {
                match field {
                    LfoField::Interval => route.set_field_at(field, route.cycle_beats, beat),
                    LfoField::Offset => route.set_field_at(field, route.phase_offset_beats, beat),
                    _ => {}
                }
            }
        }),
        ActiveField::Envelope(address, field) if !now_flipped => automation.edit(|state| {
            if let Some(route) = state.envelope_mut(address) {
                match field {
                    EnvField::Attack => route.set_field(field, route.attack_beats),
                    EnvField::Decay => route.set_field(field, route.decay_beats),
                    EnvField::Amount | EnvField::Trigger => {}
                }
            }
        }),
        ActiveField::Control => {
            let Some(spec) = tab_specs(tab).get(selected) else {
                return;
            };
            let mut next = FluidControls::clone(&controls.load());
            let current = (spec.get)(&next);
            match (spec.time_base, now_flipped) {
                // Back to native beats: land on the control's own grid.
                (TimeBase::Beats, false) => spec.apply_quantized_value(current, &mut next),
                // An ms control now displayed in beats: round to the nearest
                // divided beat.
                (TimeBase::Ms, true) => {
                    let beats = snap_step(ms_to_beats(current, bpm), FLIP_BEAT_STEP)
                        .max(FLIP_BEAT_STEP);
                    spec.apply_raw(beats_to_ms(beats, bpm), &mut next);
                }
                _ => return,
            }
            controls.store(Arc::new(next));
        }
        _ => {}
    }
}

/// The flip key qualifier for a modulator time field, None for unit-less ones.
fn lfo_time_key(field: LfoField) -> Option<&'static str> {
    match field {
        LfoField::Interval => Some("lfo.interval"),
        LfoField::Offset => Some("lfo.offset"),
        _ => None,
    }
}

fn env_time_key(field: EnvField) -> Option<&'static str> {
    match field {
        EnvField::Attack => Some("env.attack"),
        EnvField::Decay => Some("env.decay"),
        EnvField::Amount | EnvField::Trigger => None,
    }
}

/// The flip key for whatever time field the cursor sits on, or None when the
/// selection has no time base (T is then a no-op).
fn unit_toggle_key(
    automation: &AutomationState,
    lfo_selected: usize,
    items: &[ControlItem],
    selected: usize,
) -> Option<String> {
    match active_field(automation, lfo_selected) {
        ActiveField::Lfo(address, field) => {
            lfo_time_key(field).map(|key| unit_key(address.id(), Some(key)))
        }
        ActiveField::Envelope(address, field) => {
            env_time_key(field).map(|key| unit_key(address.id(), Some(key)))
        }
        ActiveField::LfoMacro(..) | ActiveField::Macro(..) => None,
        ActiveField::Control => {
            let item = items.get(selected)?;
            let spec = spec_by_id(item.id)?;
            (spec.time_base != TimeBase::None).then(|| unit_key(item.id, None))
        }
    }
}

/// One selectable row inside an open LFO editor: either one of the LFO's own
/// fields, or one of the two rows (amount, target) of a macro currently
/// stacked onto that field. The macro rows only exist while that field's `v`
/// gesture has expanded them — never by default.
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum LfoSubRow {
    Field(LfoField),
    FieldMacro(LfoField, MacroField),
}

pub(crate) fn lfo_submenu_rows(
    automation: &AutomationState,
    address: ControlAddress,
) -> Vec<LfoSubRow> {
    let mut rows = Vec::with_capacity(LfoField::ALL.len() * (1 + MacroField::ALL.len()));
    for field in LfoField::ALL {
        rows.push(LfoSubRow::Field(field));
        if is_macro_id(address.id()) {
            continue;
        }
        if let Some(key_str) = field.macro_key() {
            let key = unit_key(address.id(), Some(key_str));
            if automation.open_field() == Some(key.as_str()) {
                for slot in MacroField::ALL {
                    rows.push(LfoSubRow::FieldMacro(field, slot));
                }
            }
        }
    }
    rows
}

/// The submenu row index (1-based, matching `lfo_selected`) of an LFO
/// field's own row, or 0 if it isn't present. Used to land the cursor back
/// on a field's row after its nested rows appear or disappear, since the
/// field's own position never shifts (nested rows only ever insert or
/// remove immediately after it).
fn field_row_index(automation: &AutomationState, address: ControlAddress, field: LfoField) -> usize {
    lfo_submenu_rows(automation, address)
        .iter()
        .position(|row| *row == LfoSubRow::Field(field))
        .map_or(0, |pos| pos + 1)
}

/// Which LFO field currently has its nested macro editor expanded, if any.
fn field_macro_owner(automation: &AutomationState, address: ControlAddress) -> Option<LfoField> {
    let open_key = automation.open_field()?;
    LfoField::ALL.into_iter().find(|field| {
        field
            .macro_key()
            .is_some_and(|key_str| unit_key(address.id(), Some(key_str)) == open_key)
    })
}

/// Close exactly one level of nesting on the open editor: a field-macro's
/// own editor if one is expanded, else the whole modulator editor. This is
/// the single place that governs "close the innermost open thing" — Esc and
/// re-pressing `v` on a nested field-macro row both route through it, so
/// drilling out one step never destroys more than what's actually open.
pub(crate) fn close_one_level(automation: &mut PublishedAutomation, lfo_selected: &mut usize) {
    let Some(address) = automation.state().active_address() else {
        return;
    };
    if let Some(field) = field_macro_owner(automation.state(), address) {
        automation.edit(AutomationState::close_open_field);
        *lfo_selected = field_row_index(automation.state(), address, field);
    } else {
        automation.edit(AutomationState::close_editor);
        *lfo_selected = 0;
    }
}

pub(crate) fn env_field_at(index: usize) -> Option<EnvField> {
    EnvField::ALL.get(index.checked_sub(1)?).copied()
}

pub(crate) fn macro_field_at(index: usize) -> Option<MacroField> {
    MacroField::ALL.get(index.checked_sub(1)?).copied()
}

/// Submenu row count for the currently open editor (0 when none is open).
pub(crate) fn active_field_count(automation: &AutomationState) -> usize {
    match automation.active_kind() {
        Some(ModKind::Lfo) => automation
            .active_address()
            .map_or(LfoField::ALL.len(), |address| {
                lfo_submenu_rows(automation, address).len()
            }),
        Some(ModKind::Envelope) => EnvField::ALL.len(),
        Some(ModKind::Macro) => MacroField::ALL.len(),
        None => 0,
    }
}

/// Whether a modulator kind can open on a control. Envelopes live only on
/// macro sliders; macro routes live only on regular controls (no macro
/// feeding another macro).
fn kind_allowed_on(kind: ModKind, id: &str) -> bool {
    match kind {
        ModKind::Lfo => true,
        ModKind::Envelope => is_macro_id(id),
        ModKind::Macro => !is_macro_id(id),
    }
}

/// Toggle a modulator editor of `kind` on the selected control: same kind on
/// the same control closes it (settings kept — x is the remove gesture),
/// otherwise the open editor is swapped for the requested one (created
/// audible-neutral).
pub(crate) fn open_modulator(
    automation: &mut PublishedAutomation,
    items: &[ControlItem],
    selected: usize,
    kind: ModKind,
    sub_selected: &mut usize,
) {
    if let Some(item) = items.get(selected) {
        if !kind_allowed_on(kind, item.id) {
            return;
        }
        let address = ControlAddress::new(item.id);
        automation.edit(|state| {
            let already =
                state.active_address() == Some(address) && state.active_kind() == Some(kind);
            state.close_editor();
            if !already {
                match kind {
                    ModKind::Lfo => {
                        state.open_or_create(address);
                    }
                    ModKind::Envelope => {
                        state.open_or_create_envelope(address);
                    }
                    ModKind::Macro => {
                        state.open_or_create_macro(address);
                    }
                }
            }
        });
        *sub_selected = 1;
    }
}

pub(crate) struct PublishedAutomation {
    state: AutomationState,
    shared: Arc<ArcSwap<AutomationState>>,
}

impl PublishedAutomation {
    pub(crate) fn new(state: AutomationState, shared: Arc<ArcSwap<AutomationState>>) -> Self {
        shared.store(Arc::new(state.clone()));
        Self { state, shared }
    }

    pub(crate) fn state(&self) -> &AutomationState {
        &self.state
    }

    pub(crate) fn edit(&mut self, edit: impl FnOnce(&mut AutomationState)) {
        edit(&mut self.state);
        self.shared.store(Arc::new(self.state.clone()));
    }
}

/// Which modulator field (if any) the submenu cursor sits on for the open
/// editor. Returns None when the parent slider row (index 0) is selected or no
/// editor is open, so the caller edits the underlying control instead.
enum ActiveField {
    Lfo(ControlAddress, LfoField),
    /// A macro's amount/target row nested under an LFO field, only present
    /// while that field's stacked macro is expanded for editing.
    LfoMacro(ControlAddress, LfoField, MacroField),
    Envelope(ControlAddress, EnvField),
    Macro(ControlAddress, MacroField),
    Control,
}

fn active_field(automation: &AutomationState, lfo_selected: usize) -> ActiveField {
    let Some(address) = automation.active_address() else {
        return ActiveField::Control;
    };
    if lfo_selected == 0 {
        return ActiveField::Control;
    }
    match automation.active_kind() {
        Some(ModKind::Lfo) => match lfo_submenu_rows(automation, address).get(lfo_selected - 1) {
            Some(LfoSubRow::Field(field)) => ActiveField::Lfo(address, *field),
            Some(LfoSubRow::FieldMacro(field, mf)) => ActiveField::LfoMacro(address, *field, *mf),
            None => ActiveField::Control,
        },
        Some(ModKind::Envelope) => match env_field_at(lfo_selected) {
            Some(field) => ActiveField::Envelope(address, field),
            None => ActiveField::Control,
        },
        Some(ModKind::Macro) => match macro_field_at(lfo_selected) {
            Some(field) => ActiveField::Macro(address, field),
            None => ActiveField::Control,
        },
        None => ActiveField::Control,
    }
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn adjust_lfo_or_control(
    automation: &mut PublishedAutomation,
    lfo_selected: usize,
    controls: &Arc<ArcSwap<FluidControls>>,
    tab: Tab,
    selected: usize,
    dir: f32,
    beat: f64,
    flipped: &FlippedUnits,
) {
    let bpm = controls.load().master.bpm;
    match active_field(automation.state(), lfo_selected) {
        ActiveField::Lfo(address, field) => {
            let is_flipped = lfo_time_key(field)
                .is_some_and(|key| flipped.contains(&unit_key(address.id(), Some(key))));
            automation.edit(|state| {
                let Some(route) = state.route_mut(address) else {
                    return;
                };
                match (is_flipped, field) {
                    (true, LfoField::Interval) => {
                        let next = flipped_step(TimeBase::Beats, route.cycle_beats, dir, bpm);
                        route.set_field_raw_at(field, next, beat);
                    }
                    (true, LfoField::Offset) => {
                        let next =
                            flipped_step(TimeBase::Beats, route.phase_offset_beats, dir, bpm);
                        route.set_field_raw_at(field, next, beat);
                    }
                    _ => route.adjust_field_at(field, dir, beat),
                }
            });
        }
        ActiveField::Envelope(address, field) => {
            let is_flipped = env_time_key(field)
                .is_some_and(|key| flipped.contains(&unit_key(address.id(), Some(key))));
            automation.edit(|state| {
                let Some(route) = state.envelope_mut(address) else {
                    return;
                };
                match (is_flipped, field) {
                    (true, EnvField::Attack) => {
                        let next = flipped_step(TimeBase::Beats, route.attack_beats, dir, bpm);
                        route.set_field_raw(field, next);
                    }
                    (true, EnvField::Decay) => {
                        let next = flipped_step(TimeBase::Beats, route.decay_beats, dir, bpm);
                        route.set_field_raw(field, next);
                    }
                    _ => route.adjust_field(field, dir),
                }
            });
        }
        ActiveField::LfoMacro(address, field, macro_field) => automation.edit(|state| {
            let key = unit_key(address.id(), field.macro_key());
            if let Some(route) = state.field_macro_mut(&key) {
                route.adjust_field(macro_field, dir);
            }
        }),
        ActiveField::Macro(address, field) => automation.edit(|state| {
            if let Some(route) = state.macro_route_mut(address) {
                route.adjust_field(field, dir);
            }
        }),
        ActiveField::Control => {
            let flipped_spec = tab_specs(tab).get(selected).filter(|spec| {
                spec.time_base != TimeBase::None && flipped.contains(&unit_key(spec.id, None))
            });
            match flipped_spec {
                Some(spec) => {
                    let mut next = FluidControls::clone(&controls.load());
                    let current = (spec.get)(&next);
                    spec.apply_raw(flipped_step(spec.time_base, current, dir, bpm), &mut next);
                    controls.store(Arc::new(next));
                }
                None => adjust(controls, tab, selected, dir),
            }
        }
    }
}

fn reset_lfo_or_control(
    automation: &mut PublishedAutomation,
    lfo_selected: usize,
    controls: &Arc<ArcSwap<FluidControls>>,
    tab: Tab,
    selected: usize,
    beat: f64,
) {
    match active_field(automation.state(), lfo_selected) {
        ActiveField::Lfo(address, field) => automation.edit(|state| {
            if let Some(route) = state.route_mut(address) {
                route.reset_field_at(field, beat);
            }
        }),
        ActiveField::Envelope(address, field) => automation.edit(|state| {
            if let Some(route) = state.envelope_mut(address) {
                route.reset_field(field);
            }
        }),
        ActiveField::LfoMacro(address, field, macro_field) => automation.edit(|state| {
            let key = unit_key(address.id(), field.macro_key());
            if let Some(route) = state.field_macro_mut(&key) {
                route.reset_field(macro_field);
            }
        }),
        ActiveField::Macro(address, field) => automation.edit(|state| {
            if let Some(route) = state.macro_route_mut(address) {
                route.reset_field(field);
            }
        }),
        ActiveField::Control => reset_to_min(controls, tab, selected),
    }
}

#[allow(clippy::too_many_arguments)]
fn set_modulator_or_control(
    automation: &mut PublishedAutomation,
    lfo_selected: usize,
    controls: &Arc<ArcSwap<FluidControls>>,
    tab: Tab,
    selected: usize,
    value: f32,
    beat: f64,
    flipped: &FlippedUnits,
) {
    let bpm = controls.load().master.bpm;
    match active_field(automation.state(), lfo_selected) {
        ActiveField::Lfo(address, field) => automation.edit(|state| {
            let is_flipped = lfo_time_key(field)
                .is_some_and(|key| flipped.contains(&unit_key(address.id(), Some(key))));
            if let Some(route) = state.route_mut(address) {
                if is_flipped {
                    // Typed ms is exact: convert and clamp, but don't snap
                    // back onto the beat grid.
                    route.set_field_raw_at(field, flip_entry(TimeBase::Beats, value, bpm), beat);
                } else {
                    route.set_field_at(field, value, beat);
                }
            }
        }),
        ActiveField::Envelope(address, field) => automation.edit(|state| {
            let is_flipped = env_time_key(field)
                .is_some_and(|key| flipped.contains(&unit_key(address.id(), Some(key))));
            if let Some(route) = state.envelope_mut(address) {
                if is_flipped {
                    route.set_field_raw(field, flip_entry(TimeBase::Beats, value, bpm));
                } else {
                    route.set_field(field, value);
                }
            }
        }),
        ActiveField::LfoMacro(address, field, macro_field) => automation.edit(|state| {
            let key = unit_key(address.id(), field.macro_key());
            if let Some(route) = state.field_macro_mut(&key) {
                route.set_field(macro_field, value);
            }
        }),
        ActiveField::Macro(address, field) => automation.edit(|state| {
            if let Some(route) = state.macro_route_mut(address) {
                route.set_field(field, value);
            }
        }),
        ActiveField::Control => {
            match tab_specs(tab).get(selected) {
                Some(spec)
                    if spec.time_base != TimeBase::None
                        && flipped.contains(&unit_key(spec.id, None)) =>
                {
                    // Typed input in the flipped unit is exact: convert and
                    // clamp, but don't snap onto the native step grid.
                    let mut next = FluidControls::clone(&controls.load());
                    spec.apply_raw(flip_entry(spec.time_base, value, bpm), &mut next);
                    controls.store(Arc::new(next));
                }
                _ => set_value(controls, tab, selected, value),
            }
        }
    }
}

fn automation_footer(automation: &AutomationState) -> Option<String> {
    let address = automation.active_address()?;
    match automation.active_kind()? {
        ModKind::Lfo => {
            let route = automation.route(address)?;
            let reseed = if route.shape.is_random() {
                "   r reseed"
            } else {
                ""
            };
            Some(format!(
                "LFO {}   {}   {:.2} beats   depth {:.0}%{reseed}   x remove   Esc close",
                address.id(),
                route.shape.label(),
                route.cycle_beats,
                route.depth_ratio * 100.0
            ))
        }
        ModKind::Envelope => {
            let route = automation.envelope(address)?;
            Some(format!(
                "ENV {}   {}   amount {:+.0}%   x remove   Esc close",
                address.id(),
                route.field_display(EnvField::Trigger),
                route.amount * 100.0
            ))
        }
        ModKind::Macro => {
            let route = automation.macro_route(address)?;
            Some(format!(
                "MACRO {}   {}   x remove   Esc close",
                address.id(),
                route.summary(),
            ))
        }
    }
}

pub(crate) fn chords_footer(tab: Tab, chord_drill: ChordDrill) -> Option<String> {
    if tab != Tab::Chords {
        return None;
    }
    match chord_drill {
        ChordDrill::None => None,
        ChordDrill::Progression => Some("Progression   Enter: open chord   Esc: back".to_string()),
        ChordDrill::Slot(n) => Some(format!("Chord {}   Esc: back", n + 1)),
    }
}

fn copy_launch_line(
    controls: &Arc<ArcSwap<FluidControls>>,
    automation: &AutomationState,
) -> Result<(), Box<dyn Error>> {
    let c = FluidControls::clone(&controls.load());
    let line = launch_line(&SongState {
        controls: c,
        automation: automation.clone(),
    })?;
    let mut clipboard = arboard::Clipboard::new()?;
    clipboard.set_text(line)?;
    Ok(())
}

pub(crate) fn adjust(controls: &Arc<ArcSwap<FluidControls>>, tab: Tab, selected: usize, dir: f32) {
    let mut next = FluidControls::clone(&controls.load());
    apply_delta(tab, selected, dir, &mut next);
    controls.store(Arc::new(next));
}

pub(crate) fn reset_to_min(controls: &Arc<ArcSwap<FluidControls>>, tab: Tab, selected: usize) {
    let mut next = FluidControls::clone(&controls.load());
    apply_min(tab, selected, &mut next);
    controls.store(Arc::new(next));
}

pub(crate) fn set_value(
    controls: &Arc<ArcSwap<FluidControls>>,
    tab: Tab,
    selected: usize,
    value: f32,
) {
    let mut next = FluidControls::clone(&controls.load());
    apply_value(tab, selected, value, &mut next);
    controls.store(Arc::new(next));
}

pub(crate) struct NumericDisplay<'a> {
    entry: Option<&'a str>,
    cursor_visible: bool,
}

#[cfg(test)]
impl NumericDisplay<'_> {
    pub(crate) fn empty() -> Self {
        Self {
            entry: None,
            cursor_visible: false,
        }
    }
}

// ============================================================
// Fluid visualizer: chords drive the field colour, kicks
// spawn ripples. Driven entirely by live audio-thread telemetry.
// ============================================================

pub(crate) const FLUID_GRADIENT: &[char] = &[' ', '·', '∙', '•', '●', '◉', '⬤'];
pub(crate) const RIPPLE_LIFETIME: f32 = 3.0;
pub(crate) const RIPPLE_SPEED: f32 = 0.42; // normalized units / s

/// One chord = one hue. Cycles with the pad engine's 5-chord table.
pub(crate) fn hue_for_chord(index: u64) -> f32 {
    const HUES: [f32; 5] = [205.0, 270.0, 325.0, 158.0, 38.0];
    HUES[(index % HUES.len() as u64) as usize]
}

pub(crate) struct FluidState {
    t: f32,
    ripples: Vec<(f32, f32, f32)>, // (cx, cy, age) in 0..1 field coords
    last_kick: u64,
    hue: f32,
}

impl FluidState {
    pub(crate) fn new() -> Self {
        Self {
            t: 0.0,
            ripples: Vec::new(),
            last_kick: 0,
            hue: hue_for_chord(0),
        }
    }

    pub(crate) fn tick(&mut self, dt: f32, telemetry: &FluidTelemetry) {
        self.t += dt;

        // kick pulses -> ripples (golden-angle scatter so they don't stack)
        let kick = telemetry.kick_pulse.load(Ordering::Relaxed);
        if kick > self.last_kick {
            let new = (kick - self.last_kick).min(4);
            for k in 0..new {
                let n = (self.last_kick + k + 1) as f32;
                // Kick ripples originate along the bottom edge and radiate up,
                // keeping them clear of the centered control panel.
                let cx = (n * 0.618_034).fract();
                let cy = 0.92 + (n * 0.381_966).fract() * 0.06;
                self.ripples.push((cx.clamp(0.06, 0.94), cy, 0.0));
            }
            self.last_kick = kick;
        }

        for r in &mut self.ripples {
            r.2 += dt;
        }
        self.ripples.retain(|r| r.2 < RIPPLE_LIFETIME);
    }

    /// Liquid field value in 0..1 at normalized coords, with ripple distortion.
    pub(crate) fn field(&self, nx: f32, ny: f32) -> f32 {
        let z = self.t * 0.5;
        let mut v = 0.0;
        v += (nx * 6.0 + z).sin() * (ny * 5.0 - z * 0.7).cos();
        v += ((nx * 3.3 - ny * 4.1) + z * 1.3).sin() * 0.7;
        v += (nx * 11.0 + ny * 9.0 - z * 0.4).sin() * 0.35;
        v += ((nx + ny) * 7.5 + (z * 0.9).sin() * 2.0).cos() * 0.5;

        for &(cx, cy, age) in &self.ripples {
            let dx = nx - cx;
            let dy = ny - cy;
            let dist = (dx * dx + dy * dy).sqrt();
            let front = age * RIPPLE_SPEED;
            let fade = (1.0 - age / RIPPLE_LIFETIME).max(0.0);
            // small, tight ripple rising from the bottom edge
            let ring = (-((dist - front) * 12.0).powi(2)).exp();
            v += (dist * 34.0 - age * 9.0).sin() * ring * fade * 1.6;
        }

        (v / 3.0).tanh() * 0.5 + 0.5
    }
}

pub(crate) fn fluid_hsv(h: f32, s: f32, v: f32) -> Color {
    let h = ((h % 360.0) + 360.0) % 360.0;
    let c = v * s;
    let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
    let m = v - c;
    let (r, g, b) = match (h / 60.0) as u32 {
        0 => (c, x, 0.0),
        1 => (x, c, 0.0),
        2 => (0.0, c, x),
        3 => (0.0, x, c),
        4 => (x, 0.0, c),
        _ => (c, 0.0, x),
    };
    Color::Rgb(
        ((r + m) * 255.0) as u8,
        ((g + m) * 255.0) as u8,
        ((b + m) * 255.0) as u8,
    )
}

pub(crate) struct FluidWidget<'a> {
    fluid: &'a FluidState,
}

impl Widget for FluidWidget<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        let w = area.width.max(1) as f32;
        let h = area.height.max(1) as f32;
        let base = self.fluid.hue;

        for y in 0..area.height {
            for x in 0..area.width {
                let nx = x as f32 / w;
                let ny = y as f32 / h;
                let v = self.fluid.field(nx, ny);

                // edge vignette
                let edge_x = (nx.min(1.0 - nx) * 2.0).min(1.0);
                let edge_y = (ny.min(1.0 - ny) * 2.0).min(1.0);
                let vig = (edge_x.min(edge_y) * 1.4).clamp(0.2, 1.0);

                let hue = base + (v - 0.5) * 45.0;
                let sat = (0.5 + v * 0.3).clamp(0.0, 1.0);
                let val = ((0.12 + v * 0.8) * vig).clamp(0.0, 1.0);

                let gi = ((v * (FLUID_GRADIENT.len() - 1) as f32).round() as usize)
                    .min(FLUID_GRADIENT.len() - 1);
                buf[(area.x + x, area.y + y)]
                    .set_char(FLUID_GRADIENT[gi])
                    .set_style(Style::default().fg(fluid_hsv(hue, sat, val)));
            }
        }
    }
}

/// Multiply an RGB colour toward black; non-RGB passes through unchanged.
pub(crate) fn darken(c: Color, factor: f32) -> Color {
    if let Color::Rgb(r, g, b) = c {
        Color::Rgb(
            (r as f32 * factor) as u8,
            (g as f32 * factor) as u8,
            (b as f32 * factor) as u8,
        )
    } else {
        c
    }
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn render(
    f: &mut Frame,
    items: &[ControlItem],
    active_tab: Tab,
    selected: usize,
    lfo_selected: usize,
    beat: f64,
    numeric: NumericDisplay<'_>,
    fluid: &FluidState,
    automation: &AutomationState,
    controls: &FluidControls,
    update_message: Option<&str>,
    flipped: &FlippedUnits,
    chord_drill: ChordDrill,
) {
    let bpm = controls.master.bpm;
    let mod_ctx = ModContext {
        beat,
        kick_interval_beats: controls.kick.interval_beats,
        kick_offset_beats: controls.kick.offset_beats,
    };
    let area = f.area();
    f.render_widget(FluidWidget { fluid }, area);

    // centered control overlay
    let pw = ((area.width as f32 * 0.62) as u16)
        .clamp(46, area.width.saturating_sub(2).max(46))
        .min(area.width);
    let ph = ((area.height as f32 * 0.92) as u16)
        .clamp(10, area.height.saturating_sub(2).max(10))
        .min(area.height);
    let px = area.x + (area.width.saturating_sub(pw)) / 2;
    let py = area.y + (area.height.saturating_sub(ph)) / 2;
    let panel = Rect::new(px, py, pw, ph);

    // Frosted-glass scrim: darken the live fluid underneath instead of covering
    // it, so the visualizer still shows through the panel.
    {
        let buf = f.buffer_mut();
        for y in panel.top()..panel.bottom() {
            for x in panel.left()..panel.right() {
                let cell = &mut buf[(x, y)];
                let tint = darken(cell.fg, 0.30);
                cell.set_char(' ');
                cell.set_bg(tint);
                cell.set_fg(Color::Rgb(30, 34, 44));
            }
        }
    }

    // Borders only (transparent fill) so the scrim shows through.
    let block = Block::default()
        .title(format!(" {APP_ID} "))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Rgb(150, 160, 185)));
    let inner = block.inner(panel);
    f.render_widget(block, panel);

    let layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // 0 top pad
            Constraint::Length(1), // 1 pad
            Constraint::Length(1), // 2 tab line
            Constraint::Length(1), // 3 pad
            Constraint::Min(0),    // 4 control rows
            Constraint::Length(1), // 5 footer
        ])
        .split(inner);

    let tab_line: String = Tab::all()
        .iter()
        .map(|t| {
            let name = if *t == Tab::Chords {
                match chord_drill {
                    ChordDrill::Progression => format!("{} › Progression", t.name()),
                    ChordDrill::Slot(n) => format!("{} › Chord {}", t.name(), n + 1),
                    ChordDrill::None => t.name().to_string(),
                }
            } else {
                t.name().to_string()
            };
            if *t == active_tab {
                format!("[{name}]")
            } else {
                name
            }
        })
        .collect::<Vec<_>>()
        .join("  ");
    f.render_widget(
        Paragraph::new(tab_line).alignment(Alignment::Center).style(
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        ),
        layout[2],
    );

    // One text row per control, blank line between for vertical breathing room.
    let bar_w = (inner.width as usize).saturating_sub(34).clamp(6, 80);
    let mut rows: Vec<Line> = Vec::with_capacity(items.len() * 3);
    for (i, item) in items.iter().enumerate() {
        let active = i == selected;
        let address = ControlAddress::new(item.id);
        let route = automation.route(address);
        let envelope = automation.envelope(address);
        let macro_route = automation.macro_route(address);
        let macro_mod = live_macro_contribution(automation, controls, address, mod_ctx);
        let editor_here = automation.active_address() == Some(address);
        let lfo_open_here = editor_here && automation.active_kind() == Some(ModKind::Lfo);
        let env_open_here = editor_here && automation.active_kind() == Some(ModKind::Envelope);
        let macro_open_here = editor_here && automation.active_kind() == Some(ModKind::Macro);
        let editor_open_here = editor_here;
        let parent_active = active && (!editor_open_here || lfo_selected == 0);
        let prefix = if parent_active { "▶ " } else { "  " };
        let display = if parent_active {
            if let Some(entry) = numeric.entry {
                let cursor = if numeric.cursor_visible { "_" } else { " " };
                format!("> {entry}{cursor}")
            } else {
                item.display.clone()
            }
        } else {
            item.display.clone()
        };
        let display = if (numeric.entry.is_some() && parent_active)
            || !flipped.contains(&unit_key(item.id, None))
        {
            display
        } else {
            flip_display(address.spec().time_base, item.value, bpm).unwrap_or(display)
        };
        let fg = if parent_active {
            Color::Rgb(120, 230, 255)
        } else {
            Color::Rgb(170, 178, 195)
        };
        let mut style = Style::default().fg(fg);
        if parent_active {
            style = style.add_modifier(Modifier::BOLD);
        }
        // The LFO route folded with any macro stacked onto its own fields
        // (amount/interval/offset), so markers show what the engine hears.
        let effective_lfo =
            route.map(|r| live_effective_lfo_route(automation, controls, address, r, mod_ctx));
        let markers = {
            let spec = address.spec();
            let base = match spec.bar {
                Bar::Linear => item.value,
                Bar::Log2 => 2f32.powf(item.value),
            };
            let range = item.max - item.min;
            let ratio_of = |value: f32| {
                let value = match spec.bar {
                    Bar::Linear => value,
                    Bar::Log2 => value.log2(),
                };
                if range.abs() <= f32::EPSILON {
                    0.0
                } else {
                    ((value - item.min) / range).clamp(0.0, 1.0)
                }
            };
            // Ghosts only for sources that actually contribute.
            let lfo = effective_lfo
                .as_ref()
                .filter(|r| r.depth_ratio > f32::EPSILON);
            let env = envelope.filter(|r| r.amount.abs() > f32::EPSILON);
            let single = |l: Option<&LfoRoute>, e: Option<&EnvelopeRoute>, m: Option<f32>| {
                ratio_of(modulated_control_value_full(spec, l, e, m, base, mod_ctx))
            };
            // While an editor is open on this control, faintly shade the full
            // reach of every active source (its full throw, not just the
            // live instant) so turning a depth/amount knob previews how far
            // it can push the effective value.
            let mod_range = spec.max - spec.min;
            let shadow = editor_here.then(|| {
                let mut lo = base;
                let mut hi = base;
                if let Some(r) = effective_lfo.as_ref() {
                    let swing = mod_range * r.depth_ratio.clamp(0.0, 1.0);
                    lo = lo.min(base - swing);
                    hi = hi.max(base + swing);
                }
                if let Some(r) = envelope {
                    let swing = mod_range * r.amount.clamp(-1.0, 1.0);
                    lo = lo.min(base + swing.min(0.0));
                    hi = hi.max(base + swing.max(0.0));
                }
                if let Some(r) = macro_route {
                    let (swing_lo, swing_hi) = r.swing(mod_range);
                    lo = lo.min(base + swing_lo);
                    hi = hi.max(base + swing_hi);
                }
                (
                    ratio_of(lo.clamp(spec.min, spec.max)),
                    ratio_of(hi.clamp(spec.min, spec.max)),
                )
            });
            SliderMarkers {
                effective: (lfo.is_some() || env.is_some() || macro_mod.is_some())
                    .then(|| single(lfo, env, macro_mod)),
                lfo: lfo.map(|r| single(Some(r), None, None)),
                envelope: env.map(|r| single(None, Some(r), None)),
                macro_: macro_mod.map(|combined| single(None, None, Some(combined))),
                shadow,
            }
        };
        let mut spans = vec![Span::styled(format!("{prefix}{:<15} ", item.label), style)];
        spans.extend(slider_spans(item_ratio(item), markers, bar_w, style));
        spans.push(Span::styled(format!(" {display}"), style));
        rows.push(Line::from(spans));

        if let Some(route) = route {
            if lfo_open_here {
                for (fi, sub_row) in lfo_submenu_rows(automation, address).iter().enumerate() {
                    match *sub_row {
                        LfoSubRow::Field(field) => {
                            let value_display = match field {
                                LfoField::Interval
                                    if flipped
                                        .contains(&unit_key(item.id, Some("lfo.interval"))) =>
                                {
                                    flip_display(TimeBase::Beats, route.cycle_beats, bpm)
                                }
                                LfoField::Offset
                                    if flipped
                                        .contains(&unit_key(item.id, Some("lfo.offset"))) =>
                                {
                                    flip_display(TimeBase::Beats, route.phase_offset_beats, bpm)
                                }
                                _ => None,
                            }
                            .unwrap_or_else(|| route.field_display(field));
                            rows.push(field_line(
                                field.label(),
                                route.field_ratio(field),
                                value_display,
                                lfo_selected == fi + 1,
                                &numeric,
                                bar_w,
                                LFO_PALETTE,
                            ));
                            // A macro stacked on this field but not currently
                            // expanded shows as a closed chip, same as a
                            // regular control's macro assignment.
                            if let Some(key_str) = field.macro_key() {
                                let key = unit_key(item.id, Some(key_str));
                                if let Some(field_route) = automation.field_macro(&key)
                                    && !field_route.is_neutral()
                                {
                                    rows.push(macro_chip_line(field_route));
                                }
                            }
                        }
                        LfoSubRow::FieldMacro(field, macro_field) => {
                            let key = unit_key(item.id, field.macro_key());
                            let Some(field_route) = automation.field_macro(&key) else {
                                continue;
                            };
                            rows.push(field_line(
                                &format!("· {}", macro_field.label()),
                                field_route.field_ratio(macro_field),
                                field_route.field_display(macro_field),
                                lfo_selected == fi + 1,
                                &numeric,
                                bar_w,
                                MACRO_PALETTE,
                            ));
                        }
                    }
                }
            }
            rows.push(lfo_lane_line(route, beat, bar_w, lfo_open_here));
        }
        if let Some(route) = envelope {
            if env_open_here {
                for (fi, field) in EnvField::ALL.iter().enumerate() {
                    let value_display = match field {
                        EnvField::Attack
                            if flipped.contains(&unit_key(item.id, Some("env.attack"))) =>
                        {
                            flip_display(TimeBase::Beats, route.attack_beats, bpm)
                        }
                        EnvField::Decay
                            if route.decay_beats > 0.0
                                && flipped
                                    .contains(&unit_key(item.id, Some("env.decay"))) =>
                        {
                            flip_display(TimeBase::Beats, route.decay_beats, bpm)
                        }
                        _ => None,
                    }
                    .unwrap_or_else(|| route.field_display(*field));
                    rows.push(field_line(
                        field.label(),
                        route.field_ratio(*field),
                        value_display,
                        lfo_selected == fi + 1,
                        &numeric,
                        bar_w,
                        ENV_PALETTE,
                    ));
                }
            }
            rows.push(env_lane_line(route, mod_ctx, bar_w, env_open_here));
        }
        if let Some(route) = macro_route {
            if macro_open_here {
                for (fi, field) in MacroField::ALL.iter().enumerate() {
                    rows.push(field_line(
                        &field.label(),
                        route.field_ratio(*field),
                        route.field_display(*field),
                        lfo_selected == fi + 1,
                        &numeric,
                        bar_w,
                        MACRO_PALETTE,
                    ));
                }
            } else {
                rows.push(macro_chip_line(route));
            }
        }
        if i + 1 < items.len() {
            rows.push(Line::from(""));
        }
    }
    f.render_widget(Paragraph::new(rows), layout[4]);

    let footer = update_message
        .unwrap_or("jk select   h/l adjust   f LFO   v macro   T units   Enter set   q quit");
    let footer_style = if update_message.is_some() {
        Style::default()
            .fg(Color::Rgb(255, 220, 120))
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::Rgb(120, 128, 145))
    };
    f.render_widget(
        Paragraph::new(footer)
            .alignment(Alignment::Center)
            .style(footer_style),
        layout[5],
    );
}

/// Colour pair for a modulator submenu: (active row, idle row).
#[derive(Clone, Copy)]
pub(crate) struct FieldPalette {
    active: Color,
    idle: Color,
}

pub(crate) const LFO_PALETTE: FieldPalette = FieldPalette {
    active: Color::Rgb(255, 130, 210),
    idle: Color::Rgb(190, 105, 210),
};

pub(crate) const ENV_PALETTE: FieldPalette = FieldPalette {
    active: Color::Rgb(140, 235, 175),
    idle: Color::Rgb(95, 195, 140),
};

pub(crate) const MACRO_PALETTE: FieldPalette = FieldPalette {
    active: Color::Rgb(255, 200, 120),
    idle: Color::Rgb(210, 160, 90),
};

/// Compact one-line reminder of a closed macro assignment under its control.
fn macro_chip_line(route: &MacroRoute) -> Line<'static> {
    Line::from(Span::styled(
        format!("    {:<15} ⇒ {}", "", route.summary()),
        Style::default().fg(MACRO_PALETTE.idle),
    ))
}

/// Baseline submenu field row: label, clamped ratio bar, live display, shared
/// numeric-entry cursor. Every modulator field renders through this.
fn field_line(
    label: &str,
    ratio: f32,
    value_display: String,
    active: bool,
    numeric: &NumericDisplay<'_>,
    bar_w: usize,
    palette: FieldPalette,
) -> Line<'static> {
    let mut style = Style::default().fg(if active { palette.active } else { palette.idle });
    if active {
        style = style.add_modifier(Modifier::BOLD);
    }
    let prefix = if active { "▶ " } else { "  " };
    let display = if active && let Some(entry) = numeric.entry {
        let cursor = if numeric.cursor_visible { "_" } else { " " };
        format!("> {entry}{cursor}")
    } else {
        value_display
    };
    let bar = ratio_bar(ratio, bar_w, '█', '░');
    Line::from(Span::styled(
        format!("{prefix}  {label:<13} {bar} {display}"),
        style,
    ))
}

const LANE_WAVE: [&str; 8] = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"];

/// How many random cycles the lane scopes so sample & hold / random drift read
/// as an actual scrolling trajectory rather than a single flat step.
const RANDOM_LANE_CYCLES: f32 = 4.0;

fn lane_glyph(level: f32) -> &'static str {
    let level = level.clamp(0.0, 1.0);
    LANE_WAVE[((level * (LANE_WAVE.len() - 1) as f32).round() as usize).min(LANE_WAVE.len() - 1)]
}

/// Live modulator lane. Periodic shapes draw one phase-locked cycle across the
/// width with a bright head at the current phase. Random shapes scroll the real
/// generated trajectory right-to-left, head at "now" on the right edge, so what
/// the lane shows is exactly what the engine plays.
pub(crate) fn lfo_lane_line(
    route: &LfoRoute,
    beat: f64,
    width: usize,
    active: bool,
) -> Line<'static> {
    let width = width.clamp(6, 80);
    let floor = if active { 0.35 } else { 0.25 };
    let mut spans = Vec::with_capacity(width + 1);
    spans.push(Span::styled(
        format!("  {:<15} ", ""),
        Style::default().fg(Color::Rgb(130, 136, 160)),
    ));

    if route.shape.is_random() {
        let window = f64::from(route.cycle_beats.max(MIN_LFO_CYCLE_BEATS) * RANDOM_LANE_CYCLES);
        for i in 0..width {
            let age = (width - 1 - i) as f64 / width as f64;
            let wave = route.wave_at(beat - age * window) * route.depth_ratio;
            let level = wave * 0.5 + 0.5;
            let brightness = (floor + (i as f32 / (width - 1) as f32) * 0.6).clamp(0.0, 1.0);
            let hue = 300.0 + wave * 25.0;
            spans.push(Span::styled(
                lane_glyph(level),
                Style::default().fg(fluid_hsv(hue, 0.6, brightness)),
            ));
        }
        return Line::from(spans);
    }

    let head = (route.phase_at(beat) * width as f64) as usize % width;
    for i in 0..width {
        let phase = i as f32 / width as f32;
        let wave = route.shape_value_at_phase(phase) * route.depth_ratio;
        let level = wave * 0.5 + 0.5;
        let raw = i.abs_diff(head);
        let wrapped = raw.min(width - raw);
        let falloff = 1.0 - (wrapped as f32 / width as f32) * 2.0;
        let brightness = (floor + falloff.max(0.0) * 0.6).clamp(0.0, 1.0);
        let hue = 300.0 + wave * 25.0;
        spans.push(Span::styled(
            lane_glyph(level),
            Style::default().fg(fluid_hsv(hue, 0.6, brightness)),
        ));
    }
    Line::from(spans)
}

/// Envelope lane: the one-shot AD ramp across one trigger period, with a bright
/// head at the live phase. Uses the same `level_at` math as the engine.
pub(crate) fn env_lane_line(
    route: &EnvelopeRoute,
    ctx: ModContext,
    width: usize,
    active: bool,
) -> Line<'static> {
    let width = width.clamp(6, 80);
    let floor = if active { 0.35 } else { 0.25 };
    let window = f64::from(route.window_beats());
    let head_phase = route.lane_head_phase(ctx);
    let head = ((head_phase * width as f32) as usize).min(width - 1);

    let mut spans = Vec::with_capacity(width + 1);
    spans.push(Span::styled(
        format!("  {:<15} ", ""),
        Style::default().fg(Color::Rgb(130, 136, 160)),
    ));
    for i in 0..width {
        let col_since = (i as f64 / width as f64 * window) as f32;
        let level = route.level_for_lane(col_since) * route.amount.abs();
        let raw = i.abs_diff(head);
        let falloff = 1.0 - (raw as f32 / width as f32) * 2.0;
        let brightness = (floor + falloff.max(0.0) * 0.6).clamp(0.0, 1.0);
        let hue = if route.amount >= 0.0 { 150.0 } else { 15.0 };
        spans.push(Span::styled(
            lane_glyph(level).to_string(),
            Style::default().fg(fluid_hsv(hue, 0.55, brightness)),
        ));
    }
    Line::from(spans)
}

/// Live marker positions on a slider, all as 0..1 bar ratios. `effective` is
/// the summed value the engine plays; the per-source entries are base plus
/// that source alone, drawn as dim ghost diamonds so a diverging cursor is
/// explained at a glance (pink = LFO, green = envelope, amber = macro).
#[derive(Default, Clone, Copy)]
pub(crate) struct SliderMarkers {
    pub(crate) effective: Option<f32>,
    pub(crate) lfo: Option<f32>,
    pub(crate) envelope: Option<f32>,
    pub(crate) macro_: Option<f32>,
    /// Faint reach band (lo, hi ratios) showing the full throw of every
    /// active source while its editor is open — a preview of how far the
    /// effective value could swing, not just where it sits this instant.
    pub(crate) shadow: Option<(f32, f32)>,
}

const EFFECTIVE_MARKER_COLOR: Color = Color::Rgb(235, 245, 255);
const SHADOW_COLOR: Color = Color::Rgb(95, 100, 115);

/// Slider bar spans with ghost diamonds per modulation source, a faint reach
/// band, and one bright diamond at the effective value. Precedence: the
/// effective marker wins overlaps, then ghosts, then the actual filled bar,
/// then the shadow band, then empty track.
fn slider_spans(
    ratio: f32,
    markers: SliderMarkers,
    width: usize,
    style: Style,
) -> Vec<Span<'static>> {
    let filled = (ratio.clamp(0.0, 1.0) * width as f32).round() as usize;
    let cell = |value: Option<f32>| {
        value.map(|v| (v.clamp(0.0, 1.0) * width.saturating_sub(1) as f32).round() as usize)
    };
    let effective = cell(markers.effective);
    let ghosts = [
        (cell(markers.lfo), LFO_PALETTE.idle),
        (cell(markers.envelope), ENV_PALETTE.idle),
        (cell(markers.macro_), MACRO_PALETTE.idle),
    ];
    let shadow_range = markers.shadow.map(|(lo, hi)| {
        let lo = cell(Some(lo)).unwrap_or(0);
        let hi = cell(Some(hi)).unwrap_or(0);
        lo.min(hi)..=lo.max(hi)
    });
    (0..width)
        .map(|i| {
            if Some(i) == effective {
                Span::styled(
                    "◆",
                    Style::default()
                        .fg(EFFECTIVE_MARKER_COLOR)
                        .add_modifier(Modifier::BOLD),
                )
            } else if let Some((_, color)) = ghosts.iter().find(|(pos, _)| *pos == Some(i)) {
                Span::styled("◇", Style::default().fg(*color))
            } else if i < filled {
                Span::styled("█", style)
            } else if shadow_range.as_ref().is_some_and(|r| r.contains(&i)) {
                Span::styled("▒", Style::default().fg(SHADOW_COLOR))
            } else {
                Span::styled("░", style)
            }
        })
        .collect()
}

pub(crate) fn item_ratio(item: &ControlItem) -> f32 {
    let range = item.max - item.min;
    if range.abs() <= f32::EPSILON {
        0.0
    } else {
        let value = match item.kind {
            ControlKind::Discrete => item.value.round(),
            ControlKind::Gain | ControlKind::Continuous | ControlKind::Timing => item.value,
        };
        ((value - item.min) / range).clamp(0.0, 1.0)
    }
}

pub(crate) fn ratio_bar(ratio: f32, width: usize, filled: char, empty: char) -> String {
    let filled_count = (ratio.clamp(0.0, 1.0) * width as f32).round() as usize;
    let filled_count = filled_count.min(width);
    let empty_count = width.saturating_sub(filled_count);
    format!(
        "{}{}",
        filled.to_string().repeat(filled_count),
        empty.to_string().repeat(empty_count)
    )
}