//! Client-side App component with proper routing
//!
//! This module provides the main App component for the client that uses
//! the shared routing system and renders actual page components.

#[cfg(target_arch = "wasm32")]
use std::time::Duration;

use leptos::prelude::*;
use leptos_meta::provide_meta_context;
use rustelo_components_leptos::{
    navigation::{footer::unified::Footer, navmenu::unified::NavMenu},
    theme::ThemeProvider,
};
use rustelo_core_lib::{
    i18n::{provide_unified_i18n, UnifiedI18n},
    routing::utils::detect_language_from_path,
    state::LanguageProvider,
};

/// Main App component for client-side that implements proper routing
#[component]
pub fn AppComponent(#[prop(default = String::new())] initial_path: String) -> impl IntoView {
    // Provide meta context for client-side behavior
    provide_meta_context();

    // Setup navigation signals for client-side routing
    let (path, set_path) = signal(initial_path.clone());

    // Provide set_path context for other components
    #[cfg(target_arch = "wasm32")]
    provide_context(set_path);

    // Initialize meta config preloader early for WASM
    #[cfg(target_arch = "wasm32")]
    rustelo_core_lib::init_meta_preloader();

    // Use the LanguageProvider and setup effects inside it
    view! {
        <LanguageProvider>
            <AppContent initial_path=initial_path path=path set_path=set_path />
        </LanguageProvider>
    }
}

/// Inner app content that has access to the language context
#[component]
fn AppContent(
    initial_path: String,
    path: ReadSignal<String>,
    set_path: WriteSignal<String>,
) -> impl IntoView {
    // Now we can use the shared language context
    let language_context = rustelo_core_lib::state::use_language();

    // Reactively detect language from current path and update context
    Effect::new(move |_| {
        let current_path = path.get();
        let detected_language = detect_language_from_path(&current_path);

        #[cfg(target_arch = "wasm32")]
        web_sys::console::log_1(
            &format!(
                "🔄 App Path Change: path='{}' → language='{}'",
                current_path, detected_language
            )
            .into(),
        );

        // Update language context when path changes
        if language_context.current.get_untracked() != detected_language {
            language_context.current.set(detected_language);
        }
    });

    // Set initial language from initial path
    let initial_language = detect_language_from_path(&initial_path);
    language_context.current.set(initial_language);

    // Create and provide unified i18n context that updates with language changes
    let unified_i18n = Memo::new(move |_| {
        let current_lang = language_context.current.get();
        let current_path = path.get();

        #[cfg(target_arch = "wasm32")]
        web_sys::console::log_1(
            &format!(
                "🔄 App i18n Memo: language='{}', path='{}'",
                current_lang, current_path
            )
            .into(),
        );

        UnifiedI18n::new(&current_lang, &current_path)
    });

    // Provide the reactive i18n context
    Effect::new(move |_| {
        let i18n = unified_i18n.get();
        provide_unified_i18n(i18n);
    });

    // Setup page transition effects
    #[cfg(target_arch = "wasm32")]
    {
        let (is_first_render, set_is_first_render) = signal(true);

        Effect::new(move |_| {
            let current_path = path.get();

            #[cfg(target_arch = "wasm32")]
            web_sys::console::log_1(
                &format!(
                    "🎬 App transition Effect: path='{}', first_render={}",
                    current_path,
                    is_first_render.get()
                )
                .into(),
            );

            if is_first_render.get() {
                set_is_first_render.set(false);
            } else {
                apply_page_transition();
            }

            // Dispatch custom event to reinitialize components
            set_timeout(
                move || {
                    #[cfg(target_arch = "wasm32")]
                    web_sys::console::log_1(
                        &format!(
                            "⏰ Dispatching reinitializeComponents event after 200ms for path: {}",
                            current_path
                        )
                        .into(),
                    );

                    if let Some(window) = web_sys::window() {
                        if let Ok(event) = web_sys::CustomEvent::new("reinitializeComponents") {
                            let _ = window.dispatch_event(&event);
                        }
                    }
                },
                Duration::from_millis(200),
            );
        });
    }

    // Use the client routing with actual page components
    view! {
        <ThemeProvider>
            <div class="min-h-screen ds-bg-page flex flex-col">
                <NavMenu _set_path=set_path _path=path />
                <main class="max-w-7xl mx-auto py-2 sm:ds-container flex-grow page-content fade-out">
                    {
                        move || {
                            let current_path = path.get();
                            let current_lang = language_context.current.get();

                            #[cfg(target_arch = "wasm32")]
                            web_sys::console::log_1(&format!("🎬 App main content render: path='{}', language='{}' (content re-rendering)", current_path, current_lang).into());

                            crate::routing::render_page_content_with_language(&current_path, &current_lang)
                        }
                    }
                </main>
                {
                    move || {
                        let lang = language_context.current.get();

                        view! {
                            <Footer language=lang _set_path=set_path _path=path />
                        }
                    }
                }
            </div>
        </ThemeProvider>
    }
}

/// Apply fade transition to page content
#[cfg(target_arch = "wasm32")]
fn apply_page_transition() {
    if let Some(document) = web_sys::window().and_then(|w| w.document()) {
        if let Ok(main_element) = document.query_selector("main.page-content") {
            if let Some(element) = main_element {
                let _ = element.class_list().add_1("fade-out");

                let element_clone = element.clone();
                set_timeout(
                    move || {
                        let _ = element_clone.class_list().remove_1("fade-out");
                        let _ = element_clone.class_list().add_1("fade-in");
                    },
                    std::time::Duration::from_millis(150),
                );

                let element_clone2 = element.clone();
                set_timeout(
                    move || {
                        let _ = element_clone2.class_list().remove_1("fade-in");
                    },
                    std::time::Duration::from_millis(300),
                );
            }
        }
    }
}
