//! Main form UI component for page generation

use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, List, ListItem, Paragraph, Wrap},
    Frame,
};

use crate::manager::app::{App, AppMode, Focus, Language, PageTemplate};
use crate::manager::ui::generation::render_generation_overlay;
use crate::manager::ui::modals::render_modal;
use crate::manager::ui::page_manager::render_page_manager_interface;
use crate::manager::ui::preview::{render_preview_pane, PreviewState};

/// Render the main TUI interface
pub fn render_ui(frame: &mut Frame, app: &App) {
    let size = frame.area();

    match app.app_mode {
        AppMode::PageManager => {
            // Render Windows-style page management interface
            if let Some(page_manager_state) = &app.page_manager_state {
                render_page_manager_interface(frame, size, app, page_manager_state);
            } else {
                // Fallback if page manager failed to initialize
                render_page_manager_error(frame, size, app);
            }
        }
        AppMode::CreatePage => {
            // Render original form interface
            render_create_page_interface(frame, app);
        }
    }

    // Render help overlay if active (works in both modes)
    if app.show_help {
        render_help_overlay(frame, size);
    }

    // Render generation overlay (only in create mode)
    if matches!(app.app_mode, AppMode::CreatePage) {
        render_generation_overlay(frame, size, app);
    }

    // Render modal dialogs (works in both modes)
    if let Some(modal_state) = &app.modal_state {
        render_modal(frame, size, app, modal_state);
    }
}

/// Render the create page interface (original form)
fn render_create_page_interface(frame: &mut Frame, app: &App) {
    let size = frame.area();

    // Create main layout
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // Header
            Constraint::Min(0),    // Main content (split-pane)
            Constraint::Length(3), // Footer
        ])
        .split(size);

    // Render header
    render_header(frame, chunks[0], app);

    // Create split-pane layout for main content
    let main_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(50), // Configuration pane
            Constraint::Percentage(50), // Preview pane
        ])
        .split(chunks[1]);

    // Render configuration form
    render_configuration_form(frame, main_chunks[0], app);

    // Create preview state from app
    let preview_state = PreviewState {
        selected_tab: app.preview_tab,
        selected_translation_lang: 0,
    };

    // Render preview pane
    render_preview_pane(frame, main_chunks[1], app, &preview_state);

    // Render footer
    render_footer(frame, chunks[2], app);

    // Render chat overlay if active
    if app.chat_focused {
        render_chat_overlay(frame, size, app);
    }
}

/// Render error screen when page manager fails to initialize
fn render_page_manager_error(frame: &mut Frame, area: Rect, app: &App) {
    let error_message = app
        .translations
        .get("mgr-init-error")
        .cloned()
        .unwrap_or_else(|| {
            "Failed to initialize page manager.\nPress 'C' to switch to create mode.".to_string()
        });

    let error_widget = Paragraph::new(error_message)
        .alignment(Alignment::Center)
        .style(Style::default().fg(Color::Red))
        .block(Block::default().borders(Borders::ALL).title("Error"))
        .wrap(Wrap { trim: true });

    frame.render_widget(error_widget, area);
}

/// Render the header with title, project info, and language selector
fn render_header(frame: &mut Frame, area: Rect, app: &App) {
    // Single header area (language selector removed)
    let title = app
        .translations
        .get("mgr-title")
        .unwrap_or(&"Manager".to_string())
        .clone();

    let project_root = app.project_root.display().to_string();
    let project_text = app
        .translations
        .get("mgr-cli-project-root")
        .map(|s| s.replace("{$path}", &project_root))
        .unwrap_or(format!("Project root: {}", project_root));

    let header_text = vec![
        Line::from(vec![
            Span::styled("🚀 ", Style::default()),
            Span::styled(title, Style::default().add_modifier(Modifier::BOLD)),
        ]),
        Line::from(vec![
            Span::styled("📁 ", Style::default()),
            Span::styled(project_text, Style::default().fg(Color::Gray)),
        ]),
    ];

    let header = Paragraph::new(header_text)
        .block(Block::default().borders(Borders::ALL))
        .alignment(Alignment::Center);

    frame.render_widget(header, area);
}

