use leptos::ev;
use leptos::prelude::*;

/// Helper function to perform SPA navigation
#[cfg(target_arch = "wasm32")]
fn navigate_spa(href: &str) {
    use web_sys::window;

    let Some(window) = window() else { return };
    let Ok(history) = window.history() else {
        return;
    };

    let _ = history.push_state_with_url(&wasm_bindgen::JsValue::NULL, "", Some(href));

    // Dispatch popstate event to trigger router
    if let Ok(event) = web_sys::PopStateEvent::new("popstate") {
        let _ = window.dispatch_event(&event);
    }
}

#[component]
pub fn SpaLinkClient(
    href: String,
    children: Children,
    class: Option<String>,
    external: bool,
) -> impl IntoView {
    // Detect if link is external (starts with http/https/mailto)
    let is_external = external
        || href.starts_with("http://")
        || href.starts_with("https://")
        || href.starts_with("mailto:")
        || href.starts_with("tel:");

    if is_external {
        // External link - open in new tab
        view! {
            <a
                href=href
                class=class.unwrap_or_default()
                target="_blank"
                rel="noopener noreferrer"
            >
                {children()}
            </a>
        }
        .into_any()
    } else {
        // Internal link - use SPA navigation
        let href_clone = href.clone();
        let handle_click = move |e: ev::MouseEvent| {
            // Prevent default navigation
            e.prevent_default();

            #[cfg(target_arch = "wasm32")]
            navigate_spa(&href_clone);
        };

        view! {
            <a
                href=href
                class=class.unwrap_or_default()
                on:click=handle_click
            >
                {children()}
            </a>
        }
        .into_any()
    }
}
