audium 2.0.0

A terminal music app
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
use std::time::Duration;

use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

use ratatui::{
    Frame,
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Paragraph},
};

// -- Theme ------------------------------------------------------------------

/// All semantic color roles used across the UI.
/// Passed by reference to every render function that needs colors.
#[derive(Debug, Clone)]
pub struct Theme {
    pub name: &'static str,
    pub bg: Color,
    pub panel_bg: Color,
    pub sidebar_bg: Color,
    pub accent: Color,
    pub subtle: Color,
    pub text: Color,
    pub text_dim: Color,
    pub now_playing: Color,
    pub danger: Color,
    pub dir_col: Color,
    pub vol_empty: Color,
    pub transparent: bool,
    /// When set, render UI glyphs as ASCII (for limited terminals / a tty).
    /// Only the console fallback theme enables this.
    pub ascii: bool,
}

// -- Glyphs ------------------------------------------------------------------

/// Semantic UI glyphs, so a tty gets ASCII instead of unrenderable Unicode.
/// [`Theme::glyphs`] picks the table; no render site hard-codes a literal.
#[derive(Debug)]
pub struct Glyphs {
    /// Vertical rule separating items in a status cluster.
    pub divider: &'static str,
    /// 3-column list prefix marking the selected / active row.
    pub marker: &'static str,
    /// Left / right value-cycle arrows in the settings rows.
    pub arrow_left: &'static str,
    pub arrow_right: &'static str,
    /// Horizontal bar fill / empty (progress, thumb, settings volume).
    pub bar_fill: &'static str,
    pub bar_empty: &'static str,
    /// Padded metadata separator (e.g. `artist - album`).
    pub sep: &'static str,
    /// Music note (lyrics title, file-picker audio entries).
    pub note: &'static str,
    /// Directory marker in the file picker's title.
    pub folder: &'static str,
    /// Playback-speed multiplier sign.
    pub times: &'static str,
    /// Horizontal rule fill, used under the track table's header row.
    pub rule: &'static str,
    /// Scrubber: the track line, and the head riding along it.
    pub track: &'static str,
    pub thumb: &'static str,
    /// Frames of the equaliser on the playing row, cycled by elapsed time: it
    /// shows playback is live without the cost of a real animation.
    pub eq: [&'static str; 4],
    /// The same equaliser at rest, for the track that is loaded but paused.
    pub eq_idle: &'static str,
}

static UNICODE_GLYPHS: Glyphs = Glyphs {
    divider: "",
    marker: "",
    arrow_left: "",
    arrow_right: "",
    bar_fill: "",
    bar_empty: "",
    sep: "  ·  ",
    note: "",
    folder: "📁",
    times: "×",
    rule: "",
    track: "",
    thumb: "",
    eq: ["▁▃▅", "▃▅▂", "▅▂▆", "▂▆▃"],
    eq_idle: "▁▁▁",
};

static ASCII_GLYPHS: Glyphs = Glyphs {
    divider: "|",
    marker: ">  ",
    arrow_left: "<",
    arrow_right: ">",
    bar_fill: "#",
    bar_empty: "-",
    sep: "  -  ",
    note: "*",
    folder: "[/]",
    times: "x",
    rule: "-",
    track: "=",
    thumb: "O",
    eq: [".oO", "oO.", "O.o", ".Oo"],
    eq_idle: "...",
};

impl Theme {
    /// The glyph table to render with: ASCII on limited terminals.
    pub const fn glyphs(&self) -> &'static Glyphs {
        if self.ascii {
            &ASCII_GLYPHS
        } else {
            &UNICODE_GLYPHS
        }
    }

    fn maybe_color(&self, color: Color) -> Option<Color> {
        (!self.transparent).then_some(color)
    }

    fn apply_color(&self, style: Style, color: Color) -> Style {
        self.maybe_color(color).map_or(style, |c| style.bg(c))
    }

    pub fn apply_bg(&self, style: Style) -> Style {
        self.apply_color(style, self.bg)
    }

    pub fn apply_panel_bg(&self, style: Style) -> Style {
        self.apply_color(style, self.panel_bg)
    }

