//! Dashboard UI rendering
//!
//! Renders the full dashboard TUI interface using ratatui.
//! Provides a rich, interactive dashboard experience.

use std::collections::HashMap;

use ratatui::{prelude::*, widgets::*};

use super::{
    config::DashboardConfig,
    state::{DashboardMode, DashboardState},
};
use crate::utils::RouteMetadataAccess;

/// Main dashboard rendering function
pub fn render_dashboard(
    frame: &mut Frame,
    state: &DashboardState,
    config: &DashboardConfig,
    translations: &HashMap<String, String>,
) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // Header - TALLER for better visibility
            Constraint::Min(0),    // Main content (take remaining space)
            Constraint::Length(2), // Status bar - TALLER for better usability
            Constraint::Length(2), // Chat prompt interface - TALLER for better usage
        ])
        .split(frame.area());

    // Render header
    render_header(frame, chunks[0], config, state, translations);

    // Render main content based on mode
    match state.mode {
        DashboardMode::Main => {
            render_main_dashboard(frame, chunks[1], state, config, translations);
        }
        DashboardMode::ActionResult => {
            render_action_result(frame, chunks[1], state, translations);
        }
        DashboardMode::Help => {
            render_help(frame, chunks[1], config, translations);
        }
        DashboardMode::Settings => {
            render_settings(frame, chunks[1], state, translations);
        }
        DashboardMode::PageGenerator => {
            render_page_generator(frame, chunks[1], state, translations);
        }
        DashboardMode::PageEditor => {
            render_page_editor(frame, chunks[1], state, translations);
        }
        DashboardMode::PageSelector => {
            render_page_selector(frame, chunks[1], state, translations);
        }
    }

    // Render status bar
    render_status_bar(frame, chunks[2], state, translations);

    // Render chat prompt interface (simplified, single line)
    render_chat_prompt(frame, chunks[3], state, translations);
}

/// Render dashboard header
fn render_header(
    frame: &mut Frame,
    area: Rect,
    config: &DashboardConfig,
    state: &DashboardState,
    _translations: &HashMap<String, String>,
) {
    let title = format!(
        " {} v{} - {} [{}] ",
        config.dashboard.title,
        config.dashboard.version,
        state.mode_name(),
        state.current_language.to_uppercase()
    );

    let header = Paragraph::new(title)
        .style(
            Style::default()
                .fg(Color::White)
                .bg(Color::Blue)
                .add_modifier(Modifier::BOLD),
        )
        .alignment(Alignment::Center)
        .wrap(Wrap { trim: true });

    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Blue));

    frame.render_widget(header.block(block), area);
}

/// Render main dashboard with categories and actions
fn render_main_dashboard(
    frame: &mut Frame,
    area: Rect,
    state: &DashboardState,
    config: &DashboardConfig,
    translations: &HashMap<String, String>,
) {
    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(30), // Categories
            Constraint::Percentage(70), // Actions
        ])
        .split(area);

    render_categories(frame, chunks[0], state, config, translations);
    render_actions(frame, chunks[1], state, config, translations);
}

/// Render category list
fn render_categories(
    frame: &mut Frame,
    area: Rect,
    state: &DashboardState,
    config: &DashboardConfig,
    translations: &HashMap<String, String>,
) {
    let items: Vec<ListItem> = config
        .categories_with_actions
        .iter()
        .enumerate()
        .map(|(i, category)| {
            let style = if i == state.selected_category_index {
                Style::default()
                    .fg(Color::Black)
                    .bg(Color::LightBlue)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::White)
            };

            let content = format!(
                "{} {} ({})",
                category.icon,
                category.name,
                category.actions.len()
            );

            ListItem::new(content).style(style)
        })
        .collect();

    let items_title = if state.categories_focused {
        translations
            .get("ui-items-focused")
            .map(|s| s.as_str())
            .unwrap_or("Items [FOCUSED]")
    } else {
        translations
            .get("ui-items")
            .map(|s| s.as_str())
            .unwrap_or("Items")
    };

    let items_list = List::new(items)
        .block(
            Block::default()
                .title(items_title)
                .borders(Borders::TOP | Borders::BOTTOM) // Minimal borders
                .border_style(if state.categories_focused {
                    Style::default()
                        .fg(Color::LightCyan)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(Color::Cyan)
                }),
        )
        .highlight_style(
            Style::default()
                .fg(Color::Black)
                .bg(Color::LightBlue)
                .add_modifier(Modifier::BOLD),
        );

    frame.render_widget(items_list, area);
}

