//! Ratatui app state and core application logic

use std::collections::HashMap;

use crate::manager::page_manager::PageManager;
use crate::manager::ui::modals::{ModalState, ModalType};
use crate::manager::ui::page_manager::PageManagerState;
use crate::manager::version_control::{CommandTemplateManager, VersionControl};

/// Page templates available for generation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PageTemplate {
    HeroPage,
    FormPage,
    ContentList,
    BasicPage,
}

impl PageTemplate {
    pub fn all() -> Vec<Self> {
        vec![
            Self::HeroPage,
            Self::FormPage,
            Self::ContentList,
            Self::BasicPage,
        ]
    }

    pub fn name(&self) -> &'static str {
        match self {
            Self::HeroPage => "Hero Page",
            Self::FormPage => "Form Page",
            Self::ContentList => "Content List",
            Self::BasicPage => "Basic Page",
        }
    }

    pub fn description(&self) -> &'static str {
        match self {
            Self::HeroPage => "Landing page with hero section and CTAs",
            Self::FormPage => "Page with interactive form components",
            Self::ContentList => "Dynamic content listing with filters",
            Self::BasicPage => "Simple page with standard layout",
        }
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            Self::HeroPage => "hero_page",
            Self::FormPage => "form_page",
            Self::ContentList => "content_list",
            Self::BasicPage => "basic_page",
        }
    }
}

/// Available languages for page generation
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Language {
    pub code: String,
    pub name: String,
    pub selected: bool,
}

impl Language {
    pub fn new(code: String, name: String) -> Self {
        Self {
            code,
            name,
            selected: false,
        }
    }
}

/// Application mode
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AppMode {
    /// Page management mode (Windows-style interface)
    PageManager,
    /// Page creation mode (original form interface)
    CreatePage,
}

/// Current focus/active input component
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Focus {
    LanguageSelector, // Language selector in header
    PageName,
    Template,
    Languages,
    RoutePath,
    Priority,
    AutoScaffold,
    ReplaceExisting,
    GenerateButton,
    PreviewButton,
    CancelButton,
    Preview, // Preview pane focus
    // Generation workflow focuses
    ConfirmGenerate,
    GenerationProgress,
    GenerationResults,
}

impl Focus {
    /// Get next focus in tab order
    pub fn next(&self) -> Self {
        match self {
            Self::LanguageSelector => Self::PageName,
            Self::PageName => Self::Template,
            Self::Template => Self::Languages,
            Self::Languages => Self::RoutePath,
            Self::RoutePath => Self::Priority,
            Self::Priority => Self::AutoScaffold,
            Self::AutoScaffold => Self::ReplaceExisting,
            Self::ReplaceExisting => Self::GenerateButton,
            Self::GenerateButton => Self::PreviewButton,
            Self::PreviewButton => Self::Preview,
            Self::Preview => Self::CancelButton,
            Self::CancelButton => Self::LanguageSelector,
            // Generation workflow states don't participate in normal tab order
            Self::ConfirmGenerate => Self::ConfirmGenerate,
            Self::GenerationProgress => Self::GenerationProgress,
            Self::GenerationResults => Self::GenerationResults,
        }
    }

    /// Get previous focus in tab order
    pub fn previous(&self) -> Self {
        match self {
            Self::LanguageSelector => Self::CancelButton,
            Self::PageName => Self::LanguageSelector,
            Self::Template => Self::PageName,
            Self::Languages => Self::Template,
            Self::RoutePath => Self::Languages,
            Self::Priority => Self::RoutePath,
            Self::AutoScaffold => Self::Priority,
            Self::ReplaceExisting => Self::AutoScaffold,
            Self::GenerateButton => Self::ReplaceExisting,
            Self::PreviewButton => Self::GenerateButton,
            Self::Preview => Self::PreviewButton,
            Self::CancelButton => Self::Preview,
            // Generation workflow states don't participate in normal tab order
            Self::ConfirmGenerate => Self::ConfirmGenerate,
            Self::GenerationProgress => Self::GenerationProgress,
            Self::GenerationResults => Self::GenerationResults,
        }
    }
}

