use crate::app::App;
use crate::ui::theme::{self, pal};
use crate::ui::widgets::{hd, item, link, mono};
use rune::{El, col, row, text};

pub fn view(s: &App, open: Option<&str>) -> El {
    let p = pal();
    let Some(ws) = &s.ws else { return col() };
    let new = link("+ new", |s: &mut App| {
        let stem = s.ws.as_mut().map(|w| w.new_prompt()).unwrap_or_default();
        s.open_prompt(&stem);
    });
    let prompts = ws.prompts.iter().map(|stem| {
        let on = open == Some(stem.as_str());
        let st = stem.clone();
        item(
            on,
            row()
                .gap(6.0)
                .child(mono(
                    if on { "◆" } else { "◇" },
                    if on { p.accent } else { p.muted },
                ))
                .child(
                    text(s.title(stem))
                        .font(theme::BODY)
                        .color(if on { p.strong } else { p.fg })
                        .truncate(),
                ),
        )
        .key(format!("prompt-{stem}"))
        .cursor(rune::Cursor::Pointer)
        .on_press(move |s: &mut App| s.open_prompt(&st))
    });
    let workflows = ws.workflows.iter().map(|(stem, v, approved)| {
        let st = stem.clone();
        let v = *v;
        item(
            false,
            row()
                .gap(6.0)
                .child(mono(
                    if *approved { "✓" } else { "○" },
                    if *approved { p.ok } else { p.muted },
                ))
                .child(
                    text(s.title(stem))
                        .font(theme::BODY)
                        .color(p.fg)
                        .truncate()
                        .min_w(0.0),
                )
                .child(text(format!("· v{v}")).font(theme::BODY).color(p.muted)),
        )
        .key(format!("workflow-{stem}"))
        .cursor(rune::Cursor::Pointer)
        .on_press(move |s: &mut App| s.open_review(&st, v))
    });
    col()
        .scroll(rune::ScrollSpec {
            stick_bottom: false,
        })
        .child(
            row()
                .justify_between()
                .center_y()
                .child(hd("Prompts", &ws.prompts.len().to_string()).grow(1.0))
                .child(new.mr(8.0).mt(8.0).px(4.0)),
        )
        .children(prompts)
        .child(hd("Workflows", &ws.workflows.len().to_string()))
        .children(workflows)
}
