//! Content Loading Module for PostViewer
//!
//! Handles all content loading operations using the unified ContentLoader trait.
//! Supports both SSR and WASM environments with appropriate fallbacks.

use rustelo_core_lib::content::UnifiedContentItem;
use rustelo_core_lib::fluent::{
    ContentLoadError, ContentLoader, ContentResult, PathResolvingContentLoader,
    StandardContentLoader,
};

#[cfg(target_arch = "wasm32")]
use rustelo_core_lib::fluent::AsyncContentLoader;

/// Content loading context for post viewer components
pub struct PostViewerContentLoader {
    inner: StandardContentLoader,
}

impl PostViewerContentLoader {
    pub fn new() -> Self {
        Self {
            inner: StandardContentLoader,
        }
    }

    /// Load content synchronously for both SSR and WASM contexts
    pub fn load_content_sync(
        &self,
        slug: &str,
        language: &str,
        content_type: &str,
    ) -> Result<(String, String, String), String> {
        #[cfg(target_arch = "wasm32")]
        {
            // For WASM/client-side, use the embedded content resources
            match self.inner.load_index(content_type, language) {
                Ok(index) => {
                    if let Some(item) = index.items.iter().find(|item| item.slug == slug) {
                        let title = item.title.clone();
                        let subtitle = item.excerpt.clone().unwrap_or_default();

                        // For WASM, we return a placeholder since async loading is handled separately
                        let content_html = "<div class='text-center py-4 text-gray-600'>Content loading handled by main component...</div>".to_string();

                        web_sys::console::log_1(
                            &format!(
                                "✅ WASM: Prepared content info for slug '{}': title='{}'",
                                slug, title
                            )
                            .into(),
                        );

                        Ok((title, subtitle, content_html))
                    } else {
                        web_sys::console::error_1(
                            &format!(
                                "❌ Content item not found for slug '{}' in {} index",
                                slug, content_type
                            )
                            .into(),
                        );
                        Err(format!("Content item not found for slug '{}'", slug))
                    }
                }
                Err(e) => {
                    web_sys::console::error_1(
                        &format!(
                            "❌ Failed to load content index for {}/{}: {}",
                            content_type, language, e
                        )
                        .into(),
                    );
                    Err(format!("Failed to load content index: {}", e))
                }
            }
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            // For server-side, use the existing markdown processing
            match self.inner.load_markdown(content_type, language, slug) {
                Ok(markdown_content) => match self.inner.process_markdown(&markdown_content) {
                    Ok((metadata, html)) => {
                        let title = metadata.title.unwrap_or_else(|| {
                            slug.replace('-', " ")
                                .split_whitespace()
                                .map(|word| {
                                    let mut chars = word.chars();
                                    match chars.next() {
                                        None => String::new(),
                                        Some(first) => {
                                            first.to_uppercase().collect::<String>()
                                                + &chars.collect::<String>().to_lowercase()
                                        }
                                    }
                                })
                                .collect::<Vec<_>>()
                                .join(" ")
                        });
                        Ok((title, metadata.subtitle.unwrap_or_default(), html))
                    }
                    Err(e) => Err(format!(
                        "Failed to process {} markdown: {}",
                        content_type, e
                    )),
                },
                Err(e) => Err(format!("Failed to load {} content: {}", content_type, e)),
            }
        }
    }

    /// Map SEO-friendly URL slugs to actual content IDs
    pub fn resolve_url_slug(&self, url_slug: &str, content_type: &str, language: &str) -> String {
        self.inner.resolve_slug(url_slug, content_type, language)
    }

    /// Get HTML path for content item with category support
    pub fn get_html_path(
        &self,
        content_type: &str,
        language: &str,
        item: &UnifiedContentItem,
        category_from_path: Option<&str>,
    ) -> String {
        self.inner
            .get_html_path_with_category(content_type, language, item, category_from_path)
    }

    /// Load content index for finding items
    pub fn load_content_index(
        &self,
        content_type: &str,
        language: &str,
    ) -> ContentResult<Vec<UnifiedContentItem>> {
        self.inner
            .load_index(content_type, language)
            .map(|index| index.items)
    }
}

impl Default for PostViewerContentLoader {
    fn default() -> Self {
        Self::new()
    }
}

/// Async content loading operations for WASM contexts
#[cfg(target_arch = "wasm32")]
impl PostViewerContentLoader {
    /// Load HTML content from URL asynchronously
    pub async fn load_html_content(&self, path: &str) -> Result<String, String> {
        match self.inner.load_html_content(path).await {
            Ok(content) => Ok(content),
            Err(e) => Err(e.to_string()),
        }
    }
}

/// Content item finder utility
pub struct ContentItemFinder {
    loader: PostViewerContentLoader,
}

impl ContentItemFinder {
    pub fn new() -> Self {
        Self {
            loader: PostViewerContentLoader::new(),
        }
    }

    /// Find content item by slug with proper error handling
    pub fn find_item(
        &self,
        content_type: &str,
        language: &str,
        slug: &str,
    ) -> Result<UnifiedContentItem, ContentLoadError> {
        let items = self.loader.load_content_index(content_type, language)?;
        items
            .into_iter()
            .find(|item| item.slug == slug)
            .ok_or_else(|| {
                ContentLoadError::NotFound(format!("{}:{}:{}", content_type, language, slug))
            })
    }

    /// Find item and generate its HTML path
    pub fn find_item_with_path(
        &self,
        content_type: &str,
        language: &str,
        slug: &str,
        category_from_path: Option<&str>,
    ) -> Result<(UnifiedContentItem, String), ContentLoadError> {
        let item = self.find_item(content_type, language, slug)?;
        let html_path =
            self.loader
                .get_html_path(content_type, language, &item, category_from_path);
        Ok((item, html_path))
    }
}

impl Default for ContentItemFinder {
    fn default() -> Self {
        Self::new()
    }
}
