sigye 0.4.2

A beautiful terminal clock with ASCII art fonts
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
//! sigye - A terminal clock application with configurable fonts.

mod context;
mod mode;
mod modes;
mod render;
mod settings;
mod system_metrics;
mod weather;

use std::time::{Duration, Instant};

use clap::Parser;
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::{
    DefaultTerminal, Frame,
    layout::Alignment,
    style::{Color, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Paragraph},
};
use sigye_config::Config;
use sigye_core::{BackgroundStyle, ColorTheme, DisplayMode};
use sigye_fonts::FontRegistry;

use context::RenderContext;
use mode::Mode;
use modes::clock::ClockMode;
use modes::pomodoro::PomodoroMode;
use modes::stopwatch::StopwatchMode;
use modes::timer::TimerMode;
use modes::world_clock::WorldClockMode;
use settings::SettingsDialog;
use sigye_background::BackgroundState;
use system_metrics::SystemMonitor;
use weather::WeatherMonitor;

/// A beautiful terminal clock with ASCII art fonts, animations, and backgrounds.
#[derive(Parser)]
#[command(name = "sigye", version, about)]
struct Cli {
    /// Start in screensaver mode (fullscreen, no UI chrome)
    #[arg(long)]
    screensaver: bool,

    /// Start in demo mode (auto-cycle themes and backgrounds)
    #[arg(long)]
    demo: bool,

    /// Set the font name
    #[arg(long)]
    font: Option<String>,

    /// Set the color theme
    #[arg(long)]
    theme: Option<String>,

    /// Set the background style
    #[arg(long = "bg", alias = "background")]
    background: Option<String>,

    /// Set the display mode (clock, pomodoro, timer, stopwatch, worldclock)
    #[arg(long)]
    mode: Option<String>,

    /// Add a world clock timezone (e.g., "Tokyo=Asia/Tokyo"). Can be repeated.
    #[arg(long = "tz", value_name = "LABEL=TIMEZONE")]
    timezones: Vec<String>,

    /// Shell command to execute on timer/pomodoro completion
    #[arg(long)]
    on_complete: Option<String>,

    /// Auto-start the active timer mode (pomodoro, timer, or stopwatch)
    #[arg(long)]
    start: bool,

    /// Start in pomodoro mode and auto-start
    #[arg(long)]
    pomo: bool,

    /// Start in stopwatch mode and auto-start
    #[arg(long)]
    sw: bool,

    /// Set timer duration in minutes and auto-start timer mode
    #[arg(long = "timer", value_name = "MINS")]
    timer_mins: Option<u32>,

    /// Print time once and exit (no TUI)
    #[arg(long)]
    once: bool,

    /// Output format for --once mode (human, unix, iso, hex)
    #[arg(long, default_value = "human")]
    format: String,
}

fn main() -> color_eyre::Result<()> {
    color_eyre::install()?;
    let cli = Cli::parse();

    // Handle --once mode: print and exit without TUI
    if cli.once {
        let now = chrono::Local::now();
        let output = match cli.format.as_str() {
            "unix" | "timestamp" | "epoch" => now.timestamp().to_string(),
            "iso" | "iso8601" => now.format("%Y-%m-%dT%H:%M:%S%:z").to_string(),
            "hex" => {
                let h = now.format("%H").to_string().parse::<u32>().unwrap_or(0);
                let m = now.format("%M").to_string().parse::<u32>().unwrap_or(0);
                let s = now.format("%S").to_string().parse::<u32>().unwrap_or(0);
                format!("{h:02X}:{m:02X}:{s:02X}")
            }
            _ => {
                // Default human-readable
                now.format("%Y-%m-%d %H:%M:%S").to_string()
            }
        };
        println!("{output}");
        return Ok(());
    }

    let terminal = ratatui::init();
    let result = App::new_with_cli(cli).run(terminal);
    ratatui::restore();
    result
}

