/// RFC 16 验收 example — 焦点系统
///
/// 验证：
/// - Tab 在可聚焦组件间切换焦点
/// - Shift+Tab 反向导航
/// - 聚焦组件渲染样式变化（通过 cx.is_focused 判断）
/// - 按 `q` 退出

use lv_tui::prelude::*;
use lv_tui::Component;
use lv_tui::widgets::{Block, Column, Label};

#[derive(Component)]
struct FocusableLabel {
    text: String,
    #[reactive(paint, copy)]
    focused: bool,
}

impl FocusableLabel {
fn new(text: impl Into<String>) -> Self {
        Self { text: text.into(), focused: false }
    }
}

impl Component for FocusableLabel {
fn render(&self, cx: &mut RenderCx) {
        if self.get_focused() {
            cx.set_style(Style::default().fg(Color::Green).bold());
            cx.line(format!("> {} <", self.text));
        } else {
            cx.set_style(Style::default());
            cx.line(format!("  {}  ", self.text));
        }
    }
fn event(&mut self, event: &Event, cx: &mut EventCx) {
        match event {
            Event::Focus => self.set_focused(true, cx),
            Event::Blur => self.set_focused(false, cx),
            _ => {}
        }
    }
}

struct Root {
    body: Column,
}

impl Component for Root {
    fn render(&self, cx: &mut RenderCx) {
        self.body.render(cx);
    }

    fn focusable(&self) -> bool {
        false
    }

    fn event(&mut self, event: &Event, cx: &mut EventCx) {
        if event.is_key(Key::Char('q')) {
            cx.quit();
        }
        if let Event::Key(_) | Event::Mouse(_) | Event::Tick = event {
            self.body.event(event, cx);
        }
    }

    fn for_each_child(&self, f: &mut dyn FnMut(&Node)) {
        self.body.for_each_child(f);
    }

    fn for_each_child_mut(&mut self, f: &mut dyn FnMut(&mut Node)) {
        self.body.for_each_child_mut(f);
    }

    fn layout(&mut self, rect: Rect, cx: &mut LayoutCx) {
        self.body.layout(rect, cx);
    }
}

impl Root {
    fn new(body: Column) -> Self {
        Self { body }
    }
}

fn main() -> lv_tui::Result<()> {
    let body = Column::new()
        .padding(1)
        .gap(1)
        .child(Label::new("=== Focus Demo (Tab to switch) ==="))
        .child(
            Block::new(FocusableLabel::new("First item"))
                .border(Border::Plain)
                .padding(1),
        )
        .child(
            Block::new(FocusableLabel::new("Second item"))
                .border(Border::Plain)
                .padding(1),
        )
        .child(
            Block::new(FocusableLabel::new("Third item"))
                .border(Border::Plain)
                .padding(1),
        )
        .child(Label::new("press Tab/Shift+Tab to switch, q to quit"));

    lv_tui::app::App::new(Root::new(body)).run()
}
