use leptos::prelude::*;
#[cfg(target_arch = "wasm32")]
use web_sys::{window, HtmlElement};

/// Portal component for rendering children at document body level
///
/// Renders children into a container appended to document.body, avoiding
/// z-index and stacking context issues.
///
/// # Example
///
/// ```rust
/// use vapora_leptos_ui::utils::Portal;
///
/// view! {
///     <Portal>
///         <div class="modal">"This renders at body level"</div>
///     </Portal>
/// }
/// ```
#[component]
pub fn Portal(children: Children) -> impl IntoView {
    #[cfg(target_arch = "wasm32")]
    {
        use uuid::Uuid;

        let container_ref = NodeRef::<leptos::html::Div>::new();
        // Generate unique ID for cleanup without capturing element
        let portal_id = format!("portal-{}", Uuid::new_v4());
        let portal_id_clone = portal_id.clone();

        // Effect: move portal content to document.body
        Effect::new(move |_| {
            if let Some(container_el) = container_ref.get() {
                let html_el: HtmlElement = container_el.clone().into();

                // Set unique ID for cleanup
                html_el.set_id(&portal_id_clone);

                // Append container to document.body
                if let Some(body) = window().and_then(|w| w.document()).and_then(|d| d.body()) {
                    let _ = body.append_child(&html_el);

                    // Cleanup: remove from body using ID (avoid capturing element)
                    let cleanup_id = portal_id_clone.clone();
                    #[allow(clippy::excessive_nesting)]
                    on_cleanup(move || {
                        window()
                            .and_then(|w| w.document())
                            .and_then(|doc| doc.get_element_by_id(&cleanup_id))
                            .and_then(|el| {
                                el.parent_node()
                                    .and_then(|parent| parent.remove_child(&el).ok())
                            });
                    });
                }
            }
        });

        view! {
            <div node_ref=container_ref style="display: contents;">
                {children()}
            </div>
        }
        .into_any()
    }

    #[cfg(not(target_arch = "wasm32"))]
    {
        // SSR: render inline (no DOM manipulation)
        children().into_any()
    }
}
