haj 0.3.7

the beautiful, cross-distro package manager and tui.
use super::{App, DashboardWidget};
use ratatui::{
    Frame,
    layout::{Alignment, Constraint, Direction, Layout},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::Paragraph,
};

pub fn render(f: &mut Frame, app: &mut App) {
    let area = f.area();

    // 1. Title & Subtitle
    let title_str = include_str!("../../resources/title.txt");
    let mut header_lines: Vec<Line> = title_str
        .lines()
        .map(|line| {
            Line::from(Span::styled(
                line,
                Style::default()
                    .fg(app.theme.accent)
                    .add_modifier(Modifier::BOLD),
            ))
        })
        .collect();

    header_lines.push(Line::from(""));
    header_lines.push(Line::from(Span::styled(
        "bla(haj) :3",
        Style::default()
            .fg(app.theme.muted)
            .add_modifier(Modifier::ITALIC),
    )));
    header_lines.push(Line::from(""));

    let header_height = header_lines.len() as u16;
    let show_shark = app.active_widget == DashboardWidget::Blahaj;

    let shark_height_fixed = if show_shark { 28 } else { 0 };
    let stats_actions_height = 4; // 1 spacer + 1 stats + 1 spacer + 1 actions
    let total_fixed = header_height + shark_height_fixed + stats_actions_height;

    // Only apply padding if there's excess space to center it all
    let padding = if area.height > total_fixed {
        (area.height - total_fixed) / 2
    } else {
        0
    };

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(padding),       // [0] dynamic top padding
            Constraint::Length(header_height), // [1] title + subtitle
            if show_shark {
                Constraint::Min(0)
            } else {
                Constraint::Length(0)
            }, // [2] Shark
            Constraint::Length(1),             // [3] spacer
            Constraint::Length(1),             // [4] stats
            Constraint::Length(1),             // [5] spacer between stats and actions
            Constraint::Length(1),             // [6] actions
            Constraint::Length(padding),       // [7] bottom padding
        ])
        .split(area);

    let header = Paragraph::new(header_lines).alignment(Alignment::Center);
    f.render_widget(header, chunks[1]);

    if show_shark && chunks[2].height > 0 {
        let art_height = app.dashboard_art.lines.len() as u16;
        let chunk_height = chunks[2].height;
        let v_pad = if chunk_height > art_height {
            (chunk_height - art_height) / 2
        } else {
            0
        };

        let inner_layout = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(v_pad),
                Constraint::Length(art_height),
                Constraint::Min(0),
            ])
            .split(chunks[2]);

        let blahaj_box = Paragraph::new(app.dashboard_art.clone()).alignment(Alignment::Center);
        f.render_widget(blahaj_box, inner_layout[1]);
    }

    // 3. Stats
    let installed_count = app.installed_count;
    let updates = app.updates_count;
    let unread_news = app
        .news_items
        .iter()
        .filter(|n| !app.read_news.contains(&n.link))
        .count();
    let has_critical = app
        .news_items
        .iter()
        .any(|n| n.is_critical && !app.read_news.contains(&n.link));

    let updates_str = if updates > 0 {
        format!("󰚰 {} updates", updates)
    } else {
        "󰚰 0 updates".to_string()
    };
    let updates_color = if updates > 0 {
        app.theme.success
    } else {
        app.theme.muted
    };

    let news_str = if has_critical {
        "󰎞 !! manual intervention !!".to_string()
    } else {
        format!("󰎞 {} unread news", unread_news)
    };
    let news_color = if has_critical {
        app.theme.error
    } else if unread_news > 0 {
        app.theme.warning
    } else {
        app.theme.muted
    };

    let orphan_color = if app.orphan_count > 0 {
        app.theme.error
    } else {
        app.theme.muted
    };

    let stats_text = Line::from(vec![
        Span::styled(
            format!("󰏗 {} pkgs", installed_count),
            Style::default().fg(app.theme.accent),
        ),
        Span::styled("   ·   ", Style::default().fg(app.theme.muted)),
        Span::styled(updates_str, Style::default().fg(updates_color)),
        Span::styled("   ·   ", Style::default().fg(app.theme.muted)),
        Span::styled(
            format!("󰆴 {} orphans", app.orphan_count),
            Style::default().fg(orphan_color),
        ),
        Span::styled("   ·   ", Style::default().fg(app.theme.muted)),
        Span::styled(news_str, Style::default().fg(news_color)),
    ]);

    let stats = Paragraph::new(stats_text).alignment(Alignment::Center);
    f.render_widget(stats, chunks[4]);

    // 4. Actions
    let actions = [
        ("search", "f"),
        ("upgrade", "u"),
        ("news", "n"),
        ("stats", "t"),
        ("history", "h"),
        ("groups", "g"),
        ("shark", "b"),
        ("help", "?"),
        ("quit", "q"),
    ];
    let mut action_spans = Vec::new();
    for (idx, (label, key)) in actions.iter().enumerate() {
        if idx > 0 {
            action_spans.push(Span::raw("  "));
        }
        action_spans.push(Span::styled(*label, Style::default().fg(app.theme.text)));
        action_spans.push(Span::styled(" [", Style::default().fg(app.theme.muted)));
        action_spans.push(Span::styled(
            *key,
            Style::default().fg(app.theme.warning).bold(),
        ));
        action_spans.push(Span::styled("]", Style::default().fg(app.theme.muted)));
    }
    let actions_p = Paragraph::new(Line::from(action_spans)).alignment(Alignment::Center);
    f.render_widget(actions_p, chunks[6]);
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::{Terminal, backend::TestBackend, buffer::Buffer, text::Text};

    fn row_containing(buf: &Buffer, needle: &str) -> Option<u16> {
        let area = buf.area;
        for y in 0..area.height {
            let line: String = (0..area.width)
                .map(|x| buf[(x, y)].symbol().chars().next().unwrap_or(' '))
                .collect();
            if line.contains(needle) {
                return Some(y);
            }
        }
        None
    }

    #[test]
    fn test_dashboard_stats_and_shark_positions_stay_fixed_across_art_heights() {
        let mut app = App::new("pacman", true);
        let arts = [
            Text::raw(" loading art... "),
            Text::from(vec![Line::from("  ((@"); 15]),
            Text::from(vec![Line::from("  @@@"); 28]),
            Text::raw(include_str!("../../resources/blahajowo.txt")),
        ];

        for (width, height) in [(100u16, 24u16), (130, 36), (140, 40), (180, 50)] {
            let padding = height.saturating_sub(10 + 28 + 4) / 2;
            let expected_stats_row = height - padding - 3;
            let expected_actions_row = height - padding - 1;

            for art in &arts {
                app.dashboard_art = art.clone();
                let backend = TestBackend::new(width, height);
                let mut terminal = Terminal::new(backend).unwrap();
                terminal.draw(|f| render(f, &mut app)).unwrap();
                let buf = terminal.backend().buffer();

                assert_eq!(
                    row_containing(buf, "pkgs"),
                    Some(expected_stats_row),
                    "stats_text shifted on {width}x{height}"
                );
                assert_eq!(
                    row_containing(buf, "search [f]"),
                    Some(expected_actions_row),
                    "actions row shifted on {width}x{height}"
                );
            }
        }
    }
}