/// Render actions for selected category
fn render_actions(
    frame: &mut Frame,
    area: Rect,
    state: &DashboardState,
    config: &DashboardConfig,
    translations: &HashMap<String, String>,
) {
    if let Some(category) = state.get_current_category(config) {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(6), // Category info - MORE height for top panel
                Constraint::Min(10),   // Actions list - main content needs good space
                Constraint::Length(5), // Action details - MORE height for bottom panel
            ])
            .split(area);

        // Item info (without "Category Info" title)
        let item_info = Paragraph::new(format!(
            "{} {}\n{}",
            category.icon, category.name, category.description
        ))
        .block(
            Block::default()
                .borders(Borders::TOP | Borders::BOTTOM) // Minimal borders
                .border_style(Style::default().fg(Color::Green)),
        )
        .wrap(Wrap { trim: true });

        frame.render_widget(item_info, chunks[0]);

        // Actions list
        let actions_items: Vec<ListItem> = category
            .actions
            .iter()
            .enumerate()
            .map(|(i, action)| {
                let style = if i == state.selected_action_index {
                    Style::default()
                        .fg(Color::Black)
                        .bg(Color::LightGreen)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(Color::White)
                };

                let shortcut = if action.shortcut.is_empty() {
                    String::new()
                } else {
                    format!(" [{}]", action.shortcut)
                };

                let content = format!("{} {}{}", action.icon, action.name, shortcut);
                ListItem::new(content).style(style)
            })
            .collect();

        let subitems_title = if !state.categories_focused {
            format!(
                "{} ({}) [FOCUSED]",
                translations
                    .get("ui-subitems-focused")
                    .map(|s| s.as_str())
                    .unwrap_or("Sub-items [FOCUSED]"),
                category.actions.len()
            )
        } else {
            format!(
                "{} ({})",
                translations
                    .get("ui-subitems")
                    .map(|s| s.as_str())
                    .unwrap_or("Sub-items"),
                category.actions.len()
            )
        };

        let subitems_list = List::new(actions_items)
            .block(
                Block::default()
                    .title(subitems_title)
                    .borders(Borders::ALL)
                    .border_style(if !state.categories_focused {
                        Style::default()
                            .fg(Color::LightGreen)
                            .add_modifier(Modifier::BOLD)
                    } else {
                        Style::default().fg(Color::Green)
                    }),
            )
            .highlight_style(
                Style::default()
                    .fg(Color::Black)
                    .bg(Color::LightGreen)
                    .add_modifier(Modifier::BOLD),
            );

        frame.render_widget(subitems_list, chunks[1]);

        // Action details
        if let Some(action) = state.get_selected_action(config) {
            let action_details = Paragraph::new(format!(
                "Description: {}\nCommand: {}\nShortcut: {}",
                action.description, action.command, action.shortcut
            ))
            .block(
                Block::default()
                    .title("Action Details")
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(Color::Yellow)),
            )
            .wrap(Wrap { trim: true });

            frame.render_widget(action_details, chunks[2]);
        }
    } else {
        let no_item_selected = Paragraph::new("No item selected")
            .block(
                Block::default()
                    .title(
                        translations
                            .get("ui-subitems")
                            .map(|s| s.as_str())
                            .unwrap_or("Sub-items"),
                    )
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(Color::Red)),
            )
            .alignment(Alignment::Center);

        frame.render_widget(no_item_selected, area);
    }
}

/// Render action execution result
fn render_action_result(
    frame: &mut Frame,
    area: Rect,
    state: &DashboardState,
    translations: &HashMap<String, String>,
) {
    let result_text = state.action_result.as_deref().unwrap_or("No result");

    let result_title = translations
        .get("ui-action-result")
        .map(|s| s.as_str())
        .unwrap_or("Result");
    let result = Paragraph::new(result_text)
        .block(
            Block::default()
                .title(result_title)
                .borders(Borders::ALL)
                .border_style(Style::default().fg(Color::Green)),
        )
        .wrap(Wrap { trim: true })
        .scroll((0, 0));

    frame.render_widget(result, area);
}

