//! Selection actions for status pane.
//!
//! Handles jumping to specific file types (staged, conflicts) in the status list.

use crate::app::{actions::Action, state::AppState};

/// Handle selection actions in the status pane.
pub fn handle_selection(state: &mut AppState, action: &Action) -> bool {
    match action {
        Action::StatusNextStaged => {
            // Find next staged file after current selection
            let current_idx = state.status_selected;
            let next_staged_idx = state.status_entries
                .iter()
                .enumerate()
                .skip(current_idx + 1) // Start searching after current index
                .find(|(_, entry)| entry.staged) // Find first staged entry
                .map(|(idx, _)| idx); // Extract index
            
            if let Some(idx) = next_staged_idx {
                state.status_selected = idx;
            }
            // If no staged file found, selection remains unchanged
            true
        }
        Action::StatusPrevStaged => {
            // Find previous staged file before current selection
            let current_idx = state.status_selected;
            let prev_staged_idx = state.status_entries
                .iter()
                .enumerate()
                .take(current_idx) // Only search before current index
                .rev() // Reverse to search backwards
                .find(|(_, entry)| entry.staged) // Find first staged entry
                .map(|(idx, _)| idx); // Extract index
            
            if let Some(idx) = prev_staged_idx {
                state.status_selected = idx;
            }
            // If no staged file found, selection remains unchanged
            true
        }
        Action::StatusNextConflict => {
            let current = state.status_selected;
            if let Some(idx) = state
                .status_entries
                .iter()
                .enumerate()
                .skip(current + 1)
                .find(|(_, e)| e.conflict)
                .map(|(i, _)| i)
            {
                state.status_selected = idx;
            }
            true
        }
        Action::StatusPrevConflict => {
            let current = state.status_selected;
            if let Some(idx) = state
                .status_entries
                .iter()
                .enumerate()
                .take(current)
                .rev()
                .find(|(_, e)| e.conflict)
                .map(|(i, _)| i)
            {
                state.status_selected = idx;
            }
            true
        }
        _ => false,
    }
}