/// Render language selector in top-right corner
fn render_language_selector(frame: &mut Frame, area: Rect, app: &App) {
    // Create static fallback
    static DEFAULT_LANGUAGE: std::sync::OnceLock<Language> = std::sync::OnceLock::new();
    let default_lang =
        DEFAULT_LANGUAGE.get_or_init(|| Language::new("en".to_string(), "English".to_string()));

    let current_lang = if app.language_selection_index < app.available_languages.len() {
        &app.available_languages[app.language_selection_index]
    } else {
        // Fallback to first language if index is out of bounds
        app.available_languages.first().unwrap_or(default_lang)
    };

    let lang_options: Vec<String> = app
        .available_languages
        .iter()
        .enumerate()
        .map(|(i, lang)| {
            let indicator = if i == app.language_selection_index {
                "▶"
            } else {
                " "
            };
            format!("{} {} ({})", indicator, lang.name, lang.code)
        })
        .collect();

    let is_lang_focused = app.focus == Focus::LanguageSelector;
    let border_style = if is_lang_focused {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default().fg(Color::Gray)
    };

    // Show current language or dropdown
    let content = if is_lang_focused {
        // Show dropdown when focused
        lang_options
            .into_iter()
            .map(ListItem::new)
            .collect::<Vec<_>>()
    } else {
        // Show just current language when not focused
        vec![ListItem::new(format!(
            "🌍 {} ({})",
            current_lang.name, current_lang.code
        ))]
    };

    let lang_list = List::new(content)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title("Language")
                .border_style(border_style),
        )
        .highlight_style(Style::default().bg(Color::Blue).fg(Color::White));

    frame.render_widget(lang_list, area);
}

/// Render the configuration form with all input components
fn render_configuration_form(frame: &mut Frame, area: Rect, app: &App) {
    let form_block = Block::default()
        .borders(Borders::ALL)
        .title("Configuration");

    let form_area = form_block.inner(area);
    frame.render_widget(form_block, area);

    // Split form into sections
    let sections = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // Page name
            Constraint::Length(6), // Template selection
            Constraint::Length(6), // Language selection
            Constraint::Length(3), // Route path
            Constraint::Length(3), // Priority
            Constraint::Length(4), // Options
            Constraint::Length(3), // Action buttons
            Constraint::Min(0),    // Validation errors
        ])
        .split(form_area);

    // Render each form section
    render_page_name_input(frame, sections[0], app);
    render_template_selection(frame, sections[1], app);
    render_language_selection(frame, sections[2], app);
    render_route_path_input(frame, sections[3], app);
    render_priority_input(frame, sections[4], app);
    render_options_checkboxes(frame, sections[5], app);
    render_action_buttons(frame, sections[6], app);
    render_validation_errors(frame, sections[7], app);
}

/// Render page name input field
fn render_page_name_input(frame: &mut Frame, area: Rect, app: &App) {
    let is_focused = app.focus == Focus::PageName;
    let style = if is_focused {
        Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default()
    };

    let default_help = "Use PascalCase naming. This will be your component name.".to_string();
    let help_text = app
        .translations
        .get("mgr-prompt-page-name-help")
        .unwrap_or(&default_help);

    let input_text = if app.page_name.is_empty() && is_focused {
        "│" // Show cursor
    } else {
        &app.page_name
    };

    let content = vec![
        Line::from(vec![
            Span::styled("Page Name: ", Style::default().add_modifier(Modifier::BOLD)),
            Span::styled(input_text, style),
        ]),
        Line::from(Span::styled(
            help_text.clone(),
            Style::default().fg(Color::Gray),
        )),
    ];

    let block = Block::default()
        .borders(if is_focused {
            Borders::ALL
        } else {
            Borders::NONE
        })
        .border_style(if is_focused {
            Style::default().fg(Color::Cyan)
        } else {
            Style::default()
        });

    let paragraph = Paragraph::new(content).block(block);
    frame.render_widget(paragraph, area);
}

/// Render template selection radio buttons
fn render_template_selection(frame: &mut Frame, area: Rect, app: &App) {
    let is_focused = app.focus == Focus::Template;

    let templates = PageTemplate::all();
    let items: Vec<ListItem> = templates
        .iter()
        .map(|template| {
            let is_selected = *template == app.selected_template;
            let radio = if is_selected { "●" } else { "○" };
            let style = if is_selected {
                Style::default()
                    .fg(Color::Green)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default()
            };

            let line = Line::from(vec![
                Span::styled(format!("[{}] ", radio), style),
                Span::styled(template.name(), style),
                Span::styled(
                    format!(" - {}", template.description()),
                    Style::default().fg(Color::Gray),
                ),
            ]);

            ListItem::new(line)
        })
        .collect();

    let block = Block::default()
        .title("Template")
        .borders(if is_focused {
            Borders::ALL
        } else {
            Borders::TOP | Borders::BOTTOM
        })
        .border_style(if is_focused {
            Style::default().fg(Color::Cyan)
        } else {
            Style::default()
        });

    let list = List::new(items).block(block);
    frame.render_widget(list, area);
}

