use crate::models::NewsCard as NewsCardModel;
use dioxus::prelude::*;

/// Renders a news feed card with title, source, category badge, and summary.
///
/// When a thumbnail URL is present but the image fails to load, the card
/// automatically switches to the centered no-thumbnail layout.
///
/// # Arguments
///
/// * `card` - The news card model data to render
/// * `on_click` - Event handler triggered when the card is clicked
/// * `selected` - Whether this card is currently selected (highlighted)
#[component]
pub fn NewsCardView(
    card: NewsCardModel,
    on_click: EventHandler<NewsCardModel>,
    #[props(default = false)] selected: bool,
) -> Element {
    // Derive a CSS class from the category string (lowercase, hyphenated)
    let css_suffix = card.category.to_lowercase().replace(' ', "-");
    let badge_class = format!("news-badge news-badge--{css_suffix}");

    // Track whether the thumbnail loaded successfully.
    // Starts as true if a URL is provided; set to false on image error.
    let has_thumb_url = card.thumbnail_url.is_some();
    let mut thumb_ok = use_signal(|| has_thumb_url);

    let show_thumb = has_thumb_url && *thumb_ok.read();
    let selected_cls = if selected { " news-card--selected" } else { "" };
    let thumb_cls = if show_thumb {
        ""
    } else {
        " news-card--no-thumb"
    };
    let card_class = format!("news-card{selected_cls}{thumb_cls}");

    // Clone the card for the click handler closure
    let card_for_click = card.clone();

    rsx! {
        article {
            class: "{card_class}",
            onclick: move |_| on_click.call(card_for_click.clone()),
            if let Some(ref thumb) = card.thumbnail_url {
                if *thumb_ok.read() {
                    div { class: "news-card-thumb",
                        img {
                            src: "{thumb}",
                            alt: "",
                            loading: "lazy",
                            // Hide the thumbnail container if the image fails to load
                            onerror: move |_| thumb_ok.set(false),
                        }
                    }
                }
            }
            div { class: "news-card-body",
                div { class: "news-card-meta",
                    span { class: "{badge_class}", "{card.category}" }
                    span { class: "news-card-source", "{card.source}" }
                    span { class: "news-card-date", "{card.published_at}" }
                }
                h3 { class: "news-card-title", "{card.title}" }
                p { class: "news-card-summary", "{card.summary}" }
            }
        }
    }
}

/// Returns mock news data for the dashboard.
pub fn mock_news() -> Vec<NewsCardModel> {
    vec![
        NewsCardModel {
            title: "Llama 4 Released with 1M Context Window".into(),
            source: "Meta AI Blog".into(),
            summary: "Meta releases Llama 4 with a 1 million token context window.".into(),
            content: "Meta has officially released Llama 4, their latest \
                open-weight large language model featuring a groundbreaking \
                1 million token context window. This represents a major \
                leap in context length capabilities."
                .into(),
            category: "AI".into(),
            url: "#".into(),
            thumbnail_url: None,
            published_at: "2026-02-18".into(),
        },
        NewsCardModel {
            title: "EU AI Act Enforcement Begins".into(),
            source: "TechCrunch".into(),
            summary: "The EU AI Act enters its enforcement phase across member states.".into(),
            content: "The EU AI Act has officially entered its enforcement \
                phase. Member states are now required to comply with the \
                comprehensive regulatory framework governing AI systems."
                .into(),
            category: "Privacy".into(),
            url: "#".into(),
            thumbnail_url: None,
            published_at: "2026-02-17".into(),
        },
        NewsCardModel {
            title: "LangChain v0.4 Introduces Native MCP Support".into(),
            source: "LangChain Blog".into(),
            summary: "New version adds first-class MCP server integration.".into(),
            content: "LangChain v0.4 introduces native Model Context Protocol \
                support, enabling seamless integration with MCP servers for \
                tool use and context management in agent workflows."
                .into(),
            category: "Technology".into(),
            url: "#".into(),
            thumbnail_url: None,
            published_at: "2026-02-16".into(),
        },
        NewsCardModel {
            title: "LiteLLM Adds Multi-Provider Routing".into(),
            source: "LiteLLM".into(),
            summary: "Route requests across multiple LLM providers with automatic fallback.".into(),
            content: "LiteLLM now supports multi-provider routing with automatic \
                fallback. Users can route requests across multiple providers \
                for improved reliability and cost optimization."
                .into(),
            category: "Infrastructure".into(),
            url: "#".into(),
            thumbnail_url: None,
            published_at: "2026-02-15".into(),
        },
        NewsCardModel {
            title: "Mistral Open Sources Codestral 2".into(),
            source: "Mistral AI".into(),
            summary: "Codestral 2 achieves state-of-the-art on HumanEval benchmarks.".into(),
            content: "Mistral AI has open-sourced Codestral 2, a code \
                generation model that achieves state-of-the-art results \
                on HumanEval and other coding benchmarks."
                .into(),
            category: "Open Source".into(),
            url: "#".into(),
            thumbnail_url: None,
            published_at: "2026-02-14".into(),
        },
        NewsCardModel {
            title: "NVIDIA Releases NeMo 3.0 Framework".into(),
            source: "NVIDIA Developer".into(),
            summary: "Updated framework simplifies enterprise LLM fine-tuning.".into(),
            content: "NVIDIA has released NeMo 3.0, an updated framework \
                that simplifies enterprise LLM fine-tuning with improved \
                distributed training capabilities."
                .into(),
            category: "Infrastructure".into(),
            url: "#".into(),
            thumbnail_url: None,
            published_at: "2026-02-13".into(),
        },
        NewsCardModel {
            title: "Anthropic Claude 4 Sets New Reasoning Records".into(),
            source: "Anthropic".into(),
            summary: "Claude 4 achieves top scores across major reasoning benchmarks.".into(),
            content: "Anthropic's Claude 4 has set new records across major \
                reasoning benchmarks, demonstrating significant improvements \
                in mathematical and logical reasoning capabilities."
                .into(),
            category: "AI".into(),
            url: "#".into(),
            thumbnail_url: None,
            published_at: "2026-02-12".into(),
        },
        NewsCardModel {
            title: "CrewAI Raises $52M for Agent Orchestration".into(),
            source: "VentureBeat".into(),
            summary: "Series B funding to expand multi-agent orchestration platform.".into(),
            content: "CrewAI has raised $52M in Series B funding to expand \
                its multi-agent orchestration platform, enabling teams \
                to build and deploy complex AI agent workflows."
                .into(),
            category: "Technology".into(),
            url: "#".into(),
            thumbnail_url: None,
            published_at: "2026-02-11".into(),
        },
        NewsCardModel {
            title: "DeepSeek V4 Released Under Apache 2.0".into(),
            source: "DeepSeek".into(),
            summary: "Latest open-weight model competes with proprietary offerings.".into(),
            content: "DeepSeek has released V4 under the Apache 2.0 license, \
                an open-weight model that competes with proprietary \
                offerings in both performance and efficiency."
                .into(),
            category: "Open Source".into(),
            url: "#".into(),
            thumbnail_url: None,
            published_at: "2026-02-10".into(),
        },
        NewsCardModel {
            title: "GDPR Fines for AI Training Data Reach Record High".into(),
            source: "Reuters".into(),
            summary: "European regulators issue largest penalties yet for AI data misuse.".into(),
            content: "European regulators have issued record-high GDPR fines \
                for AI training data misuse, signaling stricter enforcement \
                of data protection laws in the AI sector."
                .into(),
            category: "Privacy".into(),
            url: "#".into(),
            thumbnail_url: None,
            published_at: "2026-02-09".into(),
        },
    ]
}
