use leptos::prelude::*;

/// Macro to log hydration debug info
#[macro_export]
macro_rules! hydration_log {
    ($component:expr, $message:expr) => {
        #[cfg(target_arch = "wasm32")]
        web_sys::console::log_1(&format!("[HYDRATION] {} - {}", $component, $message).into());
    };
    ($component:expr, $message:expr, $($arg:tt)*) => {
        #[cfg(target_arch = "wasm32")]
        web_sys::console::log_1(&format!("[HYDRATION] {} - {}", $component, format!($message, $($arg)*)).into());
    };
}

/// Component to help identify hydration mismatches
#[component]
pub fn HydrationDebugBoundary(#[prop(into)] name: String, children: Children) -> impl IntoView {
    use leptos::prelude::*;

    let name_for_attr = name.clone();

    #[cfg(target_arch = "wasm32")]
    {
        use leptos::prelude::Effect;
        let name_for_effect = name.clone();
        Effect::new(move |_| {
            web_sys::console::log_1(&format!("[HYDRATION] {} mounted", name_for_effect).into());
        });
    }

    view! {
        <div data-hydration-debug=name_for_attr>
            {children()}
        </div>
    }
}

/// Check if we're in hydration phase
pub fn is_hydrating() -> bool {
    #[cfg(target_arch = "wasm32")]
    {
        if let Some(window) = web_sys::window() {
            if let Ok(val) = js_sys::Reflect::get(&window, &"__leptos_hydrating".into()) {
                return val.as_bool().unwrap_or(false);
            }
        }
    }
    false
}

/// Mark hydration phase
pub fn set_hydrating(hydrating: bool) {
    #[cfg(target_arch = "wasm32")]
    {
        if let Some(window) = web_sys::window() {
            let _ = js_sys::Reflect::set(&window, &"__leptos_hydrating".into(), &hydrating.into());
        }
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        let _ = hydrating;
    }
}