/// The main application which holds the state and logic of the application.
pub struct App {
    /// Is the application running?
    running: bool,
    /// Shared rendering context for all modes.
    ctx: RenderContext,
    /// All display mode implementations.
    modes: Vec<Box<dyn Mode>>,
    /// Index of the currently active mode.
    active_mode_index: usize,
    /// Settings dialog state.
    settings_dialog: SettingsDialog,
    /// Background animation state.
    background_state: BackgroundState,
    /// System monitor for reactive backgrounds (lazy initialized).
    system_monitor: Option<SystemMonitor>,
    /// Weather monitor for dynamic weather background (lazy initialized).
    weather_monitor: Option<WeatherMonitor>,
    /// Whether help overlay is visible.
    show_help: bool,
    /// Whether demo mode is active (auto-cycle).
    demo_mode: bool,
    /// Timer for demo mode theme cycling.
    demo_theme_cycle: Instant,
    /// Timer for demo mode background cycling.
    demo_bg_cycle: Instant,
    /// Timer for demo mode font cycling.
    demo_font_cycle: Instant,
}

impl App {
    /// Construct a new instance of [`App`].
    pub fn new() -> Self {
        // Load configuration
        let config = Config::load();

        // Initialize font registry with bundled fonts
        let mut font_registry = FontRegistry::new();

        // Load custom fonts from config directory
        font_registry.load_custom_fonts(&Config::fonts_dir());

        // Get list of available fonts for settings dialog
        let available_fonts: Vec<String> = font_registry
            .list_fonts()
            .into_iter()
            .map(String::from)
            .collect();

        // Create settings dialog
        let settings_dialog = SettingsDialog::new(available_fonts);

        // Initialize system monitor if reactive background is selected
        let system_monitor = if config.background_style.is_reactive() {
            let monitor = SystemMonitor::new();
            monitor.start();
            Some(monitor)
        } else {
            None
        };

        // Initialize weather monitor if weather background is selected
        let weather_monitor = if config.background_style.requires_weather() {
            let monitor = WeatherMonitor::new(config.weather_location.clone());
            monitor.start();
            Some(monitor)
        } else {
            None
        };

        let on_complete_command = config.on_complete.clone();

        // Build RenderContext from config
        let ctx = RenderContext {
            time_format: config.time_format,
            color_theme: config.color_theme,
            animation_style: config.animation_style,
            animation_speed: config.animation_speed,
            colon_blink: config.colon_blink,
            show_seconds: config.show_seconds,
            background_style: config.background_style,
            current_font: config.font_name.clone(),
            font_registry,
            config,
            animation_start: Instant::now(),
            flash_intensity: 0.0,
            flash_start: None,
            screensaver_mode: false,
            on_complete_command,
            desktop_notifications: false,
            sunrise_sunset: None,
        };

        // Create all mode structs
        let modes: Vec<Box<dyn Mode>> = vec![
            Box::new(ClockMode::new()),
            Box::new(PomodoroMode::new(
                ctx.config.pomodoro_work_mins,
                ctx.config.pomodoro_sessions_completed,
                ctx.config.pomodoro_total_focus_mins,
            )),
            Box::new(TimerMode::new(ctx.config.timer_duration_mins)),
            Box::new(StopwatchMode::new()),
            Box::new(WorldClockMode::new(&ctx.config.world_clock_zones)),
        ];

        Self {
            running: false,
            ctx,
            modes,
            active_mode_index: 0,
            settings_dialog,
            background_state: BackgroundState::new(),
            system_monitor,
            weather_monitor,
            show_help: false,
            demo_mode: false,
            demo_theme_cycle: Instant::now(),
            demo_bg_cycle: Instant::now(),
            demo_font_cycle: Instant::now(),
        }
    }

