//! SSR PostViewer Page Component using actual markdown content loading

use leptos::prelude::*;
use rustelo_core_lib::{
    config::get_default_language,
    fluent::{load_content_by_slug, process_markdown_file, rewrite_content_image_paths},
    i18n::{build_page_content_patterns, SsrTranslator},
};

#[component]
pub fn PostViewerPageSSR(
    #[prop(default = get_default_language().to_string())] _language: String,
    #[prop(default = "".to_string())] slug: String,
    #[prop(default = "content".to_string())] content_type: String,
    #[prop(default = true)] show_author: bool,
    #[prop(default = true)] show_date: bool,
    #[prop(default = true)] show_tags: bool,
    #[prop(default = false)] show_related_posts: bool,
    #[prop(default = false)] enable_comments: bool,
    #[prop(default = false)] enable_social_sharing: bool,
) -> impl IntoView {
    tracing::info!(
        "SSR: PostViewerPageSSR called with language: '{:?}', slug: {:?}, content_type: '{}'",
        _language,
        slug,
        content_type
    );
    let lang = _language.clone();
    let ssr_i18n = SsrTranslator::new(_language.clone());
    let content = {
        let mut content = {
            // Build patterns dynamically based on available content types
            let patterns = vec!["post-viewer-"];
            let available_types = rustelo_core_lib::get_all_content_types();
            let mut dynamic_patterns = Vec::new();
            for content_type in &available_types {
                dynamic_patterns.push(format!("{}-", content_type));
            }
            // Add dynamic patterns to base patterns
            let mut all_patterns = patterns;
            for pattern in &dynamic_patterns {
                all_patterns.push(pattern);
            }
            build_page_content_patterns(&ssr_i18n, &all_patterns)
        };
        // For SSR, if we have a slug, try to load the actual content
        if !slug.is_empty() {
            tracing::info!("SSR: Loading content for slug: '{}'", slug);

            // Use the content_type passed from routing
            let content_type_ref = &content_type;

            tracing::info!(
                "SSR: Using content type from routing - content_type: '{}'",
                content_type
            );

            // Try to load and process the markdown content using shared infrastructure
            {
                tracing::info!("SSR: Loading {} content for slug: '{}'", content_type, slug);
                let content_result = load_content_by_slug(&slug, &content_type, &lang);

                match content_result {
                    Ok(markdown_content) => {
                        // Process the markdown to extract metadata and HTML
                        match process_markdown_file(&markdown_content) {
                            Ok((metadata, html)) => {
                                // Use metadata title if available, otherwise use slug
                                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(" ")
                                });

                                content.insert("post-title".to_string(), title);
                                content.insert(
                                    "post-subtitle".to_string(),
                                    metadata.subtitle.unwrap_or_default(),
                                );
                                let html =
                                    rewrite_content_image_paths(&html, &content_type, &lang, &slug);
                                content.insert("post-content".to_string(), html);
                                if let Some(author) = metadata.author {
                                    content.insert("post-author".to_string(), author);
                                }
                                if let Some(date) = metadata.date {
                                    content.insert("post-date".to_string(), date);
                                }
                                if !metadata.tags.is_empty() {
                                    content
                                        .insert("post-tags".to_string(), metadata.tags.join(", "));
                                }

                                tracing::info!(
                                    "SSR: Successfully loaded {} content: {}",
                                    content_type_ref,
                                    slug
                                );
                            }
                            Err(e) => {
                                tracing::error!(
                                    "SSR: Failed to process markdown for {}: {}",
                                    slug,
                                    e
                                );
                                content
                                    .insert("post-title".to_string(), format!("Error: {}", slug));
                                content.insert(
                                    "post-content".to_string(),
                                    "Failed to process content.".to_string(),
                                );
                            }
                        }
                    }
                    Err(e) => {
                        tracing::error!(
                            "SSR: Failed to load {} content {}: {}",
                            content_type_ref,
                            slug,
                            e
                        );
                        content.insert("post-title".to_string(), format!("Not Found: {}", slug));
                        content.insert(
                            "post-content".to_string(),
                            "Post content could not be loaded.".to_string(),
                        );
                    }
                }
            }
        }
        content
    };

    view! {
      <crate::post_viewer::unified::UnifiedPostViewerPage
        _language=_language
        lang_content=content
        slug=slug
        content_type=content_type.clone()
        show_author=show_author
        show_date=show_date
        show_tags=show_tags
        show_related_posts=show_related_posts
        enable_comments=enable_comments
        enable_social_sharing=enable_social_sharing
      />
    }
}