/// Render language selection checkboxes
fn render_language_selection(frame: &mut Frame, area: Rect, app: &App) {
    let is_focused = app.focus == Focus::Languages;

    let items: Vec<ListItem> = app
        .available_languages
        .iter()
        .enumerate()
        .map(|(index, lang)| {
            let checkbox = if lang.selected { "✓" } else { " " };
            let is_highlighted = is_focused && index == app.language_selection_index;

            let style = if is_highlighted {
                // Highlighted (cursor) style
                Style::default()
                    .bg(Color::Cyan)
                    .fg(Color::Black)
                    .add_modifier(Modifier::BOLD)
            } else if lang.selected {
                // Selected but not highlighted
                Style::default()
                    .fg(Color::Green)
                    .add_modifier(Modifier::BOLD)
            } else {
                // Not selected and not highlighted
                Style::default()
            };

            let cursor = if is_highlighted { "➤ " } else { "  " };

            let line = Line::from(vec![
                Span::styled(
                    cursor,
                    if is_highlighted {
                        Style::default().fg(Color::Cyan)
                    } else {
                        Style::default()
                    },
                ),
                Span::styled(format!("[{}] ", checkbox), style),
                Span::styled(format!("{} ({})", lang.name, lang.code), style),
            ]);

            ListItem::new(line)
        })
        .collect();

    let help_text = if is_focused {
        "↑↓: Navigate, Space/Enter: Toggle"
    } else {
        "Multi-select languages for generation"
    };

    let block = Block::default()
        .title(format!("Languages - {}", help_text))
        .borders(if is_focused {
            Borders::ALL
        } else {
            Borders::TOP | Borders::BOTTOM
        })
        .border_style(if is_focused {
            Style::default().fg(Color::Cyan)
        } else {
            Style::default()
        });

    let list = List::new(items).block(block);
    frame.render_widget(list, area);
}

/// Render route path input field
fn render_route_path_input(frame: &mut Frame, area: Rect, app: &App) {
    let is_focused = app.focus == Focus::RoutePath;
    let style = if is_focused {
        Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default()
    };

    let default_help = "URL path for this page (must start with '/')".to_string();
    let base_help = app
        .translations
        .get("mgr-prompt-route-path-help")
        .unwrap_or(&default_help);

    let help_text = if app.route_manually_edited {
        format!("{} (manually edited)", base_help)
    } else {
        format!("{} (auto-generated)", base_help)
    };

    let input_text = if app.route_path.is_empty() && is_focused {
        "│" // Show cursor
    } else {
        &app.route_path
    };

    let content = vec![
        Line::from(vec![
            Span::styled(
                "Route Path: ",
                Style::default().add_modifier(Modifier::BOLD),
            ),
            Span::styled(input_text, style),
            if !app.route_manually_edited && !app.page_name.is_empty() {
                Span::styled(" 🔄", Style::default().fg(Color::Yellow))
            } else if app.route_manually_edited {
                Span::styled(" ✏️", Style::default().fg(Color::Blue))
            } else {
                Span::raw("")
            },
        ]),
        Line::from(Span::styled(help_text, Style::default().fg(Color::Gray))),
    ];

    let block = Block::default()
        .borders(if is_focused {
            Borders::ALL
        } else {
            Borders::NONE
        })
        .border_style(if is_focused {
            Style::default().fg(Color::Cyan)
        } else {
            Style::default()
        });

    let paragraph = Paragraph::new(content).block(block);
    frame.render_widget(paragraph, area);
}

/// Render priority input field
fn render_priority_input(frame: &mut Frame, area: Rect, app: &App) {
    let is_focused = app.focus == Focus::Priority;
    let style = if is_focused {
        Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default()
    };

    let content = vec![Line::from(vec![
        Span::styled("Priority: ", Style::default().add_modifier(Modifier::BOLD)),
        Span::styled(format!("{:.1}", app.priority), style),
        Span::styled(" (0.1 - 10.0)", Style::default().fg(Color::Gray)),
    ])];

    let block = Block::default()
        .borders(if is_focused {
            Borders::ALL
        } else {
            Borders::NONE
        })
        .border_style(if is_focused {
            Style::default().fg(Color::Cyan)
        } else {
            Style::default()
        });

    let paragraph = Paragraph::new(content).block(block);
    frame.render_widget(paragraph, area);
}

