zc2 0.0.52

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
use super::{fg, selected, INK3, LIVE, NUM, SPLIT_W, WARN};
use crate::session::app::{App, ACCOUNT_FIXED_ROWS};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, List, ListItem, ListState, Paragraph, Sparkline};
use ratatui::Frame;

pub(super) fn not_running(f: &mut Frame, area: Rect, app: &App) {
    let reason = match &app.agent {
        Some(crate::session::app::AgentState::NotRunning(Some(e))) => e.clone(),
        None => "checking…".into(),
        _ => "no agent.json".into(),
    };
    let lines = vec![
        Line::from(Span::styled("zc agent is not running", fg(WARN))),
        Line::from(Span::styled(reason, fg(INK3))),
        Line::default(),
        Line::from("Account and sharing come from the agent that also serves the menu bar."),
        Line::from(Span::styled(
            "press a to start it — it keeps running after you quit",
            fg(INK3),
        )),
    ];
    f.render_widget(
        Paragraph::new(lines).block(Block::bordered().border_style(fg(INK3))),
        area,
    );
}

pub fn render(f: &mut Frame, area: Rect, app: &App) {
    let Some(s) = app.summary() else {
        return not_running(f, area, app);
    };
    let mut items: Vec<ListItem> = vec![
        ListItem::new(match &s.account {
            Some(a) => format!("Identity    {} · {}", a.username, a.email),
            None => "Identity    not signed in — :login".into(),
        }),
        ListItem::new(Line::from(vec![
            Span::raw("Balance     "),
            Span::styled(
                s.account
                    .as_ref()
                    .map(|a| crate::broker::balance::yen(a.balance))
                    .unwrap_or_else(|| "-".into()),
                fg(NUM),
            ),
        ])),
        ListItem::new(match &s.earnings {
            Some(e) => format!("Earnings    today {:.2} · 7 days {:.2}", e.today, e.last_7d),
            None => "Earnings    -".into(),
        }),
        ListItem::new(format!(
            "Connection  {} · {} · {}",
            s.mesh.route,
            s.mesh.address.clone().unwrap_or_else(|| "-".into()),
            if s.mesh.reachable {
                "reachable"
            } else {
                "unreachable"
            }
        )),
    ];
    for d in s.devices.iter().flatten() {
        let price = d
            .effective_price_per_hour
            .map(|p| {
                if p.min == p.max {
                    format!("{}", p.min)
                } else {
                    format!("{}–{}", p.min, p.max)
                }
            })
            .unwrap_or_else(|| "-".into());
        let dot = if d.freshness == "fresh" {
            fg(LIVE)
        } else {
            fg(INK3)
        };
        items.push(ListItem::new(Line::from(vec![
            Span::styled("● ", dot),
            Span::raw(format!(
                "{}{}  {} workers · {price}/h · {}",
                d.name,
                if d.this_mac { " (this machine)" } else { "" },
                d.workers,
                d.freshness
            )),
        ])));
    }
    let list = List::new(items)
        .block(Block::bordered().border_style(fg(INK3)).title(format!(
            " account · {} of {} devices online ",
            s.devices_online, s.devices_total
        )))
        .highlight_style(selected());
    let mut state = ListState::default();
    state.select(Some(app.account_sel));
    let (l, r) = if area.width >= SPLIT_W {
        let [l, r] = Layout::horizontal([Constraint::Percentage(45), Constraint::Percentage(55)])
            .areas(area);
        (l, Some(r))
    } else {
        (area, None)
    };
    f.render_stateful_widget(list, l, &mut state);
    let Some(r) = r else { return };
    let block = Block::bordered().border_style(fg(INK3));
    if app.account_sel == 2 {
        let data: Vec<u64> = s
            .history
            .as_ref()
            .map(|h| h.hours.iter().map(|b| (b.earned * 100.0) as u64).collect())
            .unwrap_or_default();
        f.render_widget(
            Sparkline::default()
                .block(block.title(" earnings per hour "))
                .data(data)
                .style(fg(LIVE)),
            r,
        );
    } else if app.account_sel >= ACCOUNT_FIXED_ROWS {
        let d = s
            .devices
            .as_ref()
            .and_then(|d| d.get(app.account_sel - ACCOUNT_FIXED_ROWS));
        let lines: Vec<Line> = match d {
            Some(d) => vec![
                Line::from(d.name.clone()),
                Line::from(Span::styled(
                    format!(
                        "last seen {}",
                        d.last_seen_at.clone().unwrap_or_else(|| "-".into())
                    ),
                    fg(INK3),
                )),
                Line::from(Span::styled(d.link.clone().unwrap_or_default(), fg(INK3))),
                Line::default(),
                Line::from(Span::styled("⏎ open in the hub", fg(INK3))),
            ],
            None => vec![],
        };
        f.render_widget(Paragraph::new(lines).block(block.title(" device ")), r);
    } else {
        f.render_widget(
            Paragraph::new(vec![
                Line::from(format!("env {}", s.env)),
                Line::from(Span::styled(
                    format!("agent {} · as of {}", s.agent_version, s.as_of),
                    fg(INK3),
                )),
                Line::from(Span::styled(
                    if s.hub.reachable {
                        "hub reachable".to_string()
                    } else {
                        format!(
                            "hub unreachable: {}",
                            s.hub.error.clone().unwrap_or_default()
                        )
                    },
                    fg(INK3),
                )),
            ])
            .block(block.title(" detail ")),
            r,
        );
    }
}