//! Bottom-pane `/resume` picker. Pure rendering; keys in
//! `update.rs::handle_resume_picker_key`.

use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::Modifier;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph};
use ratatui::Frame;

use crate::state::{ResumePickerState, SessionSummary};
use crate::theme;

pub const MAX_ROWS: usize = 10;

pub fn desired_height(sessions: &[SessionSummary]) -> u16 {
    let n = (sessions.len().min(MAX_ROWS) as u16).clamp(1, MAX_ROWS as u16);
    2 + n + 1
}

pub fn render(
    state: &ResumePickerState,
    sessions: &[SessionSummary],
    frame: &mut Frame,
    area: Rect,
) {
    let block = Block::default()
        .title(" Resume session ")
        .borders(Borders::ALL)
        .border_style(theme::modal_border());
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(0), Constraint::Length(1)])
        .split(inner);

    let mut body: Vec<Line> = Vec::new();
    if sessions.is_empty() {
        body.push(Line::from(Span::styled(
            "(no saved sessions for this directory)",
            theme::dim(),
        )));
    } else {
        for (idx, s) in sessions.iter().take(MAX_ROWS).enumerate() {
            let selected = idx == state.selected;
            let marker = if selected { "› " } else { "  " };
            let style = if selected {
                theme::primary().add_modifier(Modifier::BOLD)
            } else {
                theme::primary()
            };
            body.push(Line::from(vec![
                Span::styled(
                    marker,
                    if selected {
                        theme::assistant()
                    } else {
                        theme::dim()
                    },
                ),
                Span::styled(s.label.clone(), style),
            ]));
        }
    }
    frame.render_widget(Paragraph::new(body), chunks[0]);

    frame.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled("↑↓", theme::assistant()),
            Span::raw(" navigate  "),
            Span::styled("Enter", theme::assistant()),
            Span::raw(" resume  "),
            Span::styled("Esc", theme::error()),
            Span::raw(" cancel"),
        ])),
        chunks[1],
    );
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::backend::TestBackend;
    use ratatui::Terminal;

    fn sessions() -> Vec<SessionSummary> {
        vec![
            SessionSummary {
                id: "01ab".into(),
                label: "01ab  2026-05-18  fix the parser".into(),
            },
            SessionSummary {
                id: "02cd".into(),
                label: "02cd  2026-05-17  add tests".into(),
            },
        ]
    }

    #[test]
    fn renders_resume_picker() -> Result<(), Box<dyn std::error::Error>> {
        let mut term = Terminal::new(TestBackend::new(70, 6))?;
        term.draw(|f| render(&ResumePickerState::default(), &sessions(), f, f.area()))?;
        insta::assert_snapshot!(term.backend());
        Ok(())
    }

    #[test]
    fn desired_height_scales_and_handles_empty() {
        assert_eq!(desired_height(&sessions()), 2 + 2 + 1);
        assert_eq!(desired_height(&[]), 2 + 1 + 1);
    }
}
