//! Unified Content Card Component
//!
//! Generic content card that works with any content type using the unified
//! trait system

#[cfg(target_arch = "wasm32")]
use ::rustelo_core_lib::utils::nav;
use ::rustelo_core_lib::{
    categories::get_category_emoji,
    content::{ContentItemTrait, UnifiedContentItem},
    i18n::create_content_provider,
    // Note: get_content_type_base_path import removed - function not available
};
// Removed leptos_router import - using custom routing system
use leptos::prelude::*;

/// Unified Content Card component that works with any content type
#[component]
pub fn UnifiedContentCard(
    #[prop(into)] content_item: UnifiedContentItem,
    #[prop(into)] content_type: String,
    #[prop(into)] language: String,
    #[prop(into)] _content_config: rustelo_core_lib::ContentConfig,
    #[prop(optional)] lang_content: Option<std::collections::HashMap<String, String>>,
    #[prop(optional)] base_path: Option<String>,
) -> impl IntoView {
    let content = create_content_provider(lang_content.clone());
    let title = content_item.title().to_string();
    let excerpt = content_item.excerpt.as_deref().unwrap_or("");
    let date = content_item.created_at().to_string();
    // Get the appropriate time field based on content type
    let time_display = if let Some(read_time_str) = content_item.read_time.as_ref() {
        if !read_time_str.is_empty() {
            read_time_str.to_string()
        } else {
            String::new()
        }
    } else {
        String::new()
    };
    let categories = content_item.categories();
    let tags = content_item.tags();
    let featured = content_item.featured();

    // Generate URL using built-in method (respects page_route when set)
    let url = content_item.url_path();
    let title_url = content_item.url_path();
    let thumbnail = content_item.thumbnail.clone();
    let thumbnail_dark = content_item.thumbnail_dark.clone();

    view! {
        <article class={
            format!("ds-card ds-shadow-xl h-full flex flex-col {}",
                if featured {
                    "ds-bg-base-200/50 ds-ring-2 ds-ring-primary/30 border border-base-300/50"
                } else {
                    "ds-bg-base-100"
                })
        }>
            {thumbnail.map(|src| {
                let thumb_url = url.clone();
                let has_dark = thumbnail_dark.is_some();
                let dark_src = thumbnail_dark.unwrap_or_default();
                let light_class = if has_dark {
                    "w-full grid-post-img grid-post-img-light hover:scale-105 transition-transform duration-300"
                } else {
                    "w-full grid-post-img hover:scale-105 transition-transform duration-300"
                };
                view! {
                    <figure class="overflow-hidden rounded-t-2xl grid-post-figure">
                        <a href={thumb_url.clone()}
                            on:click=move |_ev| {
                                #[cfg(target_arch = "wasm32")]
                                {
                                    if let Some(set_path) = use_context::<WriteSignal<String>>() {
                                        _ev.prevent_default();
                                        nav::anchor_navigate(set_path, &thumb_url);
                                        nav::doc_scroll_to_top(100);
                                    }
                                }
                            }
                        >
                            <img src={src} alt={title.clone()}
                                 class={light_class} />
                            {if has_dark {
                                view! {
                                    <img src={dark_src} alt={title.clone()}
                                         class="w-full grid-post-img grid-post-img-dark hover:scale-105 transition-transform duration-300" />
                                }.into_any()
                            } else {
                                view! { <></> }.into_any()
                            }}
                        </a>
                    </figure>
                }
            })}
            <div class="ds-card-body p-6 flex flex-col justify-between flex-1">
                <div class="flex-grow">
                    <h3 class="ds-card-title mb-3 flex flex-col">
                        <a href={title_url.clone()} class="ds-link-hover no-underline hover:text-primary transition-colors"
                            on:click=move |_ev| {
                                #[cfg(target_arch = "wasm32")]
                                {
                                    if let Some(set_path) = use_context::<WriteSignal<String>>() {
                                        _ev.prevent_default();
                                        nav::anchor_navigate(set_path, &title_url);
                                        nav::doc_scroll_to_top(100);
                                    }
                                }
                            }
                        >
                            {title}
                        </a>
                        {if featured {
                            view! {
                                <div class="ds-card-featured ds-text-xs-500 mt-2 text-end w-min text-opacity-70">
                                    {content.t_with_prefixes("featured-post", &[&content_type, "content"], Some("Featured"))}
                                </div>
                            }.into_any()
                        } else {
                            view! { <></> }.into_any()
                        }}
                    </h3>

                    {if !excerpt.is_empty() {
                        view! {
                            <p class="ds-card-text mb-4 line-clamp-3">{excerpt}</p>
                        }.into_any()
                    } else {
                        view! { <></> }.into_any()
                    }}
                </div>

                <div class="mt-auto">
                    <div class="flex flex-col gap-2 mb-4">
                        {if !categories.is_empty() {
                            let main_category = categories[0].clone();
                            let main_category_title = content.t_with_prefixes(&main_category, &[&content_type, "content"], Some(&main_category));
                            // let categories_str = categories.join(",");
                            // Use the TOML configuration to get the proper base path for this content type and language
                            let resolved_base_path = base_path.as_ref().cloned().unwrap_or_else(|| {
                                Some(format!("/{}/{}", language, content_type)) // Fallback path returns Option
                                    .unwrap_or_else(|| {
                                        #[cfg(target_arch = "wasm32")]
                                        web_sys::console::log_1(
                                            &format!(
                                                "⚠️ CARD ROUTING WARNING: No route found for content_type='{}' in language='{}', using fallback",
                                                content_type, language
                                            ).into(),
                                        );
                                        format!("/{}", content_type)
                                    })
                            });

                            let main_category_url = format!("{}/{}", resolved_base_path, main_category);
                            let main_category_display = {
                                let category_emoji = get_category_emoji(&content_type, &language, &main_category);
                                format!("{} {}", category_emoji, main_category)
                            };
                            view! {
                                <>
                                    // Main category - prominently displayed
                                    <div class="flex flex-wrap gap-2">
                                        <a href={main_category_url.clone()}
                                           class="ds-badge ds-badge-outline no-underline hover:ds-badge-primary-focus px-3 py-1"
                                           title={format!("{} {} {}", content.t("content-view-all"), &main_category_title, &content_type)}
                                           on:click=move |_ev| {
                                               #[cfg(target_arch = "wasm32")]
                                               {
                                                   if let Some(set_path) = use_context::<WriteSignal<String>>() {
                                                       _ev.prevent_default();
                                                       nav::anchor_navigate(set_path, &main_category_url);
                                                       nav::doc_scroll_to_top(100);
                                                   }
                                               }
                                           }
                                        >
                                            {main_category_display}
                                        </a>
                                    </div>

                                    // Tags displayed separately for better visibility
                                    {if !tags.is_empty() {
                                        view! {
                                            <div class="flex flex-wrap gap-1">
                                                {tags.iter().map(|tag| {
                                                    let tag_title = content.t_with_prefixes(&tag, &[&content_type, "content"], Some(&tag));
                                                    // Use TOML configuration to get proper base path for tags
                                                    let tag_base_path = base_path.clone().unwrap_or_else(|| {
                                                        Some(format!("/{}/{}", language, content_type)) // Fallback path returns Option
                                                            .unwrap_or_else(|| format!("/{}", content_type))
                                                    });
                                                    let tag_url = format!("{}/{}", tag_base_path, tag);
                                                    let tag_title_for_attr = tag_title.clone();
                                                    view! {
                                                        <a href={tag_url.clone()}
                                                            class="ds-badge ds-badge-ghost ds-badge-sm text-base-content/70 px-2 no-underline hover:ds-badge-accent hover:text-accent-content transition-colors cursor-pointer"
                                                            title={format!("{} {} {}", content.t("content-view-all"), &tag_title_for_attr, &content_type)}
                                                            on:click=move |_ev| {
                                                                #[cfg(target_arch = "wasm32")]
                                                                {
                                                                    if let Some(set_path) = use_context::<WriteSignal<String>>() {
                                                                        _ev.prevent_default();
                                                                        nav::anchor_navigate(set_path, &tag_url);
                                                                        nav::doc_scroll_to_top(100);
                                                                    }
                                                                }
                                                            }
                                                           >
                                                            {tag_title}
                                                        </a>
                                                    }
                                                }).collect_view()}
                                            </div>
                                        }.into_any()
                                    } else {
                                        view! { <></> }.into_any()
                                    }}
                                </>
                            }.into_any()
                        } else if !tags.is_empty() {
                            // If no main category, show tags as primary display
                            view! {
                                <div class="flex flex-wrap gap-1">
                                    {tags.iter().map(|tag| {
                                        let tag_title = content.t_with_prefixes(&tag, &[&content_type, "content"], Some(&tag));
                                        // Use TOML configuration to get proper base path for tags
                                        let tag_base_path_no_cat = base_path.as_ref().cloned().unwrap_or_else(|| {
                                            Some(format!("/{}/{}", language, content_type)) // Fallback path returns Option
                                                .unwrap_or_else(|| format!("/{}", content_type))
                                        });
                                        let tag_url = format!("{}/{}", tag_base_path_no_cat, tag);
                                        let tag_title_for_attr = tag_title.clone();
                                        view! {
                                            <a href={tag_url.clone()}
                                               class="ds-badge ds-badge-ghost ds-badge-sm text-base-content/70 px-2 no-underline hover:ds-badge-accent hover:text-accent-content transition-colors cursor-pointer"
                                               title={format!("{} {} {}", content.t("content-view-all"), &tag_title_for_attr, &content_type)}
                                               on:click=move |_ev| {
                                                   #[cfg(target_arch = "wasm32")]
                                                   {
                                                       if let Some(set_path) = use_context::<WriteSignal<String>>() {
                                                           _ev.prevent_default();
                                                           nav::anchor_navigate(set_path, &tag_url);
                                                           nav::doc_scroll_to_top(100);
                                                       }
                                                   }
                                               }
                                            >
                                                {tag_title}
                                            </a>
                                        }
                                    }).collect_view()}
                                </div>
                            }.into_any()
                        } else {
                            view! { <></> }.into_any()
                        }}
                    </div>

                    <div class="pt-3 border-t border-base-300">
                        <div class="grid grid-cols-2 gap-3 items-end">
                            <div class="grid grid-rows-2 gap-1 text-sm text-base-content/60">
                                {if !date.is_empty() {
                                    let date_display = date.clone();
                                    view! {
                                        <div>{date_display}</div>
                                    }.into_any()
                                } else {
                                    view! { <div></div> }.into_any()
                                }}
                                {if !time_display.is_empty() {
                                    view! {
                                        <div>{time_display.clone()}</div>
                                    }.into_any()
                                } else {
                                    view! { <div></div> }.into_any()
                                }}
                            </div>

                            <div class="flex justify-end">
                                <a href={url.clone()} class="ds-btn ds-btn-primary ds-btn-sm px-4 py-1 whitespace-nowrap"
                                    on:click=move |_ev| {
                                        #[cfg(target_arch = "wasm32")]
                                        {
                                            if let Some(set_path) = use_context::<WriteSignal<String>>() {
                                                _ev.prevent_default();
                                                nav::anchor_navigate(set_path, &url);
                                                nav::doc_scroll_to_top(100);
                                            }
                                        }
                                    }
                                >
                                    {content.t_with_prefixes("read-more", &[&content_type, "content"], Some("Read More"))}
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </article>
    }
}