/// Input validation errors
#[derive(Debug, Clone)]
pub struct ValidationError {
    pub field: Focus,
    pub message: String,
}

/// Generation workflow state
#[derive(Debug, Clone)]
pub enum GenerationState {
    /// Normal form state
    Form,
    /// Showing confirmation dialog
    ConfirmDialog,
    /// Generating files with progress
    InProgress {
        current_step: String,
        completed_steps: usize,
        total_steps: usize,
        files_processed: Vec<String>,
    },
    /// Generation completed successfully
    Success {
        files_created: Vec<String>,
        files_updated: Vec<String>,
        generation_time: std::time::Duration,
    },
    /// Generation failed
    Error {
        error_message: String,
        files_rolled_back: Vec<String>,
    },
}

/// Main application state for the TUI
#[derive(Debug)]
pub struct App {
    /// Application mode (page manager vs create page)
    pub app_mode: AppMode,

    /// Current focus/active component
    pub focus: Focus,

    /// Page configuration (for create mode)
    pub page_name: String,
    pub selected_template: PageTemplate,
    pub available_languages: Vec<Language>,
    pub route_path: String,
    pub priority: f32,
    pub auto_scaffold: bool,
    pub replace_existing: bool,

    /// UI state
    pub should_quit: bool,
    pub show_help: bool,
    pub validation_errors: Vec<ValidationError>,

    /// Language selector state
    pub language_selection_index: usize,

    /// Route path manually edited flag
    pub route_manually_edited: bool,

    /// Preview pane state
    pub preview_tab: crate::manager::ui::preview::PreviewTab,

    /// Generation workflow state
    pub generation_state: GenerationState,

    /// Translations for UI text (labels, prompts, validation messages)
    pub translations: HashMap<String, String>,

    /// Translations for titles (changes with language selector)
    pub title_translations: HashMap<String, String>,

    /// Page manager
    pub page_manager: Option<PageManager>,

    /// Page manager state
    pub page_manager_state: Option<PageManagerState>,

    /// Modal dialog state
    pub modal_state: Option<ModalState>,

    /// Version control system
    pub version_control: Option<VersionControl>,

    /// Command template manager
    pub command_template_manager: Option<CommandTemplateManager>,

    /// Project root path
    pub project_root: std::path::PathBuf,

    /// Chat prompt interface
    pub chat_input: String,
    pub chat_focused: bool,
    pub chat_history: Vec<String>,
}

impl App {
    /// Create new app instance with default values
    pub fn new(
        project_root: std::path::PathBuf,
        translations: HashMap<String, String>,
    ) -> anyhow::Result<Self> {
        let available_languages = Self::discover_languages(&project_root)?;

        // Split translations into UI and title translations
        let mut ui_translations = HashMap::new();
        let mut title_translations = HashMap::new();

        for (key, value) in translations {
            if key.contains("title") || key.contains("name") {
                title_translations.insert(key, value);
            } else {
                ui_translations.insert(key, value);
            }
        }

        // Initialize page manager
        let page_manager = PageManager::new(project_root.clone()).ok();
        let page_manager_state = page_manager.as_ref().map(PageManagerState::new);

        // Initialize version control and command template manager
        let version_control = VersionControl::new(project_root.clone()).ok();
        let command_template_manager = CommandTemplateManager::new(project_root.clone()).ok();

        let mut app = Self {
            app_mode: AppMode::PageManager, // Start in page manager mode
            focus: Focus::PageName,
            page_name: String::new(),
            selected_template: PageTemplate::HeroPage,
            available_languages,
            route_path: String::new(),
            priority: 1.0,
            auto_scaffold: true,
            replace_existing: false,
            should_quit: false,
            show_help: false,
            validation_errors: Vec::new(),
            language_selection_index: 0,
            route_manually_edited: false,
            preview_tab: crate::manager::ui::preview::PreviewTab::FileList,
            generation_state: GenerationState::Form,
            translations: ui_translations,
            title_translations,
            page_manager,
            page_manager_state,
            modal_state: None,
            version_control,
            command_template_manager,
            project_root,
            chat_input: String::new(),
            chat_focused: false,
            chat_history: Vec::new(),
        };

        // Run initial validation
        app.update_validation();

        Ok(app)
    }