    /// Construct a new instance with CLI overrides applied.
    fn new_with_cli(cli: Cli) -> Self {
        let mut app = Self::new();

        if let Some(font_name) = cli.font {
            let fonts = app.ctx.font_registry.list_fonts();
            if let Some(matched) = fonts.iter().find(|f| f.eq_ignore_ascii_case(&font_name)) {
                app.ctx.current_font = matched.to_string();
            } else {
                app.ctx.current_font = font_name;
            }
        }

        if let Some(theme_str) = cli.theme
            && let Some(theme) = parse_color_theme(&theme_str)
        {
            app.ctx.color_theme = theme;
        }

        if let Some(bg_str) = cli.background
            && let Some(bg) = parse_background_style(&bg_str)
        {
            app.ctx.background_style = bg;
            app.update_background_monitors();
        }

        if let Some(mode_str) = cli.mode
            && let Some(mode) = parse_display_mode(&mode_str)
        {
            // Find the matching mode index
            if let Some(idx) = app.modes.iter().position(|m| m.display_mode() == mode) {
                app.active_mode_index = idx;
            }
        }

        if !cli.timezones.is_empty() {
            app.ctx.config.world_clock_zones = cli.timezones;
            // Update the WorldClockMode entries via downcast
            for m in app.modes.iter_mut() {
                if let Some(wc) = m.as_any_mut().downcast_mut::<WorldClockMode>() {
                    wc.update_entries(&app.ctx.config.world_clock_zones);
                    break;
                }
            }
        }

        if cli.on_complete.is_some() {
            app.ctx.on_complete_command = cli.on_complete;
        }

        app.ctx.screensaver_mode = cli.screensaver;
        app.ctx.desktop_notifications = app.ctx.config.desktop_notifications;
        app.demo_mode = cli.demo;

        // In screensaver mode with no background, default to Aurora
        if app.ctx.screensaver_mode && app.ctx.background_style == BackgroundStyle::None {
            app.ctx.background_style = BackgroundStyle::Aurora;
            app.update_background_monitors();
        }

        // Quick-start shortcuts
        if cli.pomo
            && let Some(idx) = app
                .modes
                .iter()
                .position(|m| m.display_mode() == DisplayMode::Pomodoro)
        {
            app.active_mode_index = idx;
        }
        if cli.sw
            && let Some(idx) = app
                .modes
                .iter()
                .position(|m| m.display_mode() == DisplayMode::Stopwatch)
        {
            app.active_mode_index = idx;
        }
        if let Some(mins) = cli.timer_mins
            && let Some(idx) = app
                .modes
                .iter()
                .position(|m| m.display_mode() == DisplayMode::Timer)
        {
            app.active_mode_index = idx;
            if let Some(tm) = app.modes[idx].as_any_mut().downcast_mut::<TimerMode>() {
                tm.sync_duration(mins);
            }
        }

        // Auto-start if any quick-start flag is set
        let auto_start = cli.start || cli.pomo || cli.sw || cli.timer_mins.is_some();
        if auto_start {
            let idx = app.active_mode_index;
            let mode = &mut app.modes[idx];
            if let Some(pm) = mode.as_any_mut().downcast_mut::<PomodoroMode>() {
                pm.toggle();
            } else if let Some(tm) = mode.as_any_mut().downcast_mut::<TimerMode>() {
                tm.toggle();
            } else if let Some(sw) = mode.as_any_mut().downcast_mut::<StopwatchMode>() {
                sw.toggle();
            }
        }

        app
    }

    /// Run the application's main loop.
    pub fn run(mut self, mut terminal: DefaultTerminal) -> color_eyre::Result<()> {
        self.running = true;
        while self.running {
            terminal.draw(|frame| self.render(frame))?;
            self.handle_crossterm_events()?;
        }
        Ok(())
    }

    /// Renders the user interface.
    fn render(&mut self, frame: &mut Frame) {
        // Demo mode auto-cycling
        if self.demo_mode {
            if self.demo_theme_cycle.elapsed() >= Duration::from_secs(5) {
                self.ctx.color_theme = self.ctx.color_theme.next();
                self.demo_theme_cycle = Instant::now();
            }
            if self.demo_bg_cycle.elapsed() >= Duration::from_secs(15) {
                self.ctx.background_style = self.ctx.background_style.next();
                self.update_background_monitors();
                self.demo_bg_cycle = Instant::now();
            }
            if self.demo_font_cycle.elapsed() >= Duration::from_secs(30) {
                let fonts = self.ctx.font_registry.list_fonts();
                let current_idx = fonts
                    .iter()
                    .position(|f| f == &self.ctx.current_font)
                    .unwrap_or(0);
                let next_idx = (current_idx + 1) % fonts.len();
                self.ctx.current_font = fonts[next_idx].to_string();
                self.demo_font_cycle = Instant::now();
            }
        }

        // Get metrics for reactive backgrounds
        let elapsed_ms = self.ctx.elapsed_ms();
        let metrics = self.system_monitor.as_ref().map(|m| m.get_metrics());

        // Resolve weather background to actual style
        let effective_background = if self.ctx.background_style == BackgroundStyle::Weather {
            self.weather_monitor
                .as_ref()
                .map(|m| m.get_background())
                .unwrap_or(BackgroundStyle::Starfield)
        } else {
            self.ctx.background_style
        };

        // Render background first (behind everything else)
        self.background_state.render(
            frame,
            effective_background,
            elapsed_ms,
            self.ctx.animation_speed,
            metrics.as_ref(),
        );

        // Update sunrise/sunset from weather monitor
        self.ctx.sunrise_sunset = self
            .weather_monitor
            .as_ref()
            .and_then(|m| m.get_sunrise_sunset());

        // Dispatch to active mode: update then render
        let mode = &mut self.modes[self.active_mode_index];
        mode.update(&mut self.ctx);
        mode.render(frame, &self.ctx);

        // Render settings dialog if visible
        let color = self.ctx.color();
        let area = frame.area();
        self.settings_dialog.render(frame, area, color);

        // Render help overlay
        self.render_help_overlay(frame);
    }