/// Render help screen
fn render_help(
    frame: &mut Frame,
    area: Rect,
    config: &DashboardConfig,
    _translations: &HashMap<String, String>,
) {
    let help_text = format!(
        "Rustelo Dashboard Help\n\nNavigation:\n↑/↓     - Move selection up/down\n←/→     - \
         Switch categories\nTab     - Next category\nEnter   - Execute action\nEsc     - Back to \
         main / Exit\nCtrl+Q  - Quit\n\nQuick Actions:\n{}",
        config
            .quick_actions
            .iter()
            .map(|qa| format!("         {}    - {}", qa.shortcut, qa.name))
            .collect::<Vec<_>>()
            .join("\n")
    );

    let help = Paragraph::new(help_text)
        .block(
            Block::default()
                .title("Help")
                .borders(Borders::ALL)
                .border_style(Style::default().fg(Color::Cyan)),
        )
        .wrap(Wrap { trim: true });

    frame.render_widget(help, area);
}

/// Render settings screen
fn render_settings(
    frame: &mut Frame,
    area: Rect,
    state: &DashboardState,
    _translations: &HashMap<String, String>,
) {
    let settings_text = format!(
        "Dashboard Settings\n\nTerminal Size: {}x{}\nShow Shortcuts: {}\nShow Descriptions: \
         {}\nCurrent Language: {}\nAvailable Languages: {}\nLast Refresh: {:?}\n\nPress F12 to \
         switch language\nPress Esc to return to dashboard",
        state.terminal_size.0,
        state.terminal_size.1,
        state.show_shortcuts,
        state.show_descriptions,
        state.current_language,
        state.available_languages.join(", "),
        state.last_refresh
    );

    let settings = Paragraph::new(settings_text)
        .block(
            Block::default()
                .title("Settings")
                .borders(Borders::ALL)
                .border_style(Style::default().fg(Color::Magenta)),
        )
        .wrap(Wrap { trim: true });

    frame.render_widget(settings, area);
}

/// Render status bar
fn render_status_bar(
    frame: &mut Frame,
    area: Rect,
    state: &DashboardState,
    _translations: &HashMap<String, String>,
) {
    let status_text = if let Some(error) = &state.error_message {
        format!("❌ {}", error)
    } else if let Some(status) = &state.status_message {
        format!("✅ {}", status)
    } else {
        "Ready - Space: switch panels | Tab: categories | ↑↓: navigate | Enter: execute".to_string()
    };

    let style = if state.error_message.is_some() {
        Style::default().fg(Color::Red)
    } else if state.status_message.is_some() {
        Style::default().fg(Color::Green)
    } else {
        Style::default().fg(Color::Gray)
    };

    let status = Paragraph::new(status_text)
        .style(style)
        .alignment(Alignment::Left)
        .wrap(Wrap { trim: true });

    frame.render_widget(status, area);
}

/// Render language selector
fn render_language_selector(
    frame: &mut Frame,
    area: Rect,
    state: &DashboardState,
    translations: &HashMap<String, String>,
) {
    let available_langs = state
        .available_languages
        .iter()
        .map(|lang| {
            if lang == &state.current_language {
                format!("[{}]", lang.to_uppercase())
            } else {
                lang.to_uppercase()
            }
        })
        .collect::<Vec<_>>()
        .join(" | ");

    let f12_hint = translations
        .get("ui-f12-language")
        .map(|s| s.as_str())
        .unwrap_or("F12 Language");

    let lang_text = if state.available_languages.len() > 1 {
        format!("{} ({})", available_langs, f12_hint)
    } else {
        format!("Language: {}", state.current_language.to_uppercase())
    };

    let language_selector = Paragraph::new(lang_text)
        .style(Style::default().fg(Color::DarkGray))
        .alignment(Alignment::Center)
        .wrap(Wrap { trim: true });

    frame.render_widget(language_selector, area);
}