    /// Discover available languages from site/i18n/locales (new site structure)
    fn discover_languages(project_root: &std::path::Path) -> anyhow::Result<Vec<Language>> {
        use std::fs;

        // Use new site structure environment variables
        let site_root = std::env::var("SITE_ROOT_PATH").unwrap_or_else(|_| "site".to_string());
        let i18n_path =
            std::env::var("SITE_I18N_PATH").unwrap_or_else(|_| format!("{}/i18n", site_root));
        let locales_dir = project_root.join(&i18n_path).join("locales");

        let mut languages = Vec::new();

        if locales_dir.exists() {
            for entry in fs::read_dir(&locales_dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.is_dir() {
                    if let Some(dir_name) = path.file_name().and_then(|n| n.to_str()) {
                        // Validate language code format
                        if dir_name.len() >= 2
                            && dir_name.len() <= 5
                            && dir_name.chars().all(|c| c.is_alphanumeric() || c == '-')
                        {
                            let name = match dir_name {
                                "en" => "English",
                                "es" => "Spanish",
                                "fr" => "French",
                                "de" => "German",
                                "it" => "Italian",
                                "pt" => "Portuguese",
                                "ja" => "Japanese",
                                "zh" => "Chinese",
                                "ru" => "Russian",
                                code => code,
                            };

                            let mut lang = Language::new(dir_name.to_string(), name.to_string());
                            // Select English by default
                            if dir_name == "en" {
                                lang.selected = true;
                            }
                            languages.push(lang);
                        }
                    }
                }
            }
        }

        // Sort languages with English first
        languages.sort_by(|a, b| {
            if a.code == "en" {
                std::cmp::Ordering::Less
            } else if b.code == "en" {
                std::cmp::Ordering::Greater
            } else {
                a.name.cmp(&b.name)
            }
        });

        // Ensure we have at least English as fallback
        if languages.is_empty() {
            languages.push(Language {
                code: "en".to_string(),
                name: "English".to_string(),
                selected: true,
            });
        }

        Ok(languages)
    }

    /// Move focus to next component
    pub fn next_focus(&mut self) {
        self.focus = self.focus.next();
    }

    /// Move focus to previous component
    pub fn previous_focus(&mut self) {
        self.focus = self.focus.previous();
    }

    /// Move to next language in the list
    pub fn next_language(&mut self) {
        if !self.available_languages.is_empty() {
            self.language_selection_index =
                (self.language_selection_index + 1) % self.available_languages.len();
        }
    }

    /// Move to previous language in the list
    pub fn previous_language(&mut self) {
        if !self.available_languages.is_empty() {
            self.language_selection_index = if self.language_selection_index == 0 {
                self.available_languages.len() - 1
            } else {
                self.language_selection_index - 1
            };
        }
    }

    /// Toggle currently highlighted language
    pub fn toggle_current_language(&mut self) {
        if let Some(lang) = self
            .available_languages
            .get_mut(self.language_selection_index)
        {
            lang.selected = !lang.selected;
            self.update_validation();
        }
    }

    /// Toggle language selection by index (for compatibility)
    pub fn toggle_language(&mut self, index: usize) {
        if let Some(lang) = self.available_languages.get_mut(index) {
            lang.selected = !lang.selected;
            self.update_validation();
        }
    }