    pub fn apply_sidebar_bg(&self, style: Style) -> Style {
        self.apply_color(style, self.sidebar_bg)
    }

    /// Style marking the selected row of a list.
    ///
    /// The RGB themes tint the background, legible because `panel_bg` sits a
    /// shade off `bg`. The console themes have no shade to spend: a mid-tone
    /// band wrecks contrast from both sides, and a brighter foreground alone
    /// is only 2.3:1 against an unselected row. Reverse video sidesteps both
    /// by swapping fg and bg, so the row is a solid block in any palette.
    pub fn selection_style(&self) -> Style {
        if self.ascii {
            Style::default().add_modifier(Modifier::REVERSED)
        } else {
            Style::default()
                .fg(self.text)
                .bg(self.panel_bg)
                .add_modifier(Modifier::BOLD)
        }
    }
}

// -- Built-in themes --------------------------------------------------------

pub fn themes() -> &'static [Theme] {
    &THEMES
}

pub fn theme_by_name(name: &str) -> &'static Theme {
    THEMES.iter().find(|t| t.name == name).unwrap_or(&THEMES[0])
}

/// The 16-color fallbacks used when truecolor is not in effect.
///
/// Tuned against the Linux console's default palette (the kernel exposes it at
/// `/sys/module/vt/parameters/default_{red,grn,blu}`), which decides what may
/// appear on what: on black, blue is 1.6:1 and darkgray 2.8:1; on white every
/// bright variant collapses. So the dark and light themes share almost no
/// colors, and both keep `panel_bg` equal to `bg`, leaving panels flat and the
/// selection to [`Theme::selection_style`].
///
/// Kept out of `THEMES` so they never appear in the truecolor theme cycler.
pub fn console_themes() -> &'static [Theme] {
    &CONSOLE_THEMES
}

/// Looks up a console theme by name, falling back to the dark one.
pub fn console_theme_by_name(name: &str) -> &'static Theme {
    CONSOLE_THEMES
        .iter()
        .find(|t| t.name == name)
        .unwrap_or(&CONSOLE_THEMES[0])
}

static CONSOLE_THEMES: [Theme; 2] = [
    // "native": inherits the terminal's own background and picks foregrounds
    // for contrast against it, so the UI blends in rather than painting over.
    // There is no legible third neutral above black (darkgray reads as black
    // on a tty), so dim text and hints share one step below white and the
    // bar's remainder is told apart by its glyph, not by being dimmer.
    Theme {
        name: "native",
        bg: Color::Reset,
        panel_bg: Color::Reset,
        sidebar_bg: Color::Reset,
        accent: Color::LightCyan,       // 17.1:1
        subtle: Color::Gray,            //  9.0:1
        text: Color::White,             // 21.0:1
        text_dim: Color::Gray,          //  9.0:1
        now_playing: Color::LightGreen, // 15.8:1
        danger: Color::LightRed,        //  6.7:1
        dir_col: Color::LightYellow,    // 19.7:1
        vol_empty: Color::Gray,         //  9.0:1; darkgray reads as black on a tty
        transparent: false,
        ascii: true,
    },
    // "paper": paints its own white background instead of inheriting, so it is
    // ink-on-paper even on a black tty, where inheriting would put black on
    // black. Only the dim ANSI variants survive against white.
    Theme {
        name: "paper",
        bg: Color::White,
        panel_bg: Color::White,
        sidebar_bg: Color::White,
        accent: Color::Blue,         // 13.3:1
        subtle: Color::DarkGray,     //  7.5:1
        text: Color::Black,          // 21.0:1
        text_dim: Color::DarkGray,   //  7.5:1
        now_playing: Color::Magenta, //  6.4:1 (green would be 3.1:1 here)
        danger: Color::Red,          //  7.8:1
        dir_col: Color::Yellow,      //  5.2:1 (renders as brown)
        vol_empty: Color::DarkGray,  //  7.5:1; gray on white is only 2.3:1
        transparent: false,
        ascii: true,
    },
];