/// Render chat prompt interface
fn render_chat_prompt(
    frame: &mut Frame,
    area: Rect,
    state: &DashboardState,
    translations: &HashMap<String, String>,
) {
    let input_text = if state.chat_focused {
        format!(
            "💬 {}: {}",
            translations
                .get("ui-chat-prompt")
                .map(|s| s.as_str())
                .unwrap_or("Ask AI Assistant"),
            state.chat_input
        )
    } else if state.chat_input.is_empty() {
        format!(
            "💬 {} | Press '/' to start",
            translations
                .get("ui-chat-prompt")
                .map(|s| s.as_str())
                .unwrap_or("Ask AI Assistant")
        )
    } else {
        format!(
            "💬 {}: {}",
            translations
                .get("ui-chat-prompt")
                .map(|s| s.as_str())
                .unwrap_or("Ask AI Assistant"),
            state.chat_input
        )
    };

    let style = if state.chat_focused {
        Style::default().fg(Color::White).bg(Color::DarkGray)
    } else {
        Style::default().fg(Color::Gray)
    };

    let prompt = Paragraph::new(input_text)
        .style(style)
        .alignment(Alignment::Left);

    frame.render_widget(prompt, area);
}

/// Render quick actions bar
fn render_quick_actions(
    frame: &mut Frame,
    area: Rect,
    config: &DashboardConfig,
    state: &DashboardState,
    translations: &HashMap<String, String>,
) {
    let mut quick_actions_text: Vec<String> = config
        .quick_actions
        .iter()
        .map(|qa| format!("[{}] {}", qa.shortcut, qa.name))
        .collect();

    // Add navigation and chat-related shortcuts
    if state.chat_focused {
        quick_actions_text.insert(0, "[Enter] Submit".to_string());
        quick_actions_text.insert(1, "[Esc] Unfocus".to_string());
    } else {
        let space_switch = translations
            .get("ui-space-switch")
            .map(|s| s.as_str())
            .unwrap_or("Space Switch Panel");
        let chat_focus = translations
            .get("ui-chat-focus")
            .map(|s| s.as_str())
            .unwrap_or("Chat");
        quick_actions_text.insert(0, format!("[Space] {}", space_switch));
        quick_actions_text.insert(1, format!("[/] {}", chat_focus));
        if state.available_languages.len() > 1 {
            let lang_text = translations
                .get("ui-f12-language")
                .map(|s| s.as_str())
                .unwrap_or("F12 Language");
            quick_actions_text.insert(2, format!("[F12] {}", lang_text));
        }
    }

    let text = quick_actions_text.join(" | ");

    let quick_actions = Paragraph::new(text)
        .style(Style::default().fg(Color::Cyan))
        .alignment(Alignment::Center)
        .wrap(Wrap { trim: true });

    frame.render_widget(quick_actions, area);
}

/// Render page generator mode
fn render_page_generator(
    frame: &mut Frame,
    area: Rect,
    state: &DashboardState,
    _translations: &HashMap<String, String>,
) {
    if let Some(ref page_app) = state.page_app {
        // Use the original rich page generator UI
        crate::manager::ui::form::render_ui(frame, page_app);

        // Check if we need to render generation overlays
        crate::manager::ui::generation::render_generation_overlay(frame, area, page_app);
    } else {
        // Fallback: show initialization message
        let paragraph = Paragraph::new("Initializing page generator...")
            .block(
                Block::default()
                    .title(" Page Generator ")
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(Color::Green)),
            )
            .alignment(Alignment::Center);
        frame.render_widget(paragraph, area);
    }
}

/// Render page editor mode
fn render_page_editor(
    frame: &mut Frame,
    area: Rect,
    state: &DashboardState,
    _translations: &HashMap<String, String>,
) {
    use super::state::PageEditorPanel;

    // Split into main panels: tabs + content
    let main_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // Panel tabs
            Constraint::Min(0),    // Panel content
            Constraint::Length(2), // Help footer
        ])
        .split(area);

    // Render panel tabs
    render_page_editor_tabs(frame, main_chunks[0], state);

    // Render current panel content
    match state.page_editor_panel {
        PageEditorPanel::RouteConfig => {
            render_route_config_panel(frame, main_chunks[1], state);
        }
        PageEditorPanel::I18nFiles => {
            render_i18n_files_panel(frame, main_chunks[1], state);
        }
        PageEditorPanel::SourceFiles => {
            render_source_files_panel(frame, main_chunks[1], state);
        }
        PageEditorPanel::EditorSelector => {
            render_editor_selector_panel(frame, main_chunks[1], state);
        }
    }

    // Render help footer
    render_page_editor_help(frame, main_chunks[2], state);
}

