// src/bottom_panel/layout.rs

use ratatui::{layout::Constraint, layout::Rect, Frame};
use crate::bottom_panel::{status_line::render_status_line, command_line::render_command_line};
use crate::bottom_panel::find_file_palette;
use crate::config::colors::themes::Theme;
use crate::modes::general::command_navigation::NavigationState;
use crate::state::app::state::AppState;
use crate::pages::routing::Router;

/// Calculate the layout constraints for the bottom panel (status line + command line/palette).
pub fn bottom_panel_constraints(
    app_state: &AppState,
    navigation_state: &NavigationState,
    event_handler_command_mode_active: bool,
) -> Vec<Constraint> {
    let mut status_line_height = 1;
    #[cfg(feature = "ui-debug")]
    {
        if let Some(debug_state) = &app_state.debug_state {
            if debug_state.is_error {
                status_line_height = 4;
            }
        }
    }

    const PALETTE_OPTIONS_HEIGHT_FOR_LAYOUT: u16 = 15;
    let command_palette_area_height = if navigation_state.active {
        1 + PALETTE_OPTIONS_HEIGHT_FOR_LAYOUT
    } else if event_handler_command_mode_active {
        1
    } else {
        0
    };

    let mut constraints = vec![Constraint::Length(status_line_height)];
    if command_palette_area_height > 0 {
        constraints.push(Constraint::Length(command_palette_area_height));
    }
    constraints
}

/// Render the bottom panel (status line + command line/palette).
pub fn render_bottom_panel(
    f: &mut Frame,
    root_chunks: &[Rect],
    chunk_idx: &mut usize,
    current_dir: &str,
    theme: &Theme,
    current_fps: f64,
    app_state: &AppState,
    router: &Router,
    navigation_state: &NavigationState,
    event_handler_command_input: &str,
    event_handler_command_mode_active: bool,
    event_handler_command_message: &str,
) {
    // --- Status line area ---
    let status_line_area = root_chunks[*chunk_idx];
    *chunk_idx += 1;

    // --- Command line / palette area ---
    let command_render_area = if root_chunks.len() > *chunk_idx {
        Some(root_chunks[*chunk_idx])
    } else {
        None
    };
    if command_render_area.is_some() {
        *chunk_idx += 1;
    }

    // --- Render status line ---
    render_status_line(
        f,
        status_line_area,
        current_dir,
        theme,
        current_fps,
        app_state,
        router,
    );

    // --- Render command line or palette ---
    if let Some(area) = command_render_area {
        if navigation_state.active {
            find_file_palette::render_find_file_palette(f, area, theme, navigation_state);
        } else if event_handler_command_mode_active {
            render_command_line(
                f,
                area,
                event_handler_command_input,
                true,
                theme,
                event_handler_command_message,
            );
        }
    }
}