static THEMES: [Theme; 15] = [
    Theme {
        name: "dark",
        bg: Color::Rgb(18, 18, 18),
        panel_bg: Color::Rgb(24, 24, 24),
        sidebar_bg: Color::Rgb(18, 18, 18),
        accent: Color::Rgb(100, 180, 255),
        subtle: Color::Rgb(80, 80, 80),
        text: Color::White,
        text_dim: Color::Rgb(179, 179, 179),
        now_playing: Color::Rgb(100, 180, 255),
        danger: Color::Rgb(255, 80, 80),
        dir_col: Color::Rgb(255, 210, 100),
        vol_empty: Color::Rgb(50, 50, 50),
        transparent: false,
        ascii: false,
    },
    Theme {
        name: "light",
        bg: Color::Rgb(245, 245, 245),
        panel_bg: Color::Rgb(235, 235, 235),
        sidebar_bg: Color::Rgb(240, 240, 240),
        accent: Color::Rgb(0, 100, 210),
        subtle: Color::Rgb(160, 160, 160),
        text: Color::Rgb(20, 20, 20),
        text_dim: Color::Rgb(90, 90, 90),
        now_playing: Color::Rgb(0, 100, 210),
        danger: Color::Rgb(200, 30, 30),
        dir_col: Color::Rgb(180, 100, 0),
        vol_empty: Color::Rgb(200, 200, 200),
        transparent: false,
        ascii: false,
    },
    Theme {
        name: "nord",
        bg: Color::Rgb(46, 52, 64),
        panel_bg: Color::Rgb(59, 66, 82),
        sidebar_bg: Color::Rgb(46, 52, 64),
        accent: Color::Rgb(136, 192, 208),
        subtle: Color::Rgb(76, 86, 106),
        text: Color::Rgb(236, 239, 244),
        text_dim: Color::Rgb(216, 222, 233),
        now_playing: Color::Rgb(163, 190, 140),
        danger: Color::Rgb(191, 97, 106),
        dir_col: Color::Rgb(235, 203, 139),
        vol_empty: Color::Rgb(67, 76, 94),
        transparent: false,
        ascii: false,
    },
    Theme {
        name: "gruvbox",
        bg: Color::Rgb(40, 40, 40),
        panel_bg: Color::Rgb(50, 48, 47),
        sidebar_bg: Color::Rgb(40, 40, 40),
        accent: Color::Rgb(250, 189, 47),
        subtle: Color::Rgb(102, 92, 84),
        text: Color::Rgb(235, 219, 178),
        text_dim: Color::Rgb(189, 174, 147),
        now_playing: Color::Rgb(184, 187, 38),
        danger: Color::Rgb(251, 73, 52),
        dir_col: Color::Rgb(214, 93, 14),
        vol_empty: Color::Rgb(60, 56, 54),
        transparent: false,
        ascii: false,
    },
    Theme {
        name: "gruvbox_light",
        bg: Color::Rgb(251, 241, 199),
        panel_bg: Color::Rgb(242, 229, 188),
        sidebar_bg: Color::Rgb(251, 241, 199),
        accent: Color::Rgb(181, 118, 20),
        subtle: Color::Rgb(168, 153, 132),
        text: Color::Rgb(60, 56, 54),
        text_dim: Color::Rgb(102, 92, 84),
        now_playing: Color::Rgb(121, 116, 14),
        danger: Color::Rgb(204, 36, 29),
        dir_col: Color::Rgb(214, 93, 14),
        vol_empty: Color::Rgb(213, 196, 161),
        transparent: false,
        ascii: false,
    },
    Theme {
        name: "rosepine",
        bg: Color::Rgb(25, 23, 36),
        panel_bg: Color::Rgb(31, 29, 46),
        sidebar_bg: Color::Rgb(25, 23, 36),
        accent: Color::Rgb(196, 167, 231),
        subtle: Color::Rgb(110, 106, 134),
        text: Color::Rgb(224, 222, 244),
        text_dim: Color::Rgb(144, 140, 170),
        now_playing: Color::Rgb(235, 188, 186),
        danger: Color::Rgb(235, 111, 146),
        dir_col: Color::Rgb(246, 193, 119),
        vol_empty: Color::Rgb(38, 35, 58),
        transparent: false,
        ascii: false,
    },
    Theme {
        name: "rosepine_dawn",
        bg: Color::Rgb(250, 244, 237),
        panel_bg: Color::Rgb(255, 250, 243),
        sidebar_bg: Color::Rgb(250, 244, 237),
        accent: Color::Rgb(144, 122, 169),
        subtle: Color::Rgb(152, 147, 165),
        text: Color::Rgb(87, 82, 121),
        text_dim: Color::Rgb(121, 117, 147),
        now_playing: Color::Rgb(180, 99, 122),
        danger: Color::Rgb(180, 99, 122),
        dir_col: Color::Rgb(234, 157, 52),
        vol_empty: Color::Rgb(223, 218, 217),
        transparent: false,
        ascii: false,
    },
    Theme {
        name: "catppuccin",
        bg: Color::Rgb(30, 30, 46),
        panel_bg: Color::Rgb(36, 36, 54),
        sidebar_bg: Color::Rgb(30, 30, 46),
        accent: Color::Rgb(137, 180, 250),
        subtle: Color::Rgb(88, 91, 112),
        text: Color::Rgb(205, 214, 244),
        text_dim: Color::Rgb(166, 173, 200),
        now_playing: Color::Rgb(166, 227, 161),
        danger: Color::Rgb(243, 139, 168),
        dir_col: Color::Rgb(249, 226, 175),
        vol_empty: Color::Rgb(49, 50, 68),
        transparent: false,
        ascii: false,
    },
    Theme {
        name: "catppuccin_latte",
        bg: Color::Rgb(239, 241, 245),
        panel_bg: Color::Rgb(230, 233, 239),
        sidebar_bg: Color::Rgb(239, 241, 245),
        accent: Color::Rgb(30, 102, 245),
        subtle: Color::Rgb(172, 176, 190),
        text: Color::Rgb(76, 79, 105),
        text_dim: Color::Rgb(108, 111, 133),
        now_playing: Color::Rgb(64, 160, 43),
        danger: Color::Rgb(210, 15, 57),
        dir_col: Color::Rgb(223, 142, 29),
        vol_empty: Color::Rgb(204, 208, 218),
        transparent: false,
        ascii: false,
    },
    Theme {
        name: "dracula",
        bg: Color::Rgb(40, 42, 54),
        panel_bg: Color::Rgb(48, 50, 65),
        sidebar_bg: Color::Rgb(40, 42, 54),
        accent: Color::Rgb(189, 147, 249),
        subtle: Color::Rgb(98, 114, 164),
        text: Color::Rgb(248, 248, 242),
        text_dim: Color::Rgb(191, 192, 190),
        now_playing: Color::Rgb(80, 250, 123),
        danger: Color::Rgb(255, 85, 85),
        dir_col: Color::Rgb(255, 184, 108),
        vol_empty: Color::Rgb(55, 57, 72),
        transparent: false,
        ascii: false,
    },
    Theme {
        name: "tokyo_night",
        bg: Color::Rgb(26, 27, 38),
        panel_bg: Color::Rgb(31, 35, 53),
        sidebar_bg: Color::Rgb(26, 27, 38),
        accent: Color::Rgb(122, 162, 247),
        subtle: Color::Rgb(86, 95, 137),
        text: Color::Rgb(192, 202, 245),
        text_dim: Color::Rgb(169, 177, 214),
        now_playing: Color::Rgb(158, 206, 106),
        danger: Color::Rgb(247, 118, 142),
        dir_col: Color::Rgb(224, 175, 104),
        vol_empty: Color::Rgb(41, 46, 66),
        transparent: false,
        ascii: false,
    },
    Theme {
        name: "solarized_dark",
        bg: Color::Rgb(0, 43, 54),
        panel_bg: Color::Rgb(7, 54, 66),
        sidebar_bg: Color::Rgb(0, 43, 54),
        accent: Color::Rgb(38, 139, 210),
        subtle: Color::Rgb(88, 110, 117),
        text: Color::Rgb(253, 246, 227),
        text_dim: Color::Rgb(147, 161, 161),
        now_playing: Color::Rgb(133, 153, 0),
        danger: Color::Rgb(220, 50, 47),
        dir_col: Color::Rgb(203, 75, 22),
        vol_empty: Color::Rgb(0, 35, 43),
        transparent: false,
        ascii: false,
    },
    Theme {
        name: "solarized_light",
        bg: Color::Rgb(253, 246, 227),
        panel_bg: Color::Rgb(238, 232, 213),
        sidebar_bg: Color::Rgb(253, 246, 227),
        accent: Color::Rgb(38, 139, 210),
        subtle: Color::Rgb(147, 161, 161),
        text: Color::Rgb(0, 43, 54),
        text_dim: Color::Rgb(88, 110, 117),
        now_playing: Color::Rgb(133, 153, 0),
        danger: Color::Rgb(220, 50, 47),
        dir_col: Color::Rgb(203, 75, 22),
        vol_empty: Color::Rgb(210, 203, 186),
        transparent: false,
        ascii: false,
    },
    Theme {
        name: "everforest",
        bg: Color::Rgb(35, 38, 33),
        panel_bg: Color::Rgb(43, 47, 40),
        sidebar_bg: Color::Rgb(35, 38, 33),
        accent: Color::Rgb(131, 192, 146),
        subtle: Color::Rgb(93, 98, 86),
        text: Color::Rgb(211, 198, 170),
        text_dim: Color::Rgb(157, 151, 132),
        now_playing: Color::Rgb(131, 192, 146),
        danger: Color::Rgb(230, 126, 128),
        dir_col: Color::Rgb(230, 192, 115),
        vol_empty: Color::Rgb(53, 57, 49),
        transparent: false,
        ascii: false,
    },
    Theme {
        name: "kanagawa",
        bg: Color::Rgb(22, 22, 29),
        panel_bg: Color::Rgb(31, 31, 40),
        sidebar_bg: Color::Rgb(22, 22, 29),
        accent: Color::Rgb(126, 156, 216),
        subtle: Color::Rgb(84, 84, 109),
        text: Color::Rgb(220, 215, 186),
        text_dim: Color::Rgb(150, 147, 125),
        now_playing: Color::Rgb(118, 148, 106),
        danger: Color::Rgb(195, 95, 95),
        dir_col: Color::Rgb(196, 154, 105),
        vol_empty: Color::Rgb(38, 38, 50),
        transparent: false,
        ascii: false,
    },
];

