use crate::backend::CrosstermBackend;
use crate::component::Component;
use crate::runtime::Runtime;
use crate::Result;

/// lv-tui 应用入口
///
/// ```rust,ignore
/// App::new(MyRoot::new()).run()
/// ```
pub struct App<C: Component> {
    root: C,
}

impl<C: Component + 'static> App<C> {
    pub fn new(root: C) -> Self {
        Self { root }
    }

    /// 启动应用主循环（真实终端）
    pub fn run(self) -> Result<()> {
        let backend = CrosstermBackend::new()?;
        Runtime::new(self.root, backend)?.run()
    }

    /// 创建无头测试环境，返回 [`Pilot`](crate::pilot::Pilot) 用于自动化测试。
    ///
    /// ```rust,ignore
    /// let mut pilot = App::test(MyRoot::new(), 80, 24);
    /// pilot.press(Key::Enter);
    /// assert!(pilot.buffer().cells.iter().any(|c| c.symbol == "✓"));
    /// ```
    pub fn test(self, width: u16, height: u16) -> crate::pilot::Pilot {
        crate::pilot::Pilot::new(self.root, width, height)
    }
}
