use lv_tui::prelude::*;
use lv_tui::widgets::*;

struct App { content: Column, submitted: String, counter: u32 }

impl App {
    fn new() -> Self {
        Self { counter: 0, submitted: String::new(), content: Column::new().gap(1)
            .child(Label::new("Layout: margin + flexGrow Demo").style(Style::default().bold()))
            .child(Label::new(""))
            .child(Label::new("Row with margin:").style(Style::default().fg(Color::Gray)))
            .child(Row::new().gap(1)
                .child(Label::new(" [A] ").style(Style::default().bg(Color::Blue).fg(Color::White).margin(1)))
                .child(Label::new(" [B] ").style(Style::default().bg(Color::Green).fg(Color::Black).margin(1)))
                .child(Label::new(" [C] ").style(Style::default().bg(Color::Red).fg(Color::White).margin(1))))
            .child(Label::new(""))
            .child(Label::new("flexGrow (fill remaining):").style(Style::default().fg(Color::Gray)))
            .child(Row::new()
                .child(Label::new("Fixed").style(Style::default().width(Length::Fixed(10)).bg(Color::Blue).fg(Color::White)))
                .child(Label::new(" Grow ").style(Style::default().flex_grow(1).bg(Color::Cyan).fg(Color::Black))))
            .child(Label::new(""))
            .child(Label::new("Input with onSubmit:").style(Style::default().fg(Color::Gray)))
            .child(Input::new().placeholder("Press Enter...").on_submit(|_| {}))
            .child(Label::new(""))
            .child(Label::new("q to quit").style(Style::default().fg(Color::Gray))),
        }
    }
}

impl Component for App {
    fn render(&self, cx: &mut RenderCx) {
        self.content.render(cx);
        if !self.submitted.is_empty() {
            let y = cx.rect.y + cx.rect.height - 1;
            cx.buffer.write_text(lv_tui::geom::Pos { x: cx.rect.x, y }, cx.rect, &format!("Submitted: {}", self.submitted), &cx.style);
        }
    }
    fn event(&mut self, e: &Event, cx: &mut EventCx) {
        if e.is_key(Key::Char('q')) { cx.quit(); return; }
        // Check for Enter in the focused Input to capture submission
        if e.is_key(Key::Enter) {
            // The Input handles Enter and calls onSubmit internally.
            // We intercept Enter here at the App level.
            self.counter += 1;
            self.submitted = format!("Submit #{}", self.counter);
            cx.invalidate_paint();
        }
        self.content.event(e, cx);
    }
    fn layout(&mut self, r: lv_tui::geom::Rect, cx: &mut lv_tui::component::LayoutCx) { self.content.layout(r, cx); }
    fn measure(&self, c: lv_tui::layout::Constraint, _cx: &mut lv_tui::component::MeasureCx) -> lv_tui::geom::Size {
        lv_tui::geom::Size { width: c.max.width, height: c.max.height }
    }
    fn focusable(&self) -> bool { false }
}

fn main() -> lv_tui::Result<()> {
    lv_tui::app::App::new(App::new()).run()
}
