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

struct App { input: Input, status: String }

impl App {
    fn new() -> Self {
        Self {
            input: Input::new().placeholder("Type, then Ctrl+Y to copy"),
            status: String::new(),
        }
    }
}

impl Component for App {
    fn render(&self, cx: &mut RenderCx) {
        let x = cx.rect.x;
        cx.buffer.write_text(lv_tui::geom::Pos { x, y: cx.rect.y }, cx.rect, "Clipboard Demo (OSC 52)", &cx.style);

        // Position cursor for Input rendering
        cx.cursor = lv_tui::geom::Pos { x, y: cx.rect.y.saturating_add(1) };
        self.input.render(cx);

        cx.buffer.write_text(lv_tui::geom::Pos { x, y: cx.rect.y.saturating_add(2) }, cx.rect, &self.status, &cx.style);
        cx.buffer.write_text(lv_tui::geom::Pos { x, y: cx.rect.y.saturating_add(3) }, cx.rect, "Ctrl+Y copy  q quit", &cx.style);
    }

    fn event(&mut self, e: &Event, cx: &mut EventCx) {
        if e.is_key(Key::Char('q')) { cx.quit(); return; }
        if let Event::Key(k) = e {
            if k.key == Key::Char('c') && k.modifiers.ctrl { cx.quit(); return; }
            if k.key == Key::Char('y') && k.modifiers.ctrl {
                let txt = self.input.text().to_string();
                if !txt.is_empty() {
                    cx.copy_to_clipboard(&txt);
                    self.status = format!("Copied: {}", txt);
                    cx.invalidate_paint();
                }
                return;
            }
        }
        self.input.event(e, cx);
    }

    fn layout(&mut self, r: lv_tui::geom::Rect, cx: &mut lv_tui::component::LayoutCx) {
        self.input.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 for_each_child(&self, f: &mut dyn FnMut(&lv_tui::node::Node)) { self.input.for_each_child(f); }
    fn for_each_child_mut(&mut self, f: &mut dyn FnMut(&mut lv_tui::node::Node)) { self.input.for_each_child_mut(f); }
    fn focusable(&self) -> bool { false }
}

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