    /// Reads the crossterm events and updates the state of [`App`].
    /// Uses polling with timeout for real-time clock updates.
    fn handle_crossterm_events(&mut self) -> color_eyre::Result<()> {
        // Poll for events with 100ms timeout for smooth clock updates
        if event::poll(Duration::from_millis(100))? {
            match event::read()? {
                Event::Key(key) if key.kind == KeyEventKind::Press => self.on_key_event(key),
                Event::Mouse(_) => {}
                Event::Resize(_, _) => {}
                _ => {}
            }
        }
        Ok(())
    }

    /// Handles the key events and updates the state of [`App`].
    fn on_key_event(&mut self, key: KeyEvent) {
        // If settings dialog is visible, handle dialog keys
        if self.settings_dialog.visible {
            self.handle_settings_key(key);
            return;
        }

        // Toggle help overlay
        if key.code == KeyCode::Char('?') {
            self.show_help = !self.show_help;
            return;
        }
        // Dismiss help on any key if visible
        if self.show_help {
            self.show_help = false;
            return;
        }

        // Let the active mode handle the key first
        if self.modes[self.active_mode_index].handle_key(key, &mut self.ctx) {
            return;
        }

        // Global keybindings
        match (key.modifiers, key.code) {
            (_, KeyCode::Esc | KeyCode::Char('q'))
            | (KeyModifiers::CONTROL, KeyCode::Char('c') | KeyCode::Char('C')) => self.quit(),
            (_, KeyCode::Char('m')) => self.toggle_display_mode(),
            (_, KeyCode::Char('t')) => {
                self.ctx.time_format = self.ctx.time_format.toggle();
            }
            (_, KeyCode::Char('c')) => {
                self.ctx.color_theme = self.ctx.color_theme.next();
            }
            (_, KeyCode::Char('a')) => {
                self.ctx.animation_style = self.ctx.animation_style.next();
            }
            (_, KeyCode::Char('b')) => {
                self.ctx.background_style = self.ctx.background_style.next();
                self.update_background_monitors();
            }
            (_, KeyCode::Char('s')) => self.open_settings(),
            _ => {}
        }
    }

