//! File editor state management
//!
//! Manages the state for editable file tabs using iced-code-editor.

use std::path::PathBuf;

use iced_code_editor::CodeEditor;

/// Create a custom theme matching our Aubergine/Gold color scheme
fn create_storybook_theme() -> iced_code_editor::Style {
    use crate::theme::*;

    iced_code_editor::Style {
        background: Aubergine::_900,
        text_color: Neutral::CREAM,
        gutter_background: Aubergine::_800,
        gutter_border: Aubergine::_700,
        line_number_color: Neutral::WARM_GRAY_400,
        scrollbar_background: Aubergine::_700,
        scroller_color: Gold::_500,
        current_line_highlight: Aubergine::_700,
    }
}

/// State for an editable file tab
pub struct FileEditorState {
    /// Path to the file
    pub path: PathBuf,

    /// Code editor instance with syntax highlighting and line numbers
    pub editor: CodeEditor,
}

impl std::fmt::Debug for FileEditorState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FileEditorState")
            .field("path", &self.path)
            .field("editor", &"<CodeEditor>")
            .finish()
    }
}

impl FileEditorState {
    /// Create a new file editor state from a path and initial content
    pub fn new(path: PathBuf, initial_content: String) -> Self {
        // Detect language from file extension
        let language = path
            .extension()
            .and_then(|ext| ext.to_str())
            .map(|ext| {
                // Map .sb extension to "storybook"
                if ext == "sb" || ext == "storybook" {
                    "storybook"
                } else {
                    ext
                }
            })
            .unwrap_or("txt");

        // Create code editor with syntax highlighting
        let mut editor = CodeEditor::new(&initial_content, language);

        // Enable line numbers
        editor.set_line_numbers_enabled(true);

        // Set custom theme to match our Aubergine/Gold color scheme
        let custom_theme = create_storybook_theme();
        editor.set_theme(custom_theme);

        Self { path, editor }
    }

    /// Get the current text content as a string
    pub fn text(&self) -> String {
        self.editor.content()
    }

    /// Get the filename for display
    pub fn filename(&self) -> String {
        self.path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .to_string()
    }
}
