/// RFC 17 验收 example — Mouse hit-test

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

#[derive(Component)]
struct MouseArea {
    label: String,
    #[reactive(paint, copy)]
    clicked: bool,
}

impl MouseArea {
fn new(label: impl Into<String>) -> Self {
        Self { label: label.into(), clicked: false }
    }
}

impl Component for MouseArea {
fn render(&self, cx: &mut RenderCx) {
        if self.get_clicked() {
            cx.set_style(Style::default().fg(Color::Green).bold());
            cx.line(format!("[{}] CLICKED!", self.label));
        } else {
            cx.line(format!("[{}] click me", self.label));
        }
    }
fn event(&mut self, event: &Event, cx: &mut EventCx) {
        if matches!(event, Event::Mouse(_)) {
            self.set_clicked(true, cx);
        }
    }
}

struct Root { body: Column }

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

impl Component for Root {
    fn render(&self, cx: &mut RenderCx) { self.body.render(cx); }
    fn layout(&mut self, rect: Rect, cx: &mut LayoutCx) { self.body.layout(rect, cx); }
    fn event(&mut self, event: &Event, cx: &mut EventCx) {
        if event.is_key(Key::Char('q')) { cx.quit(); }
        if let Event::Key(_) = 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 main() -> lv_tui::Result<()> {
    let body = Column::new()
        .padding(1)
        .gap(1)
        .child(Label::new("=== Mouse Hit-Test Demo ==="))
        .child(MouseArea::new("Area 1"))
        .child(MouseArea::new("Area 2"))
        .child(MouseArea::new("Area 3"))
        .child(Label::new("click a row, press q to quit"));

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