// src/state/app/search.rs

use common::proto::komp_ac::search::search_response::Hit;

/// Holds the complete state for the search palette.
pub struct SearchState {
    /// The name of the table being searched.
    pub table_name: String,
    /// The current text entered by the user.
    pub input: String,
    /// The position of the cursor within the input text.
    pub cursor_position: usize,
    /// The search results returned from the server.
    pub results: Vec<Hit>,
    /// The index of the currently selected search result.
    pub selected_index: usize,
    /// A flag to indicate if a search is currently in progress.
    pub is_loading: bool,
}

impl SearchState {
    /// Creates a new SearchState for a given table.
    pub fn new(table_name: String) -> Self {
        Self {
            table_name,
            input: String::new(),
            cursor_position: 0,
            results: Vec::new(),
            selected_index: 0,
            is_loading: false,
        }
    }

    /// Moves the selection to the next item, wrapping around if at the end.
    pub fn next_result(&mut self) {
        if !self.results.is_empty() {
            let next = self.selected_index + 1;
            self.selected_index = if next >= self.results.len() {
                0 // Wrap to the start
            } else {
                next
            };
        }
    }

    /// Moves the selection to the previous item, wrapping around if at the beginning.
    pub fn previous_result(&mut self) {
        if !self.results.is_empty() {
            self.selected_index = if self.selected_index == 0 {
                self.results.len() - 1 // Wrap to the end
            } else {
                self.selected_index - 1
            };
        }
    }
}