// -- Shared widget helpers --------------------------------------------------

/// Renders `value` with a vi-style block cursor: reverse video *covering* the
/// character at byte offset `cursor`, not an extra glyph wedged between two.
/// `REVERSED` is a plain terminal attribute, so this works on a tty too.
pub fn cursor_spans(value: &str, cursor: usize, theme: &Theme) -> Vec<Span<'static>> {
    let text = Style::default().fg(theme.text);
    let block = Style::default()
        .fg(theme.accent)
        .add_modifier(Modifier::REVERSED);
    let before = &value[..cursor];
    let after = &value[cursor..];
    let (under, rest) = after.chars().next().map_or_else(
        || (" ".to_string(), ""),
        |c| (c.to_string(), &after[c.len_utf8()..]),
    );
    vec![
        Span::styled(before.to_string(), text),
        Span::styled(under, block),
        Span::styled(rest.to_string(), text),
    ]
}

/// Like [`cursor_spans`], but scrolls a `width`-cell window over values too
/// long for the field, the way a shell prompt does. Without it a long name
/// runs past the right edge and you type blind.
pub fn cursor_spans_windowed(
    value: &str,
    cursor: usize,
    width: usize,
    theme: &Theme,
) -> Vec<Span<'static>> {
    let start = h_window_start(value, cursor, width);
    let window = h_window(value, start, width);

    // char index -> byte offset within the window
    let cur = value[..cursor].chars().count();
    let window_cursor = window
        .char_indices()
        .nth(cur.saturating_sub(start))
        .map_or(window.len(), |(i, _)| i);

    cursor_spans(&window, window_cursor, theme)
}

