// src/pages/intro/logic.rs
use crate::state::app::state::AppState;
use crate::buffer::state::{AppView, BufferState};

/// Handles intro screen selection by updating view history and managing focus state.
/// 0: Continue (restores last form or default)
/// 1: Admin view
/// 2: Login view
/// 3: Register view (with focus reset)
pub fn handle_intro_selection(
    app_state: &mut AppState,
    buffer_state: &mut BufferState,
    index: usize,
) {
    match index {
        // Continue: go to the most recent existing Form tab, or open a sensible default
        0 => {
            // 1) Try to switch to an already open Form buffer (most recent)
            if let Some(existing_path) = buffer_state
                .history
                    .iter()
                    .rev()
                    .find_map(|view| {
                        if let AppView::Form(p) = view {
                            Some(p.clone())
                        } else {
                            None
                        }
                    })
            {
                buffer_state.update_history(AppView::Form(existing_path));
                return;
            }

            // 2) Otherwise pick a fallback path
            let fallback_path = if let (Some(profile), Some(table)) = (
                app_state.current_view_profile_name.clone(),
                app_state.current_view_table_name.clone(),
            ) {
                Some(format!("{}/{}", profile, table))
            } else if let Some(any_key) = app_state.form_editor.keys().next().cloned() {
                // Use any existing editor key if available
                Some(any_key)
            } else {
                // Otherwise pick the first available table from the profile tree
                let mut found: Option<String> = None;
                for prof in &app_state.profile_tree.profiles {
                    if let Some(tbl) = prof.tables.first() {
                        found = Some(format!("{}/{}", prof.name, tbl.name));
                        break;
                    }
                }
                found
            };

            if let Some(path) = fallback_path {
                buffer_state.update_history(AppView::Form(path));
            } else {
                // No sensible default; stay on Intro
            }
        }
        1 => {
            buffer_state.update_history(AppView::Admin);
        }
        2 => {
            buffer_state.update_history(AppView::Login);
        }
        3 => {
            buffer_state.update_history(AppView::Register);
            // Register view requires focus reset
            app_state.ui.focus_outside_canvas = false;
            app_state.focused_button_index = 0;
        }
        _ => return,
    }
}
