//! Refactored Client-side PostViewer page component
//!
//! Uses modular components and unified ContentLoader trait for better code organization.

use crate::common::use_page_i18n_dynamic;
#[cfg(all(target_arch = "wasm32", not(feature = "ssr")))]
use crate::post_viewer::html_generator::{AsyncContentUpdater, ContentTemplates, DomUtils};
use crate::post_viewer::{content_loader::PostViewerContentLoader, path_resolver::PathResolver};
use leptos::prelude::*;
use reactive_graph::traits::Get;
use rustelo_core_lib::{config::get_default_language, state::use_language};

/// Client-side reactive PostViewer page component for any content type
#[component]
pub fn PostViewerPageClient(
    #[allow(unused_variables)]
    #[prop(default = get_default_language().to_string())]
    _language: String,
    #[prop(default = "".to_string())] slug: String,
    #[prop(default = "content".to_string())] content_type: String,
) -> impl IntoView {
    // Get language context outside the memo to ensure we track the same instance
    let language_context = use_language();
    // Try to get path signal but don't panic if not available
    let current_path = use_context::<ReadSignal<String>>();

    // Extract slug and category from props or path, use content_type prop directly
    let content_info = Memo::new(move |_| {
        // Always extract from path to get both slug and category
        let (slug, category) = current_path
            .and_then(|path_signal| {
                let path = path_signal.get();
                #[cfg(target_arch = "wasm32")]
                web_sys::console::log_1(
                    &format!("🐛 CLIENT: Extracting from path: '{}'", path).into(),
                );
                let params = PathResolver::extract_parameters(&path);
                #[cfg(target_arch = "wasm32")]
                web_sys::console::log_1(
                    &format!(
                        "🐛 CLIENT: Extracted - slug: {:?}, category: {:?}",
                        params.slug, params.category
                    )
                    .into(),
                );
                Some((params.slug, params.category))
            })
            .unwrap_or_else(|| {
                #[cfg(target_arch = "wasm32")]
                web_sys::console::log_1(
                    &format!("🐛 CLIENT: No current_path context, trying window.location").into(),
                );

                // Try to get path from window.location as fallback
                #[cfg(target_arch = "wasm32")]
                if let Some(window) = web_sys::window() {
                    if let Some(location) = window.location().pathname().ok() {
                        web_sys::console::log_1(
                            &format!("🐛 CLIENT: Got location.pathname: '{}'", location).into(),
                        );
                        let params = PathResolver::extract_parameters(&location);
                        web_sys::console::log_1(
                            &format!(
                                "🐛 CLIENT: Location extracted - slug: {:?}, category: {:?}",
                                params.slug, params.category
                            )
                            .into(),
                        );
                        return (params.slug, params.category);
                    }
                }

                #[cfg(target_arch = "wasm32")]
                web_sys::console::log_1(
                    &format!("🐛 CLIENT: Final fallback - using slug prop: {:?}", slug).into(),
                );
                // Final fallback: if no path, use slug prop but category will be None
                (Some(slug.clone()), None)
            });
        // Use the content_type prop passed from routing instead of detecting from path
        (slug, category, content_type.clone())
    });

    // Create content loader instances for each closure
    let _content_memo = Memo::new({
        let current_language = language_context.current;
        let content_info = content_info.clone();

        move |_| {
            let content_loader = PostViewerContentLoader::new();
            let language = current_language.get();
            let (slug_opt, _category_opt, content_type) = content_info.get();

            #[cfg(target_arch = "wasm32")]
            DomUtils::console_log(&format!(
                "🔄 Content memo triggered - Language: '{}', Slug: {:?}, Type: '{}'",
                language, slug_opt, content_type
            ));

            match slug_opt {
                Some(url_slug) => {
                    // Map the URL slug to the actual content ID
                    let content_id =
                        content_loader.resolve_url_slug(&url_slug, &content_type, &language);

                    #[cfg(target_arch = "wasm32")]
                    DomUtils::console_log(&format!(
                        "🔄 Loading {} content: URL slug='{}' -> Content ID='{}', language='{}'",
                        content_type, url_slug, content_id, &language
                    ));

                    content_loader.load_content_sync(&content_id, &language, &content_type)
                }
                None => {
                    #[cfg(target_arch = "wasm32")]
                    DomUtils::console_warn("⚠️ No slug provided for content loading");
                    Err("No slug provided".to_string())
                }
            }
        }
    });

    // Create a reactive page content memo using the new helper
    let base_page_content = use_page_i18n_dynamic(vec!["post-viewer-"], || {
        rustelo_core_lib::get_all_content_types()
            .iter()
            .map(|content_type| format!("{}-", content_type))
            .collect()
    });

    // WASM content component with proper async loading
    #[cfg(target_arch = "wasm32")]
    let content_component = move || {
        let content_loader = PostViewerContentLoader::new();
        let current_language = language_context.current.get();
        let base_content = base_page_content.get();
        let (slug_opt, category_opt, content_type) = content_info.get();

        match slug_opt {
            Some(url_slug) => {
                let content_id =
                    content_loader.resolve_url_slug(&url_slug, &content_type, &current_language);

                match content_loader.load_content_index(&content_type, &current_language) {
                    Ok(items) => {
                        if let Some(item) = items.iter().find(|item| item.slug == content_id) {
                            #[cfg(target_arch = "wasm32")]
                            web_sys::console::log_1(
                                &format!(
                                    "🐛 CLIENT: About to call get_html_path with category: {:?}",
                                    category_opt
                                )
                                .into(),
                            );
                            let html_path = content_loader.get_html_path(
                                &content_type,
                                &current_language,
                                item,
                                category_opt.as_deref(),
                            );
                            #[cfg(target_arch = "wasm32")]
                            web_sys::console::log_1(
                                &format!("🐛 CLIENT: Generated html_path: '{}'", html_path).into(),
                            );
                            let _item_clone = item.clone();

                            // Create content with loading placeholder
                            let final_content = ContentTemplates::loading_with_item(
                                base_content,
                                item.title.clone(),
                                item.excerpt.clone().unwrap_or_default(),
                            );

                            // Show title section during loading
                            DomUtils::toggle_title_section(true);

                            // Trigger async content loading after component mounts (client-side only)
                            #[cfg(all(target_arch = "wasm32", not(feature = "ssr")))]
                            {
                                let path_for_effect = html_path.clone();
                                Effect::new(move |_| {
                                    // Double-check we're actually on the client side
                                    if !cfg!(target_arch = "wasm32") {
                                        return;
                                    }

                                    let path = path_for_effect.clone();
                                    wasm_bindgen_futures::spawn_local(
                                        AsyncContentUpdater::update_with_html_fetch(path),
                                    );
                                });
                            }

                            view! {
                                <crate::post_viewer::unified::UnifiedPostViewerPage
                                    _language=current_language.clone()
                                    lang_content=final_content
                                />
                            }
                            .into_any()
                        } else {
                            let error_content = ContentTemplates::content_not_found(base_content);

                            view! {
                                <crate::post_viewer::unified::UnifiedPostViewerPage
                                    _language=current_language.clone()
                                    lang_content=error_content
                                />
                            }
                            .into_any()
                        }
                    }
                    Err(_) => {
                        let error_content = ContentTemplates::index_error(base_content);

                        view! {
                            <crate::post_viewer::unified::UnifiedPostViewerPage
                                _language=current_language.clone()
                                lang_content=error_content
                            />
                        }
                        .into_any()
                    }
                }
            }
            None => {
                let error_content = ContentTemplates::no_slug(base_content);

                view! {
                    <crate::post_viewer::unified::UnifiedPostViewerPage
                        _language=current_language.clone()
                        lang_content=error_content
                    />
                }
                .into_any()
            }
        }
    };

    // SSR version with original logic for server-side rendering
    #[cfg(not(target_arch = "wasm32"))]
    let content_component = move || {
        // Enhance the base content with loaded post data
        let page_content = Memo::new({
            let base_page_content = base_page_content.clone();
            let _content_memo = _content_memo.clone();

            move |_| {
                let mut final_content = base_page_content.get();

                // For hydration compatibility, render the same loading placeholder as WASM initially
                match _content_memo.get() {
                    Ok((title, subtitle, _html_content)) => {
                        final_content.insert("post-title".to_string(), title);
                        final_content.insert("post-subtitle".to_string(), subtitle);
                        // Insert the same loading placeholder as WASM for hydration compatibility
                        final_content.insert(
                            "post-content".to_string(),
                            crate::post_viewer::html_generator::HtmlProcessor::create_loading_placeholder(),
                        );
                    }
                    Err(e) => {
                        let error_content =
                            crate::post_viewer::html_generator::HtmlProcessor::create_error_content(
                                "Content Not Available",
                                "We couldn't load the requested content",
                                Some(&e),
                            );

                        final_content
                            .insert("post-title".to_string(), "Content Not Found".to_string());
                        final_content.insert(
                            "post-subtitle".to_string(),
                            "We couldn't load the requested content".to_string(),
                        );
                        final_content.insert("post-content".to_string(), error_content);
                    }
                }

                final_content
            }
        });

        let current_language = language_context.current.get();
        let (slug_opt, _category_opt, content_type_current) = content_info.get();
        view! {
            <crate::post_viewer::unified::UnifiedPostViewerPage
                _language=current_language.clone()
                lang_content=page_content.get()
                slug=slug_opt.unwrap_or_default()
                content_type=content_type_current.clone()
            />
        }
        .into_any()
    };

    // Render the appropriate version based on target
    content_component
}