/// First visible character index of a `width`-*column* window holding the
/// cursor.
///
/// Column-based, not char-based: `width` wide characters would be twice
/// `width` cells and clip the cursor off the right edge. Exposed so a
/// multi-line editor can offset every row alike, since scrolling only the
/// cursor's row would knock it out of alignment with its neighbours.
pub fn h_window_start(value: &str, cursor: usize, width: usize) -> usize {
    if width == 0 {
        return 0;
    }
    let chars: Vec<char> = value.chars().collect();
    // plus the one cell the block cursor needs past the end
    let total: usize = chars.iter().map(|c| char_cols(*c)).sum::<usize>() + 1;
    if total <= width {
        return 0;
    }
    let cur = value[..cursor].chars().count();
    // walk back from the cursor until one more character would exceed `width`
    let cursor_cell = chars.get(cur).map_or(1, |c| char_cols(*c));
    let mut used = cursor_cell;
    let mut start = cur;
    while start > 0 {
        let w = char_cols(chars[start - 1]);
        if used + w > width {
            break;
        }
        used += w;
        start -= 1;
    }
    start
}

/// A slice of `line` starting `start` characters in and at most `width`
/// *columns* wide, stopping before a wide character that would straddle the
/// edge.
pub fn h_window(line: &str, start: usize, width: usize) -> String {
    let mut out = String::new();
    let mut used = 0;
    for c in line.chars().skip(start) {
        let w = char_cols(c);
        if used + w > width {
            break;
        }
        out.push(c);
        used += w;
    }
    out
}

