// src/pages/admin/main/state.rs
use ratatui::widgets::ListState;

/// State for non-admin users (simple profile browser)
#[derive(Default, Clone, Debug)]
pub struct NonAdminState {
    pub profiles: Vec<String>,          // profile names
    pub profile_list_state: ListState,  // highlight state
    pub selected_profile_index: Option<usize>, // persistent selection
}

impl NonAdminState {
    pub fn get_selected_index(&self) -> Option<usize> {
        self.profile_list_state.selected()
    }

    pub fn set_profiles(&mut self, new_profiles: Vec<String>) {
        let current_selection_index = self.profile_list_state.selected();
        self.profiles = new_profiles;

        if self.profiles.is_empty() {
            self.profile_list_state.select(None);
        } else {
            let new_selection = match current_selection_index {
                Some(index) => Some(index.min(self.profiles.len() - 1)),
                None => Some(0),
            };
            self.profile_list_state.select(new_selection);
        }
    }

    pub fn next(&mut self) {
        if self.profiles.is_empty() {
            self.profile_list_state.select(None);
            return;
        }
        let i = match self.profile_list_state.selected() {
            Some(i) => if i >= self.profiles.len() - 1 { 0 } else { i + 1 },
            None => 0,
        };
        self.profile_list_state.select(Some(i));
    }

    pub fn previous(&mut self) {
        if self.profiles.is_empty() {
            self.profile_list_state.select(None);
            return;
        }
        let i = match self.profile_list_state.selected() {
            Some(i) => if i == 0 { self.profiles.len() - 1 } else { i - 1 },
            None => self.profiles.len() - 1,
        };
        self.profile_list_state.select(Some(i));
    }
}