/// Render the panel tabs at the top
fn render_page_editor_tabs(frame: &mut Frame, area: Rect, state: &DashboardState) {
    use super::state::PageEditorPanel;

    let _page_name = state.page_editing_name.as_deref().unwrap_or("Unknown Page");

    let tabs = [
        "📋 Route Config",
        "🌐 I18n Files",
        "🦀 Source Files",
        "🖥️  Editor Select",
    ];

    let tab_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(25),
            Constraint::Percentage(25),
            Constraint::Percentage(25),
            Constraint::Percentage(25),
        ])
        .split(area);

    for (i, (tab_title, chunk)) in tabs.iter().zip(tab_chunks.iter()).enumerate() {
        let is_active = matches!(
            (i, &state.page_editor_panel),
            (0, PageEditorPanel::RouteConfig)
                | (1, PageEditorPanel::I18nFiles)
                | (2, PageEditorPanel::SourceFiles)
                | (3, PageEditorPanel::EditorSelector)
        );

        let style = if is_active {
            Style::default().fg(Color::Black).bg(Color::Green)
        } else {
            Style::default().fg(Color::White).bg(Color::DarkGray)
        };

        let border_style = if is_active {
            Style::default().fg(Color::Green)
        } else {
            Style::default().fg(Color::DarkGray)
        };

        let tab = Paragraph::new(*tab_title)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(border_style),
            )
            .style(style)
            .alignment(Alignment::Center);

        frame.render_widget(tab, *chunk);
    }
}

