use leptos::prelude::*;

/// Wraps the application shell and emits a navigation log entry on every path
/// change.  Place this component once inside the app's language/auth providers
/// so it can read the shared `ReadSignal<String>` path context and the
/// current-language context.
///
/// The first render is logged with `nav_type = "initial"`.  All subsequent
/// path changes are logged with `nav_type = "spa"`.
///
/// On SSR this component is a transparent pass-through — tracking happens only
/// on the client (WASM) where user navigation actually occurs.
#[component]
pub fn NavLogProvider(children: Children) -> impl IntoView {
    #[cfg(target_arch = "wasm32")]
    {
        use leptos::task::spawn_local;
        use rustelo_core_lib::state::{use_current_language, AuthState};

        use super::server_fns::track_page_view;

        let path = use_context::<ReadSignal<String>>();
        let lang = use_current_language();
        let auth_state = use_context::<AuthState>();
        // Tracks whether this is the very first effect run (initial page load).
        let is_first = RwSignal::new(true);

        Effect::new(move |_| {
            let p = match path {
                Some(sig) => sig.get(),
                None => {
                    web_sys::console::warn_1(
                        &"[NavLog] ReadSignal<String> not found in context — tracking disabled"
                            .into(),
                    );
                    return;
                }
            };

            let initial = is_first.get_untracked();
            if initial {
                is_first.set(false);
            }

            let l = lang.get_untracked();
            let nav_type = if initial { "initial" } else { "spa" };
            let page = p.clone();
            let nt = nav_type.to_string();
            // Read user id without subscribing this effect to auth changes.
            let uid = auth_state
                .as_ref()
                .and_then(|a| a.user.get_untracked())
                .map(|u| u.id.clone());

            web_sys::console::log_1(
                &format!(
                    "[NavLog] tracking: page='{}' lang='{}' type='{}' user={}",
                    page,
                    l,
                    nav_type,
                    uid.as_deref().unwrap_or("anon")
                )
                .into(),
            );

            spawn_local(async move {
                if let Err(e) = track_page_view(page.clone(), l, nt, uid).await {
                    web_sys::console::warn_1(
                        &format!("[NavLog] track_page_view failed for '{}': {}", page, e).into(),
                    );
                }
            });
        });
    }

    children()
}