/// Render options checkboxes
fn render_options_checkboxes(frame: &mut Frame, area: Rect, app: &App) {
    let auto_scaffold_focused = app.focus == Focus::AutoScaffold;
    let replace_focused = app.focus == Focus::ReplaceExisting;

    let auto_checkbox = if app.auto_scaffold { "✓" } else { " " };
    let replace_checkbox = if app.replace_existing { "✓" } else { " " };

    let auto_style = if auto_scaffold_focused {
        Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD)
    } else if app.auto_scaffold {
        Style::default()
            .fg(Color::Green)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default()
    };

    let replace_style = if replace_focused {
        Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD)
    } else if app.replace_existing {
        Style::default()
            .fg(Color::Green)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default()
    };

    let content = vec![
        Line::from(vec![
            Span::styled(format!("[{}] ", auto_checkbox), auto_style),
            Span::styled("Auto-scaffold files", auto_style),
        ]),
        Line::from(vec![
            Span::styled(format!("[{}] ", replace_checkbox), replace_style),
            Span::styled("Replace existing", replace_style),
        ]),
    ];

    let block = Block::default().title("Options");
    let paragraph = Paragraph::new(content).block(block);
    frame.render_widget(paragraph, area);
}

/// Render action buttons
fn render_action_buttons(frame: &mut Frame, area: Rect, app: &App) {
    let button_layout = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(33),
            Constraint::Percentage(33),
            Constraint::Percentage(34),
        ])
        .split(area);

    // Generate button
    let generate_focused = app.focus == Focus::GenerateButton;
    let generate_style = if generate_focused {
        Style::default()
            .bg(Color::Green)
            .fg(Color::Black)
            .add_modifier(Modifier::BOLD)
    } else if app.is_valid() {
        Style::default()
            .fg(Color::Green)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::Gray)
    };

    let generate_text = if app.is_valid() {
        "Generate"
    } else {
        "Generate (invalid)"
    };
    let generate_button = Paragraph::new(generate_text)
        .alignment(Alignment::Center)
        .style(generate_style)
        .block(Block::default().borders(Borders::ALL));

    frame.render_widget(generate_button, button_layout[0]);

    // Preview button
    let preview_focused = app.focus == Focus::PreviewButton;
    let preview_style = if preview_focused {
        Style::default()
            .bg(Color::Blue)
            .fg(Color::White)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default()
            .fg(Color::Blue)
            .add_modifier(Modifier::BOLD)
    };

    let preview_button = Paragraph::new("Preview")
        .alignment(Alignment::Center)
        .style(preview_style)
        .block(Block::default().borders(Borders::ALL));

    frame.render_widget(preview_button, button_layout[1]);

    // Cancel button
    let cancel_focused = app.focus == Focus::CancelButton;
    let cancel_style = if cancel_focused {
        Style::default()
            .bg(Color::Red)
            .fg(Color::White)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)
    };

    let cancel_button = Paragraph::new("Cancel")
        .alignment(Alignment::Center)
        .style(cancel_style)
        .block(Block::default().borders(Borders::ALL));

    frame.render_widget(cancel_button, button_layout[2]);
}

/// Render validation errors
fn render_validation_errors(frame: &mut Frame, area: Rect, app: &App) {
    if !app.validation_errors.is_empty() {
        let error_items: Vec<ListItem> = app
            .validation_errors
            .iter()
            .map(|error| {
                let line = Line::from(vec![
                    Span::styled("❌ ", Style::default().fg(Color::Red)),
                    Span::styled(&error.message, Style::default().fg(Color::Red)),
                ]);
                ListItem::new(line)
            })
            .collect();

        let error_list = List::new(error_items).block(
            Block::default()
                .title("Validation Errors")
                .borders(Borders::ALL),
        );

        frame.render_widget(error_list, area);
    }
}

