// src/components/common/command_line.rs

use ratatui::{
    widgets::{Block, Paragraph},
    style::Style,
    layout::Rect,
    Frame,
};
use crate::config::colors::themes::Theme;
use unicode_width::UnicodeWidthStr; // Import for width calculation

pub fn render_command_line(
    f: &mut Frame,
    area: Rect,
    input: &str,    // This is event_handler.command_input
    active: bool,   // This is event_handler.command_mode
    theme: &Theme,
    message: &str,  // This is event_handler.command_message
) {
    // Original logic for determining display_text
    let display_text = if !active {
        // If not in normal command mode, but there's a message (e.g. from Find File palette closing)
        // Or if command mode is off and message is empty (render minimally)
        if message.is_empty() {
            "".to_string() // Render an empty string, background will cover
        } else {
            message.to_string()
        }
    } else { // active is true (normal command mode)
        let prompt = ":";
        if message.is_empty() || message == ":" {
            format!("{}{}", prompt, input)
        } else {
            if input.is_empty() { // If command was just executed, input is cleared, show message
                message.to_string()
            } else { // Show input and message
                format!("{}{} | {}", prompt, input, message)
            }
        }
    };

    let content_width = UnicodeWidthStr::width(display_text.as_str());
    let available_width = area.width as usize;
    let padding_needed = available_width.saturating_sub(content_width);

    let display_text_padded = if padding_needed > 0 {
        format!("{}{}", display_text, " ".repeat(padding_needed))
    } else {
        // If text is too long, ratatui's Paragraph will handle truncation.
        // We could also truncate here if specific behavior is needed:
        // display_text.chars().take(available_width).collect::<String>()
        display_text
    };

    // Determine style based on active state, but apply to the whole paragraph
    let text_style = if active {
        Style::default().fg(theme.accent)
    } else {
        // If not active, but there's a message, use default foreground.
        // If message is also empty, this style won't matter much for empty text.
        Style::default().fg(theme.fg)
    };

    let paragraph = Paragraph::new(display_text_padded)
        .block(Block::default().style(Style::default().bg(theme.bg))) // Block ensures bg for whole area
        .style(text_style); // Style for the text itself

    f.render_widget(paragraph, area);
}