/// Display columns of a single character (0 for combining marks, 2 for wide).
fn char_cols(c: char) -> usize {
    UnicodeWidthChar::width(c).unwrap_or(0)
}

/// Centred two-line prompt for an empty panel: what is missing, then the key
/// that fixes it. Shared so every empty panel reads the same way.
pub fn render_empty_state(
    frame: &mut Frame<'_>,
    area: Rect,
    headline: &str,
    key: &str,
    action: &str,
    t: &Theme,
) {
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Min(0),
            Constraint::Length(1), // headline
            Constraint::Length(1), // "press <key> to ..."
            Constraint::Min(0),
        ])
        .split(area);

    frame.render_widget(
        Paragraph::new(Span::styled(
            headline.to_string(),
            Style::default().fg(t.text_dim),
        ))
        .alignment(Alignment::Center),
        rows[1],
    );
    frame.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled("press ", Style::default().fg(t.subtle)),
            Span::styled(key.to_string(), Style::default().fg(t.accent)),
            Span::styled(format!(" {action}"), Style::default().fg(t.subtle)),
        ]))
        .alignment(Alignment::Center),
        rows[2],
    );
}

/// Width of the index column, and the gap between every column.
pub const NUM_W: usize = 3;
const GAP: usize = 2;
pub const GAP_S: &str = "  ";

/// Column widths for one tracklist row.
///
/// A library reads as a table, not as `artist - title` run together. Narrow
/// panels drop columns from the right rather than squeezing all three into
/// illegibility, so the title always keeps a usable width.
pub struct Columns {
    title: usize,
    artist: usize,
    album: usize,
    time: usize,
}

impl Columns {
    const MIN_TITLE: usize = 16;
    const MIN_META: usize = 10;
    /// Enough for `mm:ss` up to 99 minutes; longer runs simply widen the cell.
    const TIME_W: usize = 5;