/// Render route configuration panel
fn render_route_config_panel(frame: &mut Frame, area: Rect, state: &DashboardState) {
    if let Some(ref config) = state.route_config_data {
        // Get all available fields from the RouteConfigToml structure
        let mut fields = Vec::new();

        // Create a mock TOML value for compatibility with the existing code
        if let Ok(toml_string) = toml::to_string(config) {
            if let Ok(toml_value) = toml_string.parse::<toml::Value>() {
                if let Some(routes_table) = toml_value.as_table() {
                    // Find the matching route entry
                    for (route_key, route_value) in routes_table {
                        if let Some(route_table) = route_value.as_table() {
                            if let Some(page_component) = route_table.get("page_component") {
                                if let Some(component_str) = page_component.as_str() {
                                    if component_str == config.component.as_str() {
                                        // Add route key first
                                        fields.push(format!("🔑 Route Key: {}", route_key));

                                        // Get all fields from this route entry dynamically
                                        for (key, value) in route_table {
                                            let icon = match key.as_str() {
                                                "canonical_path" => "📍",
                                                "page_component" => "🦀",
                                                "priority" => "⚡",
                                                "enabled" => "✅",
                                                "auth_required" => "🔐",
                                                "title_key" => "🏷️ ",
                                                "description_key" => "📝",
                                                "keywords" => "🔍",
                                                "meta_description" => "📋",
                                                "robots" => "🤖",
                                                _ => "📄",
                                            };

                                            let value_str = match value {
                                                toml::Value::String(s) => s.clone(),
                                                toml::Value::Integer(i) => i.to_string(),
                                                toml::Value::Float(f) => f.to_string(),
                                                toml::Value::Boolean(b) => {
                                                    if *b { "Yes" } else { "No" }.to_string()
                                                }
                                                toml::Value::Array(arr) => {
                                                    let items: Vec<String> = arr
                                                        .iter()
                                                        .filter_map(|v| v.as_str())
                                                        .map(|s| s.to_string())
                                                        .collect();
                                                    format!("[{}]", items.join(", "))
                                                }
                                                _ => "Complex value".to_string(),
                                            };

                                            fields.push(format!("{} {}: {}", icon, key, value_str));
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        if fields.is_empty() {
            fields.push("No route configuration fields found".to_string());
        }

        let list_items: Vec<ListItem> = fields
            .iter()
            .enumerate()
            .map(|(i, field)| {
                let style = if i == state.selected_panel_item_index {
                    Style::default().fg(Color::Black).bg(Color::Green)
                } else {
                    Style::default().fg(Color::White)
                };
                ListItem::new(field.as_str()).style(style)
            })
            .collect();

        let list = List::new(list_items)
            .block(
                Block::default()
                    .title(" Route Configuration ")
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(Color::Blue)),
            )
            .highlight_style(Style::default().fg(Color::Black).bg(Color::Green));

        frame.render_widget(list, area);
    } else {
        let msg = Paragraph::new("No route configuration found for this page")
            .block(
                Block::default()
                    .title(" Route Configuration ")
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(Color::Red)),
            )
            .style(Style::default().fg(Color::Yellow))
            .alignment(Alignment::Center);
        frame.render_widget(msg, area);
    }
}

/// Render I18n files panel
fn render_i18n_files_panel(frame: &mut Frame, area: Rect, state: &DashboardState) {
    if state.i18n_files.is_empty() {
        let msg = Paragraph::new(
            "No I18n files found for this page\n\nExpected locations:\n• \
             site/i18n/locales/en/{page}.ftl\n• site/i18n/locales/es/{page}.ftl",
        )
        .block(
            Block::default()
                .title(" I18n Files ")
                .borders(Borders::ALL)
                .border_style(Style::default().fg(Color::Red)),
        )
        .style(Style::default().fg(Color::Yellow))
        .alignment(Alignment::Center);
        frame.render_widget(msg, area);
    } else {
        let list_items: Vec<ListItem> = state
            .i18n_files
            .iter()
            .enumerate()
            .map(|(i, (display_name, file_path))| {
                let style = if i == state.selected_panel_item_index {
                    Style::default().fg(Color::Black).bg(Color::Green)
                } else {
                    Style::default().fg(Color::White)
                };

                let item_text = format!("{}\n   📁 {}", display_name, file_path);
                ListItem::new(item_text).style(style)
            })
            .collect();

        let list = List::new(list_items)
            .block(
                Block::default()
                    .title(format!(" I18n Files ({}) ", state.i18n_files.len()))
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(Color::Blue)),
            )
            .highlight_style(Style::default().fg(Color::Black).bg(Color::Green));

        frame.render_widget(list, area);
    }
}

/// Render source files panel
fn render_source_files_panel(frame: &mut Frame, area: Rect, state: &DashboardState) {
    if state.source_files.is_empty() {
        let msg = Paragraph::new(
            "No source files found for this page\n\nExpected location:\n• crates/pages/src/{page}/",
        )
        .block(
            Block::default()
                .title(" Source Files ")
                .borders(Borders::ALL)
                .border_style(Style::default().fg(Color::Red)),
        )
        .style(Style::default().fg(Color::Yellow))
        .alignment(Alignment::Center);
        frame.render_widget(msg, area);
    } else {
        let list_items: Vec<ListItem> = state
            .source_files
            .iter()
            .enumerate()
            .map(|(i, (display_name, file_path))| {
                let style = if i == state.selected_panel_item_index {
                    Style::default().fg(Color::Black).bg(Color::Green)
                } else {
                    Style::default().fg(Color::White)
                };

                let item_text = format!("{}\n   📁 {}", display_name, file_path);
                ListItem::new(item_text).style(style)
            })
            .collect();

        let list = List::new(list_items)
            .block(
                Block::default()
                    .title(format!(" Source Files ({}) ", state.source_files.len()))
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(Color::Blue)),
            )
            .highlight_style(Style::default().fg(Color::Black).bg(Color::Green));

        frame.render_widget(list, area);
    }
}

/// Render editor selector panel
fn render_editor_selector_panel(frame: &mut Frame, area: Rect, state: &DashboardState) {
    let editors = [
        "💻 VS Code - Multi-tab support, excellent Rust integration",
        "🚀 Cursor - AI-powered editor with multi-tab support",
        "⚙️  System Default - Uses your system's default editor",
    ];

    let list_items: Vec<ListItem> = editors
        .iter()
        .enumerate()
        .map(|(i, editor_desc)| {
            let style = if i == state.selected_panel_item_index {
                Style::default().fg(Color::Black).bg(Color::Green)
            } else {
                Style::default().fg(Color::White)
            };
            ListItem::new(*editor_desc).style(style)
        })
        .collect();

    let list = List::new(list_items)
        .block(
            Block::default()
                .title(" Editor Selection ")
                .borders(Borders::ALL)
                .border_style(Style::default().fg(Color::Blue)),
        )
        .highlight_style(Style::default().fg(Color::Black).bg(Color::Green));

    frame.render_widget(list, area);
}

/// Render help footer for page editor
fn render_page_editor_help(frame: &mut Frame, area: Rect, state: &DashboardState) {
    use super::state::PageEditorPanel;

    let help_text = match state.page_editor_panel {
        PageEditorPanel::RouteConfig => {
            "↑↓: Select field | [v] View | [e] Edit | [Space] Next Panel | [Shift+Tab] Prev Panel \
             | [/] AI Assistant | [Esc] Back"
        }
        PageEditorPanel::I18nFiles | PageEditorPanel::SourceFiles => {
            "↑↓: Select file | [v] View | [e] Edit | [Space] Next Panel | [Shift+Tab] Prev Panel | \
             [/] AI Assistant | [Esc] Back"
        }
        PageEditorPanel::EditorSelector => {
            "↑↓: Select editor | [v] View | [e] Set Default | [Space] Next Panel | [Shift+Tab] \
             Prev Panel | [/] AI Assistant | [Esc] Back"
        }
    };

    let help = Paragraph::new(help_text)
        .block(
            Block::default()
                .title(" Controls ")
                .borders(Borders::ALL)
                .border_style(Style::default().fg(Color::DarkGray)),
        )
        .style(Style::default().fg(Color::Gray))
        .alignment(Alignment::Center)
        .wrap(Wrap { trim: true });

    frame.render_widget(help, area);
}

/// Render page selector interface
fn render_page_selector(
    frame: &mut Frame,
    area: Rect,
    state: &DashboardState,
    translations: &HashMap<String, String>,
) {
    let block = Block::default()
        .title(" Select Page to Edit ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::Cyan));

    let inner = block.inner(area);
    frame.render_widget(block, area);

    if state.available_pages.is_empty() {
        // No pages found
        let no_pages_msg = translations
            .get("selector-no-pages")
            .cloned()
            .unwrap_or_else(|| {
                "No pages found to edit.\nCreate a page first using the page generator.".to_string()
            });

        let paragraph = Paragraph::new(no_pages_msg)
            .style(Style::default().fg(Color::Yellow))
            .alignment(Alignment::Center);
        frame.render_widget(paragraph, inner);
    } else {
        // Create list items from available pages
        let items: Vec<ListItem> = state
            .available_pages
            .iter()
            .enumerate()
            .map(|(i, page)| {
                let style = if i == state.selected_page_index {
                    Style::default().fg(Color::Black).bg(Color::Cyan)
                } else {
                    Style::default().fg(Color::White)
                };

                let display_text = if page.contains("→") {
                    // New route-based format: "/about → AboutPage"
                    format!("🌐 {}", page)
                } else if page.starts_with("📄") {
                    // File-based format already has prefix
                    page.clone()
                } else if page.starts_with("component:") {
                    format!("🧩 {}", page.strip_prefix("component:").unwrap_or(page))
                } else {
                    format!("📄 {}", page)
                };

                ListItem::new(display_text).style(style)
            })
            .collect();

        let list = List::new(items)
            .highlight_style(Style::default().fg(Color::Black).bg(Color::Cyan))
            .highlight_symbol("▶ ");

        frame.render_widget(list, inner);

        // Show help text at the bottom
        let help_area = Rect {
            x: inner.x,
            y: inner.y + inner.height - 2,
            width: inner.width,
            height: 2,
        };

        let help_text = "↑↓: Navigate | Enter: Select | Esc: Cancel";
        let help = Paragraph::new(help_text)
            .style(Style::default().fg(Color::DarkGray))
            .alignment(Alignment::Center);
        frame.render_widget(help, help_area);
    }
}