    /// Set selected template
    pub fn set_template(&mut self, template: PageTemplate) {
        self.selected_template = template;
        self.update_route_from_name();
        self.update_validation();
    }

    /// Update page name and auto-update route path (only if not manually
    /// edited)
    pub fn update_page_name(&mut self, name: String) {
        self.page_name = name;
        if !self.route_manually_edited {
            self.update_route_from_name();
        }
        self.update_validation();
    }

    /// Auto-generate route path from page name
    fn update_route_from_name(&mut self) {
        if !self.page_name.is_empty() {
            // Convert PascalCase to kebab-case
            let mut route = String::new();
            let mut prev_was_lower = false;

            for ch in self.page_name.chars() {
                if ch.is_uppercase() && prev_was_lower {
                    route.push('-');
                }
                route.push(ch.to_lowercase().next().unwrap_or(ch));
                prev_was_lower = ch.is_lowercase();
            }

            // Ensure starts with /
            if !route.starts_with('/') {
                route = format!("/{}", route);
            }

            self.route_path = route;
        }
    }

    /// Update route path manually
    pub fn update_route_path(&mut self, path: String) {
        self.route_path = path;
        self.route_manually_edited = true; // Mark as manually edited
        self.update_validation();
    }

    /// Update priority value
    pub fn update_priority(&mut self, priority: f32) {
        self.priority = priority.clamp(0.1, 10.0);
        self.update_validation();
    }

    /// Toggle auto-scaffold option
    pub fn toggle_auto_scaffold(&mut self) {
        self.auto_scaffold = !self.auto_scaffold;
    }

    /// Toggle replace existing option
    pub fn toggle_replace_existing(&mut self) {
        self.replace_existing = !self.replace_existing;
    }

    /// Update validation errors based on current state
    fn update_validation(&mut self) {
        self.validation_errors.clear();

        // Page name validation
        if self.page_name.is_empty() {
            self.validation_errors.push(ValidationError {
                field: Focus::PageName,
                message: self.get_translation("mgr-validation-name-empty"),
            });
        } else if !self.page_name.chars().next().unwrap_or('a').is_uppercase() {
            self.validation_errors.push(ValidationError {
                field: Focus::PageName,
                message: self.get_translation("mgr-validation-name-case"),
            });
        } else if !self.page_name.chars().all(|c| c.is_alphanumeric()) {
            self.validation_errors.push(ValidationError {
                field: Focus::PageName,
                message: self.get_translation("mgr-validation-name-chars"),
            });
        } else if self.page_name.len() > 50 {
            self.validation_errors.push(ValidationError {
                field: Focus::PageName,
                message: self.get_translation("mgr-validation-name-length"),
            });
        }

        // Route path validation
        if self.route_path.is_empty() {
            self.validation_errors.push(ValidationError {
                field: Focus::RoutePath,
                message: self.get_translation("mgr-validation-path-empty"),
            });
        } else if !self.route_path.starts_with('/') {
            self.validation_errors.push(ValidationError {
                field: Focus::RoutePath,
                message: self.get_translation("mgr-validation-path-start"),
            });
        } else if self.route_path != "/" && self.route_path.ends_with('/') {
            self.validation_errors.push(ValidationError {
                field: Focus::RoutePath,
                message: self.get_translation("mgr-validation-path-end"),
            });
        }

        // Language selection validation
        if !self.available_languages.iter().any(|lang| lang.selected) {
            self.validation_errors.push(ValidationError {
                field: Focus::Languages,
                message: self.get_translation("mgr-error-at-least-one-language"),
            });
        }
    }

    /// Get translation with fallback to key name
    fn get_translation(&self, key: &str) -> String {
        // Check title translations first, then UI translations
        self.title_translations
            .get(key)
            .or_else(|| self.translations.get(key))
            .cloned()
            .unwrap_or_else(|| key.to_string())
    }

    /// Check if current configuration is valid for generation
    pub fn is_valid(&self) -> bool {
        self.validation_errors.is_empty()
    }