    pub const fn for_width(width: usize) -> Self {
        let body = width.saturating_sub(NUM_W + GAP);
        let meta2 = (GAP + Self::MIN_META) * 2;
        let time = GAP + Self::TIME_W;

        if body >= Self::MIN_TITLE + meta2 + time {
            // roughly 4:3:3. Giving the title every spare column would leave
            // it sprawling on a wide terminal, the metadata stranded off to
            // the right; a proportional split holds them together.
            let rest = body - time - GAP * 2;
            let artist = rest * 3 / 10;
            let album = rest * 3 / 10;
            Self {
                title: rest - artist - album,
                artist,
                album,
                time: Self::TIME_W,
            }
        } else if body >= Self::MIN_TITLE + GAP + Self::MIN_META + time {
            let rest = body - time;
            let title = rest * 3 / 5;
            Self {
                title,
                artist: rest - title - GAP,
                album: 0,
                time: Self::TIME_W,
            }
        } else if body >= Self::MIN_TITLE + GAP + Self::MIN_META {
            let title = body * 3 / 5;
            Self {
                title,
                artist: body - title - GAP,
                album: 0,
                time: 0,
            }
        } else {
            Self {
                title: body,
                artist: 0,
                album: 0,
                time: 0,
            }
        }
    }

    /// One span per visible column, each padded to its width so the columns
    /// line up whatever the contents are.
    pub fn cells(&self, title: &str, artist: &str, album: &str, time: &str) -> Vec<Span<'static>> {
        let mut out = vec![Span::raw(pad(title, self.title))];
        if self.artist > 0 {
            out.push(Span::raw(format!("{GAP_S}{}", pad(artist, self.artist))));
        }
        if self.album > 0 {
            out.push(Span::raw(format!("{GAP_S}{}", pad(album, self.album))));
        }
        if self.time > 0 {
            // Right-aligned: durations line up on the colon.
            out.push(Span::raw(format!(
                "{GAP_S}{time:>w$}",
                w = self.time.max(str_width(time))
            )));
        }
        out
    }
}

/// Truncates to `width` columns and pads back out to it, so a short value
/// still occupies its whole column and the next one starts where expected.
fn pad(s: &str, width: usize) -> String {
    let s = truncate(s, width);
    let fill = width.saturating_sub(str_width(&s));
    format!("{s}{blank:fill$}", blank = "")
}

/// The gutter cell for a track row: a live equaliser on the playing track,
/// blank on every other.  Shared so the library and the queue mark the current
/// track the same way.
pub fn row_marker(is_playing: bool, paused: bool, elapsed: Duration, t: &Theme) -> String {
    if !is_playing {
        return String::new();
    }
    let g = t.glyphs();
    if paused {
        return g.eq_idle.to_string();
    }
    let frame = (elapsed.as_millis() / 250) as usize % g.eq.len();
    g.eq[frame].to_string()
}

/// Builds a consistently styled panel block.
pub fn styled_block<'a>(title: &'a str, focused: bool, theme: &Theme) -> Block<'a> {
    Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_type(BorderType::Plain)
        .border_style(Style::default().fg(if focused { theme.accent } else { theme.subtle }))
        .title_style(
            Style::default()
                .fg(if focused {
                    theme.accent
                } else {
                    theme.text_dim
                })
                .add_modifier(Modifier::BOLD),
        )
}

/// Display width of `s` in terminal columns.
///
/// A CJK ideograph or a wide emoji occupies two cells but one `char`, so every
/// layout measurement uses this rather than `chars().count()`; counting chars
/// makes those rows overflow and push later columns off the edge.
pub fn str_width(s: &str) -> usize {
    UnicodeWidthStr::width(s)
}

/// Truncates a string to `max` display columns, appending `~` if it had to cut.
///
/// Width-aware on both ends: it stops before a wide character that would
/// straddle the limit, and never returns more than `max` columns even when the
/// final kept character is two cells wide.
pub fn truncate(s: &str, max: usize) -> String {
    if str_width(s) <= max {
        return s.to_string();
    }
    // At max == 0 there is not even room for the ellipsis, and returning "~"
    // would overflow the caller's field by one cell.
    if max == 0 {
        return String::new();
    }
    // Keep whole characters until one more would leave no room for the `~`.
    let mut out = String::new();
    let mut used = 0;
    for c in s.chars() {
        let w = UnicodeWidthChar::width(c).unwrap_or(0);
        if used + w > max - 1 {
            break;
        }
        out.push(c);
        used += w;
    }
    out.push('~');
    out
}

pub fn format_duration(secs: u64) -> String {
    let m = secs / 60;
    let s = secs % 60;
    format!("{m}:{s:02}")
}