    /// Handle key events when settings dialog is open.
    fn handle_settings_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Esc => {
                self.cancel_settings();
            }
            KeyCode::Enter => {
                self.save_settings();
            }
            KeyCode::Up | KeyCode::Char('k') => {
                self.settings_dialog.prev_field();
            }
            KeyCode::Down | KeyCode::Char('j') => {
                self.settings_dialog.next_field();
            }
            KeyCode::Left | KeyCode::Char('h') => {
                self.settings_dialog.prev_value();
                self.apply_preview();
            }
            KeyCode::Right | KeyCode::Char('l') => {
                self.settings_dialog.next_value();
                self.apply_preview();
            }
            _ => {}
        }
    }

    /// Apply current dialog values as live preview.
    fn apply_preview(&mut self) {
        self.ctx.current_font = self.settings_dialog.selected_font().to_string();
        self.ctx.color_theme = self.settings_dialog.color_theme;
        self.ctx.time_format = self.settings_dialog.time_format;
        self.ctx.animation_style = self.settings_dialog.animation_style;
        self.ctx.animation_speed = self.settings_dialog.animation_speed;
        self.ctx.colon_blink = self.settings_dialog.colon_blink;
        self.ctx.show_seconds = self.settings_dialog.show_seconds;
        self.ctx.background_style = self.settings_dialog.background_style;
        // Update pomodoro config (will take effect on next timer reset)
        self.ctx.config.pomodoro_work_mins = self.settings_dialog.pomodoro_work_mins;
        self.ctx.config.pomodoro_break_mins = self.settings_dialog.pomodoro_break_mins;
        self.ctx.config.pomodoro_long_break_mins = self.settings_dialog.pomodoro_long_break_mins;
        self.ctx.config.pomodoro_sound = self.settings_dialog.pomodoro_sound;
        self.ctx.config.desktop_notifications = self.settings_dialog.desktop_notifications;
        // Update timer duration via downcast
        let new_timer_mins = self.settings_dialog.timer_duration_mins;
        self.ctx.config.timer_duration_mins = new_timer_mins;
        for m in self.modes.iter_mut() {
            if let Some(tm) = m.as_any_mut().downcast_mut::<TimerMode>() {
                tm.sync_duration(new_timer_mins);
                break;
            }
        }
        self.update_background_monitors();
    }

    /// Open settings dialog with current settings.
    fn open_settings(&mut self) {
        self.settings_dialog.open(
            &self.ctx.current_font,
            self.ctx.color_theme,
            self.ctx.time_format,
            self.ctx.animation_style,
            self.ctx.animation_speed,
            self.ctx.colon_blink,
            self.ctx.show_seconds,
            self.ctx.background_style,
            self.ctx.config.pomodoro_work_mins,
            self.ctx.config.pomodoro_break_mins,
            self.ctx.config.pomodoro_long_break_mins,
            self.ctx.config.pomodoro_sound,
            self.ctx.config.desktop_notifications,
            self.ctx.config.timer_duration_mins,
        );
    }

    /// Save current settings to config file and close dialog.
    fn save_settings(&mut self) {
        // Update and save config (values already applied via preview)
        self.ctx.config.font_name = self.ctx.current_font.clone();
        self.ctx.config.color_theme = self.ctx.color_theme;
        self.ctx.config.time_format = self.ctx.time_format;
        self.ctx.config.animation_style = self.ctx.animation_style;
        self.ctx.config.animation_speed = self.ctx.animation_speed;
        self.ctx.config.colon_blink = self.ctx.colon_blink;
        self.ctx.config.show_seconds = self.ctx.show_seconds;
        self.ctx.config.background_style = self.ctx.background_style;
        self.ctx.config.desktop_notifications = self.settings_dialog.desktop_notifications;
        self.ctx.config.timer_duration_mins = self.settings_dialog.timer_duration_mins;

        if let Err(e) = self.ctx.config.save() {
            eprintln!("Warning: Failed to save config: {e}");
        }

        self.settings_dialog.close();
    }

    /// Cancel settings and revert to original values.
    fn cancel_settings(&mut self) {
        // Revert to original values
        self.ctx.current_font = self.settings_dialog.original_font().to_string();
        self.ctx.color_theme = self.settings_dialog.original_color_theme();
        self.ctx.time_format = self.settings_dialog.original_time_format();
        self.ctx.animation_style = self.settings_dialog.original_animation_style();
        self.ctx.animation_speed = self.settings_dialog.original_animation_speed();
        self.ctx.colon_blink = self.settings_dialog.original_colon_blink();
        self.ctx.show_seconds = self.settings_dialog.original_show_seconds();
        self.ctx.background_style = self.settings_dialog.original_background_style();
        self.ctx.config.pomodoro_work_mins = self.settings_dialog.original_pomodoro_work_mins();
        self.ctx.config.pomodoro_break_mins = self.settings_dialog.original_pomodoro_break_mins();
        self.ctx.config.pomodoro_long_break_mins =
            self.settings_dialog.original_pomodoro_long_break_mins();
        self.ctx.config.pomodoro_sound = self.settings_dialog.original_pomodoro_sound();
        self.ctx.config.desktop_notifications =
            self.settings_dialog.original_desktop_notifications();
        let orig_timer_mins = self.settings_dialog.original_timer_duration_mins();
        self.ctx.config.timer_duration_mins = orig_timer_mins;
        // Sync timer mode via downcast
        for m in self.modes.iter_mut() {
            if let Some(tm) = m.as_any_mut().downcast_mut::<TimerMode>() {
                tm.sync_duration(orig_timer_mins);
                break;
            }
        }
        self.update_background_monitors();

        self.settings_dialog.close();
    }

    /// Start or stop background monitors based on current background style.
    fn update_background_monitors(&mut self) {
        // System monitor for reactive backgrounds
        if self.ctx.background_style.is_reactive() && self.system_monitor.is_none() {
            let monitor = SystemMonitor::new();
            monitor.start();
            self.system_monitor = Some(monitor);
        } else if !self.ctx.background_style.is_reactive() && self.system_monitor.is_some() {
            self.system_monitor = None;
        }

        // Weather monitor for weather background
        if self.ctx.background_style.requires_weather() && self.weather_monitor.is_none() {
            let monitor = WeatherMonitor::new(self.ctx.config.weather_location.clone());
            monitor.start();
            self.weather_monitor = Some(monitor);
        } else if !self.ctx.background_style.requires_weather() && self.weather_monitor.is_some() {
            self.weather_monitor = None;
        }
    }

    /// Set running to false to quit the application.
    fn quit(&mut self) {
        self.running = false;
    }

    /// Cycle through display modes by advancing active_mode_index.
    fn toggle_display_mode(&mut self) {
        self.active_mode_index = (self.active_mode_index + 1) % self.modes.len();
    }

    /// Render the help overlay showing all keybindings.
    fn render_help_overlay(&self, frame: &mut Frame) {
        if !self.show_help {
            return;
        }

        let area = frame.area();
        let width = 56u16.min(area.width.saturating_sub(4));
        let height = 28u16.min(area.height.saturating_sub(2));
        let x = (area.width.saturating_sub(width)) / 2;
        let y = (area.height.saturating_sub(height)) / 2;
        let overlay_area = ratatui::layout::Rect::new(x, y, width, height);

        frame.render_widget(Clear, overlay_area);

        let accent = self.ctx.color();
        let fg = Color::White;
        let dim = Color::Gray;

        let key_line = |key: &'static str, desc: &'static str| -> Line<'static> {
            Line::from(vec![
                Span::styled(key, Style::default().fg(fg).bold()),
                Span::styled(desc, Style::default().fg(dim)),
            ])
        };

        let help_lines = vec![
            Line::from(Span::styled(
                "Keyboard Shortcuts",
                Style::default().fg(accent).bold(),
            ))
            .centered(),
            Line::from(""),
            Line::from(Span::styled("  Global", Style::default().fg(accent).bold())),
            key_line("    q / Esc     ", "Quit"),
            key_line("    m           ", "Cycle mode"),
            key_line("    t           ", "Toggle 12/24 hour"),
            key_line("    c           ", "Cycle color theme"),
            key_line("    a           ", "Cycle animation style"),
            key_line("    b           ", "Cycle background"),
            key_line("    s           ", "Open settings"),
            key_line("    ?           ", "Toggle this help"),
            Line::from(""),
            Line::from(Span::styled(
                "  Pomodoro",
                Style::default().fg(accent).bold(),
            )),
            key_line("    Space       ", "Start / Pause"),
            key_line("    r           ", "Reset current phase"),
            key_line("    n           ", "Skip to next phase"),
            Line::from(""),
            Line::from(Span::styled("  Timer", Style::default().fg(accent).bold())),
            key_line("    Space       ", "Start / Pause"),
            key_line("    r           ", "Reset"),
            key_line("    + / -       ", "Adjust duration"),
            Line::from(""),
            Line::from(Span::styled(
                "  Stopwatch",
                Style::default().fg(accent).bold(),
            )),
            key_line("    Space       ", "Start / Pause"),
            key_line("    r           ", "Reset"),
            key_line("    l           ", "Lap"),
            Line::from(""),
            Line::from(Span::styled(
                "Press any key to close",
                Style::default().fg(dim),
            ))
            .centered(),
        ];

        let help_widget = Paragraph::new(help_lines).block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(Style::default().fg(accent))
                .title(" Help ")
                .title_alignment(Alignment::Center)
                .style(Style::default().fg(fg).bg(Color::Black)),
        );

        frame.render_widget(help_widget, overlay_area);
    }
}