    /// Get list of selected languages
    pub fn selected_languages(&self) -> Vec<String> {
        self.available_languages
            .iter()
            .filter(|lang| lang.selected)
            .map(|lang| lang.code.clone())
            .collect()
    }

    /// Navigate to previous language in selector
    pub fn previous_language_selection(&mut self) {
        if self.available_languages.is_empty() {
            return;
        }
        if self.language_selection_index == 0 {
            self.language_selection_index = self.available_languages.len() - 1;
        } else {
            self.language_selection_index = self.language_selection_index.saturating_sub(1);
        }

        // Update title translations for the new language
        if let Err(e) = self.update_title_translations() {
            // If translation loading fails, keep current translations
            eprintln!("Warning: Failed to load title translations: {}", e);
        }
    }

    /// Navigate to next language in selector
    pub fn next_language_selection(&mut self) {
        if self.available_languages.is_empty() {
            return;
        }
        self.language_selection_index =
            (self.language_selection_index + 1) % self.available_languages.len();

        // Update title translations for the new language
        if let Err(e) = self.update_title_translations() {
            // If translation loading fails, keep current translations
            eprintln!("Warning: Failed to load title translations: {}", e);
        }
    }

    /// Update title translations based on current language selection
    fn update_title_translations(&mut self) -> anyhow::Result<()> {
        if let Some(selected_lang) = self.available_languages.get(self.language_selection_index) {
            let new_title_translations = self.load_title_translations(&selected_lang.code)?;
            self.title_translations = new_title_translations;
        }
        Ok(())
    }

    /// Load only title-related translations for a specific language
    fn load_title_translations(&self, _lang: &str) -> anyhow::Result<HashMap<String, String>> {
        // TODO: Implement proper FTL translations loading when LanguageRegistry
        // supports it For now, return empty HashMap to prevent compilation
        // errors
        let _lang_registry = rustelo_core_types::i18n::LanguageRegistry::new();
        Ok(HashMap::new())
    }

    /// Show/hide help overlay
    pub fn toggle_help(&mut self) {
        self.show_help = !self.show_help;
    }

    /// Mark app for shutdown
    pub fn quit(&mut self) {
        self.should_quit = true;
    }

    /// Switch to page manager mode
    pub fn switch_to_page_manager(&mut self) {
        self.app_mode = AppMode::PageManager;
        if let Some(page_manager) = &self.page_manager {
            if let Some(state) = &mut self.page_manager_state {
                state.refresh_pages(page_manager);
            }
        }
    }

    /// Switch to create page mode
    pub fn switch_to_create_page(&mut self) {
        self.app_mode = AppMode::CreatePage;
        self.focus = Focus::PageName;
        // Reset form state
        self.page_name.clear();
        self.route_path.clear();
        self.route_manually_edited = false;
        self.generation_state = GenerationState::Form;
        self.validation_errors.clear();
    }

    /// Refresh page manager data
    pub fn refresh_page_manager(&mut self) -> anyhow::Result<()> {
        if let Some(page_manager) = &mut self.page_manager {
            page_manager.refresh()?;
            if let Some(state) = &mut self.page_manager_state {
                state.refresh_pages(page_manager);
            }
        }
        Ok(())
    }

    /// Show modal dialog
    pub fn show_modal(&mut self, modal_type: ModalType, title: String, message: String) {
        self.modal_state = Some(ModalState::new(modal_type, title, message));
    }

    /// Close modal dialog
    pub fn close_modal(&mut self) {
        self.modal_state = None;
    }

    /// Show save template modal
    pub fn show_save_template_modal(&mut self) {
        let title = self.get_translation("mgr-save-template-title");
        let message = self.get_translation("mgr-save-template-message");
        let mut modal_state = ModalState::new(ModalType::SaveTemplate, title, message).with_input();
        modal_state.input_text = format!("{}_template", self.page_name.to_lowercase());
        self.modal_state = Some(modal_state);
    }

