use gtk::prelude::*;

/// Create a sparkline widget showing a mini trend chart.
pub fn sparkline_widget(data: &[f64], width: i32, height: i32) -> gtk::DrawingArea {
    let area = gtk::DrawingArea::builder()
        .accessible_role(gtk::AccessibleRole::Img)
        .build();
    area.update_property(&[gtk::accessible::Property::Label("Spending trend sparkline")]);
    area.set_size_request(width, height);

    if data.is_empty() {
        return area;
    }

    let data_owned: Vec<f64> = data.to_vec();
    area.set_draw_func(move |_area, ctx, w, h| {
        let w = w as f64;
        let h = h as f64;
        let data = &data_owned;

        if data.is_empty() || w <= 0.0 || h <= 0.0 {
            return;
        }

        let min = data.iter().cloned().fold(f64::INFINITY, f64::min);
        let max = data.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
        let range = if (max - min).abs() < 0.01 { 1.0 } else { max - min };

        let padding = 2.0;
        let chart_w = w - padding * 2.0;
        let chart_h = h - padding * 2.0;

        // Determine trend direction
        let first = data.first().copied().unwrap_or(0.0);
        let last = data.last().copied().unwrap_or(0.0);
        let trending_up = last > first;

        // Color: red for trending up (more expenses), green for trending down
        let (r, g, b) = if trending_up {
            (0.87, 0.33, 0.36)  // Red-ish for expenses going up
        } else {
            (0.42, 0.75, 0.45)  // Green-ish for expenses going down
        };

        // Build points
        let step = if data.len() > 1 { chart_w / (data.len() - 1) as f64 } else { chart_w };
        let points: Vec<(f64, f64)> = data.iter().enumerate().map(|(i, &val)| {
            let x = padding + i as f64 * step;
            let y = padding + chart_h - ((val - min) / range * chart_h);
            (x, y)
        }).collect();

        // Fill area under curve
        ctx.move_to(points[0].0, h - padding);
        for &(x, y) in &points {
            ctx.line_to(x, y);
        }
        ctx.line_to(points.last().unwrap().0, h - padding);
        ctx.close_path();
        ctx.set_source_rgba(r, g, b, 0.15);
        let _ = ctx.fill();

        // Draw line
        ctx.move_to(points[0].0, points[0].1);
        for &(x, y) in points.iter().skip(1) {
            ctx.line_to(x, y);
        }
        ctx.set_source_rgba(r, g, b, 0.8);
        ctx.set_line_width(1.5);
        let _ = ctx.stroke();
    });

    area
}
