// src/ui/position_indicator.rs
pub struct PositionIndicator {
    idle: bool,
    first_recording: bool,
    beat_count: usize,
    current_beat: usize,
    metronome_position: f32,
}

impl PositionIndicator {
    pub fn new(
        idle: bool,
        first_recording: bool,
        beat_count: usize,
        current_beat: usize,
        metronome_position: f32,
    ) -> Self {
        Self {
            idle,
            first_recording,
            beat_count,
            current_beat,
            metronome_position,
        }
    }

    /// Calculate the fill amount for the progress bar
    fn calculate_fill_amount(&self) -> f32 {
        if self.idle {
            0.0
        } else if self.first_recording {
            if self.current_beat == 0 {
                self.metronome_position
            } else {
                1.0
            }
        } else {
            (self.current_beat as f32 + self.metronome_position) / self.beat_count as f32
        }
    }

    /// Calculate positions of vertical divider bars during recording
    fn calculate_recording_bar_positions(&self) -> Vec<f32> {
        if !self.first_recording || self.current_beat == 0 {
            return Vec::new();
        }

        let mut positions = Vec::new();
        let total_bars = self.current_beat;
        let target_divisions = self.current_beat + 1;

        for bar_index in 0..total_bars {
            // Calculate target position for this bar (1/(N+1), 2/(N+1), etc.)
            let target_position = (bar_index + 1) as f32 / target_divisions as f32;

            // Calculate where this bar was positioned at the end of the previous beat
            let prev_target = if self.current_beat == 1 {
                // For second beat (current_beat=1), the single bar starts at right edge
                1.0
            } else if bar_index == (self.current_beat - 1) {
                // The newest bar (last one) always starts from the right edge
                1.0
            } else {
                // Existing bars start from their previous final positions
                (bar_index + 1) as f32 / self.current_beat as f32
            };

            // Interpolate from previous position to target position
            let current_position =
                prev_target + (target_position - prev_target) * self.metronome_position;
            positions.push(current_position);
        }

        positions
    }

    /// Calculate positions of vertical divider bars during playback
    fn calculate_playback_bar_positions(&self) -> Vec<f32> {
        if self.beat_count <= 1 {
            return Vec::new();
        }

        let mut positions = Vec::new();
        for i in 1..self.beat_count {
            positions.push(i as f32 / self.beat_count as f32);
        }
        positions
    }
}

impl egui::Widget for PositionIndicator {
    fn ui(self, ui: &mut egui::Ui) -> egui::Response {
        let sf = ui.available_width() / 100.0;

        let bar_height = sf * 8.0;
        let inner_margin = sf * 2.0;

        let background_color = egui::Color32::from_rgb(51, 51, 51); // #333333
        let fill_color = egui::Color32::from_rgb(0, 136, 204); // #0088cc (blue like playing tracks)
        let divider_color = egui::Color32::from_rgb(102, 102, 102); // #666666

        let frame_response = egui::Frame::none()
            .outer_margin(egui::Margin::symmetric(0.0, 5.0 * sf))
            .show(ui, |ui| {
                // Calculate widget size
                let width = ui.available_width();
                let height = bar_height;
                let size = egui::vec2(width, height);

                // Allocate the space we need
                let (rect, response) = ui.allocate_exact_size(size, egui::Sense::hover());

                // Calculate bar position (with inner margin)
                let bar_left = rect.min.x + inner_margin;
                let bar_right = rect.max.x - inner_margin;
                let bar_width = bar_right - bar_left;
                let bar_center_y = rect.center().y;
                let bar_top = bar_center_y - bar_height / 2.0;
                let bar_bottom = bar_center_y + bar_height / 2.0;

                let bar_rect = egui::Rect::from_min_max(
                    egui::pos2(bar_left, bar_top),
                    egui::pos2(bar_right, bar_bottom),
                );

                // Draw background bar
                ui.painter().rect_filled(
                    bar_rect,
                    egui::Rounding::same(bar_height / 2.0),
                    background_color,
                );

                // Calculate and draw fill
                let fill_amount = self.calculate_fill_amount();
                if fill_amount > 0.0 {
                    let fill_width = bar_width * fill_amount.clamp(0.0, 1.0);
                    if fill_width > 0.0 {
                        let fill_rect = egui::Rect::from_min_max(
                            egui::pos2(bar_left, bar_top),
                            egui::pos2(bar_left + fill_width, bar_bottom),
                        );

                        ui.painter().rect_filled(
                            fill_rect,
                            egui::Rounding::same(bar_height / 2.0),
                            fill_color,
                        );
                    }
                }

                // Draw vertical divider lines
                let bar_positions = if self.idle {
                    self.calculate_playback_bar_positions()
                } else if self.first_recording {
                    self.calculate_recording_bar_positions()
                } else {
                    self.calculate_playback_bar_positions()
                };

                for position in bar_positions {
                    let divider_x = bar_left + (bar_width * position.clamp(0.0, 1.0));
                    ui.painter().line_segment(
                        [
                            egui::pos2(divider_x, bar_top),
                            egui::pos2(divider_x, bar_bottom),
                        ],
                        egui::Stroke::new(1.5 * sf, divider_color),
                    );
                }

                response
            });

        frame_response.response
    }
}