impl Default for App {
    fn default() -> Self {
        Self::new()
    }
}

/// Parse a string into a ColorTheme (case-insensitive).
fn parse_color_theme(s: &str) -> Option<ColorTheme> {
    let lower = s.to_lowercase();
    match lower.as_str() {
        "cyan" => Some(ColorTheme::Cyan),
        "green" => Some(ColorTheme::Green),
        "white" => Some(ColorTheme::White),
        "magenta" => Some(ColorTheme::Magenta),
        "yellow" => Some(ColorTheme::Yellow),
        "red" => Some(ColorTheme::Red),
        "blue" => Some(ColorTheme::Blue),
        "rainbow" => Some(ColorTheme::Rainbow),
        "rainbowvertical" | "rainbow-vertical" => Some(ColorTheme::RainbowVertical),
        "gradientwarm" | "gradient-warm" | "warm" => Some(ColorTheme::GradientWarm),
        "gradientcool" | "gradient-cool" | "cool" => Some(ColorTheme::GradientCool),
        "gradientocean" | "gradient-ocean" | "ocean" => Some(ColorTheme::GradientOcean),
        "gradientneon" | "gradient-neon" | "neon" => Some(ColorTheme::GradientNeon),
        "gradientfire" | "gradient-fire" | "fire" => Some(ColorTheme::GradientFire),
        "gradientfrost" | "gradient-frost" | "frost" => Some(ColorTheme::GradientFrost),
        "gradientaurora" | "gradient-aurora" | "aurora" => Some(ColorTheme::GradientAurora),
        "gradientwinter" | "gradient-winter" | "winter" => Some(ColorTheme::GradientWinter),
        "gradientsakura" | "gradient-sakura" | "sakura" => Some(ColorTheme::GradientSakura),
        _ => None,
    }
}

