mod action;
mod app;
mod components;
mod event;
mod theme;
mod tui;
mod yabridge;

use color_eyre::eyre::Result;
use crossterm::terminal::{disable_raw_mode, LeaveAlternateScreen};
use crossterm::ExecutableCommand;

use crate::app::App;
use crate::tui::Tui;

#[tokio::main]
async fn main() -> Result<()> {
    // Install panic hook that restores terminal BEFORE color_eyre's hook runs
    let default_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        let _ = std::io::stderr().execute(LeaveAlternateScreen);
        let _ = disable_raw_mode();
        default_hook(info);
    }));

    color_eyre::install()?;

    // Load saved theme preference
    if let Some(name) = crate::theme::load_theme_preference() {
        crate::theme::set_theme(name);
    }

    // Create and initialize the application
    let mut app = App::new();

    // Create the TUI
    let mut tui = Tui::new()?.tick_rate(250);
    tui.enter()?;

    // Load initial data
    app.init().await;

    // Main event loop
    while app.running {
        // Render
        tui.draw(|frame| app.render(frame))?;

        // Wait for next event OR background action
        tokio::select! {
            event = tui.next() => {
                match event {
                    Some(event) => {
                        let actions = app.handle_event(event);
                        for action in actions {
                            app.process_action(action);
                        }
                    }
                    None => {
                        // Event channel closed — terminal lost
                        break;
                    }
                }
            }
            action = app.recv_action() => {
                if let Some(action) = action {
                    app.process_action(action);
                }
            }
        }
    }

    // Cleanup
    tui.exit()?;

    Ok(())
}