    /// Show load template modal
    pub fn show_load_template_modal(&mut self) {
        let title = self.get_translation("mgr-load-template-title");
        let message = self.get_translation("mgr-load-template-message");

        // Load available templates
        let templates = if let Some(tm) = &self.command_template_manager {
            tm.list_templates().unwrap_or_else(|_| Vec::new())
        } else {
            Vec::new()
        };

        let modal_state =
            ModalState::new(ModalType::LoadTemplate, title, message).with_items(templates);
        self.modal_state = Some(modal_state);
    }

    /// Show backup list modal
    pub fn show_backup_list_modal(&mut self, page_name: Option<&str>) {
        let title = self.get_translation("mgr-backup-list-title");
        let message = self.get_translation("mgr-backup-list-message");

        // Load available backups
        let backups = if let Some(vc) = &self.version_control {
            vc.list_backups(page_name)
                .unwrap_or_else(|_| Vec::new())
                .into_iter()
                .map(|b| {
                    format!(
                        "{} - {} ({})",
                        b.page_name,
                        b.timestamp.format("%Y-%m-%d %H:%M"),
                        b.description
                    )
                })
                .collect()
        } else {
            Vec::new()
        };

        let modal_state =
            ModalState::new(ModalType::BackupList, title, message).with_items(backups);
        self.modal_state = Some(modal_state);
    }

    /// Create backup for current page
    pub fn create_backup(
        &mut self,
        page_name: &str,
        description: Option<&str>,
    ) -> anyhow::Result<()> {
        if let Some(vc) = &self.version_control {
            if let Some(page_manager) = &self.page_manager {
                let files = page_manager.get_editable_files(page_name, true);
                let backup_info = vc.create_backup(page_name, &files, description)?;

                // Show confirmation
                let title = self.get_translation("mgr-backup-created-title");
                let message = format!("Backup created: {}", backup_info.tar_file);
                self.show_modal(ModalType::ConfirmAction, title, message);
            }
        }
        Ok(())
    }

    /// Save current settings as command template
    pub fn save_command_template(&mut self, template_name: &str) -> anyhow::Result<()> {
        if let Some(tm) = &self.command_template_manager {
            use chrono::Utc;

            use crate::manager::version_control::CommandTemplate;

            let template = CommandTemplate {
                name: template_name.to_string(),
                description: format!("Template for {}", self.page_name),
                timestamp: Utc::now(),
                page_name: self.page_name.clone(),
                template: format!("{:?}", self.selected_template).to_lowercase(),
                languages: self.selected_languages(),
                route_path: self.route_path.clone(),
                priority: self.priority,
                auto_scaffold: self.auto_scaffold,
                replace_existing: self.replace_existing,
                extra_flags: HashMap::new(),
            };

            tm.save_template(&template)?;

            // Show confirmation
            let title = self.get_translation("mgr-template-saved-title");
            let message = format!("Template saved: {}", template_name);
            self.show_modal(ModalType::ConfirmAction, title, message);
        }
        Ok(())
    }

    /// Load command template
    pub fn load_command_template(&mut self, template_name: &str) -> anyhow::Result<()> {
        if let Some(tm) = &self.command_template_manager {
            let template = tm.load_template(template_name)?;

            // Apply template to current settings
            self.page_name = template.page_name;
            self.route_path = template.route_path;
            self.priority = template.priority;
            self.auto_scaffold = template.auto_scaffold;
            self.replace_existing = template.replace_existing;

            // Update selected languages
            for lang in &mut self.available_languages {
                lang.selected = template.languages.contains(&lang.code);
            }

            // Parse template type
            let template_type = template.template.clone();
            match template_type.as_str() {
                "hero_page" => self.selected_template = PageTemplate::HeroPage,
                "form_page" => self.selected_template = PageTemplate::FormPage,
                "content_list" => self.selected_template = PageTemplate::ContentList,
                _ => self.selected_template = PageTemplate::BasicPage,
            }

            // Update route if not manually edited
            if !self.route_manually_edited {
                self.update_route_from_name();
            }

            // Show confirmation
            let title = self.get_translation("mgr-template-loaded-title");
            let message = format!("Template loaded: {}", template_name);
            self.show_modal(ModalType::ConfirmAction, title, message);
        }
        Ok(())
    }

