//! Error boundary component for graceful error handling

use leptos::error::ErrorBoundary as LeptosErrorBoundary;
use leptos::prelude::*;

/// Error boundary component
///
/// Catches errors from child components and displays a user-friendly error message.
/// Following L-HYDRATION-SAFETY principles, this ensures errors don't crash the entire app.
///
/// # Example
///
/// ```ignore
/// view! {
///     <ErrorBoundary>
///         <SomeComponentThatMightError/>
///     </ErrorBoundary>
/// }
/// ```
#[component]
pub fn ErrorBoundary(children: Children) -> impl IntoView {
    view! {
        <LeptosErrorBoundary
            fallback=|errors| view! {
                <ErrorDisplay errors=errors/>
            }
        >
            {children()}
        </LeptosErrorBoundary>
    }
}

/// Error display component
///
/// Renders error messages in a user-friendly format.
#[component]
fn ErrorDisplay(errors: ArcRwSignal<Errors>) -> impl IntoView {
    let error_list = move || {
        errors.with(|errors| {
            errors
                .iter()
                .map(|(_, error)| {
                    view! {
                        <li class="text-sm text-red-600 dark:text-red-400">
                            {error.to_string()}
                        </li>
                    }
                })
                .collect::<Vec<_>>()
        })
    };

    view! {
        <div class="dash-card border-l-4 border-red-500 bg-red-50 dark:bg-red-900/20 p-6 my-4">
            <div class="flex items-start">
                <div class="flex-shrink-0">
                    <span class="text-2xl">"⚠️"</span>
                </div>
                <div class="ml-3 flex-1">
                    <h3 class="text-lg font-semibold text-red-800 dark:text-red-300">
                        "An error occurred"
                    </h3>
                    <ul class="mt-2 space-y-1 list-disc list-inside">
                        {error_list}
                    </ul>
                    <p class="mt-4 text-sm text-gray-600 dark:text-gray-400">
                        "Please try refreshing the page. If the problem persists, contact support."
                    </p>
                </div>
            </div>
        </div>
    }
}