/// Parse a string into a BackgroundStyle (case-insensitive).
fn parse_background_style(s: &str) -> Option<BackgroundStyle> {
    let lower = s.to_lowercase();
    match lower.as_str() {
        "none" => Some(BackgroundStyle::None),
        "starfield" | "stars" => Some(BackgroundStyle::Starfield),
        "matrix" | "matrixrain" | "matrix-rain" => Some(BackgroundStyle::MatrixRain),
        "gradient" | "gradientwave" | "gradient-wave" => Some(BackgroundStyle::GradientWave),
        "snowfall" | "snow" => Some(BackgroundStyle::Snowfall),
        "frost" => Some(BackgroundStyle::Frost),
        "aurora" => Some(BackgroundStyle::Aurora),
        "sunny" | "sun" => Some(BackgroundStyle::Sunny),
        "rainy" | "rain" => Some(BackgroundStyle::Rainy),
        "stormy" | "storm" => Some(BackgroundStyle::Stormy),
        "windy" | "wind" => Some(BackgroundStyle::Windy),
        "cloudy" | "clouds" => Some(BackgroundStyle::Cloudy),
        "foggy" | "fog" => Some(BackgroundStyle::Foggy),
        "weather" => Some(BackgroundStyle::Weather),
        "dawn" | "twilightdawn" | "twilight-dawn" => Some(BackgroundStyle::TwilightDawn),
        "dusk" | "twilightdusk" | "twilight-dusk" => Some(BackgroundStyle::TwilightDusk),
        "cherryblossom" | "cherry-blossom" | "sakura" => Some(BackgroundStyle::CherryBlossom),
        "systempulse" | "system-pulse" | "pulse" => Some(BackgroundStyle::SystemPulse),
        "resourcewave" | "resource-wave" | "resource" => Some(BackgroundStyle::ResourceWave),
        "dataflow" | "data-flow" => Some(BackgroundStyle::DataFlow),
        "heatmap" | "heat-map" | "heat" => Some(BackgroundStyle::HeatMap),
        _ => None,
    }
}

/// Parse a string into a DisplayMode (case-insensitive).
fn parse_display_mode(s: &str) -> Option<DisplayMode> {
    let lower = s.to_lowercase();
    match lower.as_str() {
        "clock" => Some(DisplayMode::Clock),
        "pomodoro" => Some(DisplayMode::Pomodoro),
        "timer" => Some(DisplayMode::Timer),
        "stopwatch" => Some(DisplayMode::Stopwatch),
        "worldclock" | "world-clock" | "world" => Some(DisplayMode::WorldClock),
        _ => None,
    }
}