    /// Move to next preview tab
    pub fn next_preview_tab(&mut self) {
        use crate::manager::ui::preview::PreviewTab;
        self.preview_tab = match self.preview_tab {
            PreviewTab::FileList => PreviewTab::RouteConfig,
            PreviewTab::RouteConfig => PreviewTab::Component,
            PreviewTab::Component => PreviewTab::Translations,
            PreviewTab::Translations => PreviewTab::FileList,
        };
    }

    /// Move to previous preview tab
    pub fn previous_preview_tab(&mut self) {
        use crate::manager::ui::preview::PreviewTab;
        self.preview_tab = match self.preview_tab {
            PreviewTab::FileList => PreviewTab::Translations,
            PreviewTab::RouteConfig => PreviewTab::FileList,
            PreviewTab::Component => PreviewTab::RouteConfig,
            PreviewTab::Translations => PreviewTab::Component,
        };
    }

    /// Start generation confirmation dialog
    pub fn start_generation_confirmation(&mut self) {
        self.generation_state = GenerationState::ConfirmDialog;
        self.focus = Focus::ConfirmGenerate;
    }

    /// Cancel generation and return to form
    pub fn cancel_generation(&mut self) {
        self.generation_state = GenerationState::Form;
        self.focus = Focus::GenerateButton;
    }

    /// Start generation progress
    pub fn start_generation(&mut self, total_steps: usize) {
        self.generation_state = GenerationState::InProgress {
            current_step: "Initializing...".to_string(),
            completed_steps: 0,
            total_steps,
            files_processed: Vec::new(),
        };
        self.focus = Focus::GenerationProgress;
    }

    /// Update generation progress
    pub fn update_generation_progress(&mut self, step: String, file_processed: Option<String>) {
        if let GenerationState::InProgress {
            current_step,
            completed_steps,
            total_steps: _,
            files_processed,
        } = &mut self.generation_state
        {
            *current_step = step;
            *completed_steps += 1;
            if let Some(file) = file_processed {
                files_processed.push(file);
            }
        }
    }

    /// Complete generation successfully
    pub fn complete_generation(
        &mut self,
        files_created: Vec<String>,
        files_updated: Vec<String>,
        duration: std::time::Duration,
    ) {
        self.generation_state = GenerationState::Success {
            files_created,
            files_updated,
            generation_time: duration,
        };
        self.focus = Focus::GenerationResults;
    }

    /// Fail generation with error
    pub fn fail_generation(&mut self, error: String, rolled_back_files: Vec<String>) {
        self.generation_state = GenerationState::Error {
            error_message: error,
            files_rolled_back: rolled_back_files,
        };
        self.focus = Focus::GenerationResults;
    }

    /// Toggle chat input focus
    pub fn toggle_chat_focus(&mut self) {
        self.chat_focused = !self.chat_focused;
    }

    /// Add character to chat input
    pub fn chat_input_char(&mut self, c: char) {
        if self.chat_focused {
            self.chat_input.push(c);
        }
    }

    /// Remove last character from chat input
    pub fn chat_backspace(&mut self) {
        if self.chat_focused {
            self.chat_input.pop();
        }
    }

    /// Submit chat input and add to history
    pub fn submit_chat(&mut self) -> String {
        let input = self.chat_input.clone();
        if !input.trim().is_empty() {
            self.chat_history.push(input.clone());
            self.chat_input.clear();
        }
        input
    }
}