/// Render footer with help and navigation hints
fn render_footer(frame: &mut Frame, area: Rect, app: &App) {
    let validation_status = if app.is_valid() {
        Span::styled("✅ Valid", Style::default().fg(Color::Green))
    } else {
        Span::styled(
            format!("❌ {} errors", app.validation_errors.len()),
            Style::default().fg(Color::Red),
        )
    };

    let preview_help = match app.focus {
        Focus::Preview => "←/→: Switch Preview Tabs | ",
        Focus::PreviewButton => "Enter: Jump to Live Preview | ",
        _ => "",
    };

    // Add Space bar help text
    let space_help = if matches!(app.focus, Focus::Preview) {
        "Space: Back to Form | "
    } else if is_configuration_focus_ui(app.focus) {
        "Space: Switch to Preview | "
    } else {
        ""
    };

    let help_text = vec![Line::from(vec![
        Span::styled(
            "Tab/Shift+Tab",
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw(": Navigate | "),
        Span::raw(space_help),
        Span::raw(preview_help),
        Span::styled(
            "Enter",
            Style::default()
                .fg(Color::Green)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw(": Select/Toggle | "),
        Span::styled(
            "Esc",
            Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
        ),
        Span::raw(": Cancel | "),
        Span::styled(
            "?",
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw(": Help | "),
        validation_status,
    ])];

    let footer = Paragraph::new(help_text)
        .block(Block::default().borders(Borders::ALL))
        .alignment(Alignment::Center);

    frame.render_widget(footer, area);
}

/// Render help overlay
fn render_help_overlay(frame: &mut Frame, area: Rect) {
    let help_area = centered_rect(60, 70, area);

    // Clear the background
    frame.render_widget(Clear, help_area);

    let help_content = vec![
        Line::from(Span::styled(
            "Keyboard Shortcuts",
            Style::default().add_modifier(Modifier::BOLD),
        )),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                "Tab/Shift+Tab",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw("    Navigate between fields"),
        ]),
        Line::from(vec![
            Span::styled(
                "Enter",
                Style::default()
                    .fg(Color::Green)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw("           Select option / Toggle checkbox"),
        ]),
        Line::from(vec![
            Span::styled(
                "Space",
                Style::default()
                    .fg(Color::Green)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw("           Switch panels / Toggle options"),
        ]),
        Line::from(vec![
            Span::styled(
                "Esc",
                Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
            ),
            Span::raw("             Cancel / Exit"),
        ]),
        Line::from(vec![
            Span::styled(
                "?",
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw("               Show/hide this help"),
        ]),
        Line::from(""),
        Line::from("Text Input Fields:"),
        Line::from(vec![
            Span::styled(
                "Backspace",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw("       Delete character"),
        ]),
        Line::from(vec![
            Span::styled(
                "Ctrl+W",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw("          Delete word"),
        ]),
        Line::from(vec![
            Span::styled(
                "Ctrl+U",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw("          Clear field"),
        ]),
        Line::from(""),
        Line::from("Priority Field:"),
        Line::from(vec![
            Span::styled(
                "↑/↓ or +/-",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw("      Adjust priority (0.1-10.0)"),
        ]),
        Line::from(""),
        Line::from(Span::styled(
            "Press ? or Esc to close this help",
            Style::default().fg(Color::Gray),
        )),
    ];

    let help_block = Block::default()
        .title("Help")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Yellow));

    let help_paragraph = Paragraph::new(help_content)
        .block(help_block)
        .wrap(Wrap { trim: true });

    frame.render_widget(help_paragraph, help_area);
}

/// Helper function to create a centered rectangle
fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
    let popup_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage((100 - percent_y) / 2),
            Constraint::Percentage(percent_y),
            Constraint::Percentage((100 - percent_y) / 2),
        ])
        .split(r);

    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage((100 - percent_x) / 2),
            Constraint::Percentage(percent_x),
            Constraint::Percentage((100 - percent_x) / 2),
        ])
        .split(popup_layout[1])[1]
}

/// Check if the current focus is part of the configuration form (not preview or
/// buttons) This is a UI version of the function in input.rs
fn is_configuration_focus_ui(focus: Focus) -> bool {
    matches!(
        focus,
        Focus::LanguageSelector
            | Focus::PageName
            | Focus::Template
            | Focus::Languages
            | Focus::RoutePath
            | Focus::Priority
            | Focus::AutoScaffold
            | Focus::ReplaceExisting
    )
}

/// Render chat input overlay
fn render_chat_overlay(frame: &mut Frame, area: Rect, app: &App) {
    // Create overlay area at the bottom
    let overlay_height = 5;
    let overlay_area = Rect {
        x: area.x,
        y: area.height.saturating_sub(overlay_height),
        width: area.width,
        height: overlay_height,
    };

    // Clear the overlay area
    frame.render_widget(Clear, overlay_area);

    // Chat input box
    let chat_text = if app.chat_input.is_empty() {
        "Type your message..."
    } else {
        &app.chat_input
    };

    let chat_input = Paragraph::new(chat_text)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(format!(
                    "💬 {}",
                    app.translations
                        .get("ui-chat-prompt")
                        .map(|s| s.as_str())
                        .unwrap_or("Ask AI Assistant")
                ))
                .border_style(Style::default().fg(Color::Cyan)),
        )
        .style(if app.chat_input.is_empty() {
            Style::default().fg(Color::DarkGray)
        } else {
            Style::default().fg(Color::White)
        });

    frame.render_widget(chat_input, overlay_area);
}
