//! Terminal lifecycle and top-level screen routing.

use std::io;

use ratatui::DefaultTerminal;
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEventKind};

use super::config_screen;
use super::menu::{MenuItem, MenuState, render_menu};
use super::mode_select;
use super::picker;
use crate::config::Config;

/// Runs the main menu loop until the user exits.
pub fn run_menu(terminal: &mut DefaultTerminal, config: &Config) -> io::Result<()> {
    let mut state = MenuState::new();
    loop {
        terminal.draw(|frame| render_menu(frame, &state, &config.palette))?;
        if let Event::Key(key) = event::read()? {
            if key.kind != KeyEventKind::Press {
                continue;
            }
            match key.code {
                KeyCode::Char('q') | KeyCode::Esc => return Ok(()),
                KeyCode::Up => state.previous(),
                KeyCode::Down => state.next(),
                KeyCode::Enter => match state.current() {
                    MenuItem::Quit => return Ok(()),
                    MenuItem::Play => {
                        if mode_select::run(terminal, config)? {
                            return Ok(());
                        }
                    }
                    MenuItem::Replay => {
                        if picker::run(terminal, config)? {
                            return Ok(());
                        }
                    }
                    MenuItem::Config => {
                        if config_screen::run(terminal, config)? {
                            return Ok(());
                        }
                    }
                },
                _ => {}
            }
        }
    }
}
