//! Basic Hydration Example
//!
//! Demonstrates zero-configuration client hydration using TOML route
//! configuration. This is the 90% use case - pure configuration-driven approach
//! with no custom client code.

use client;

/// Zero-configuration WebAssembly hydration
///
/// This function demonstrates the most common client pattern:
/// - Read TOML route configuration from site/config/routes/*.toml
/// - Generate WebAssembly hydration automatically
/// - No custom client code needed
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
    println!("🚀 BASIC HYDRATION EXAMPLE");
    println!("==========================");
    println!();

    println!("📝 Step 1: Your TOML Configuration");
    println!("   File: site/config/routes/en.toml");
    println!("   [[routes]]");
    println!("   path = \"/dashboard\"");
    println!("   component = \"Dashboard\"");
    println!("   title_key = \"dashboard-title\"");
    println!("   language = \"en\"");
    println!("   enabled = true");
    println!();

    println!("⚙️  Step 2: Build System Generation");
    println!("   cargo leptos build");
    println!("   → Reads your TOML configuration");
    println!("   → Generates route handling code");
    println!("   → Creates component hydration logic");
    println!("   → Builds optimized WebAssembly");
    println!();

    println!("🔧 Step 3: Zero-Config Hydration");
    println!("   rustelo_client::hydrate() provides:");
    println!("   ✅ Hydration for /dashboard route");
    println!("   ✅ Client-side navigation");
    println!("   ✅ i18n with dashboard-title");
    println!("   ✅ Reactive component updates");
    println!("   ✅ Theme system integration");
    println!();

    // The actual hydration call - this is all that's needed!
    rustelo_client::hydrate();

    println!("✨ Hydration complete! Your TOML routes are now interactive.");
}

/// Example of configuration validation before hydration
///
/// This shows how to validate your TOML configuration at build time
/// to catch configuration errors before deploying WebAssembly.
fn validate_configuration_example() {
    use rustelo_core_types::RoutesConfig;

    println!("🔍 CONFIGURATION VALIDATION");
    println!("===========================");
    println!();

    // Simulate loading TOML configuration (in real usage, this would be from files)
    let toml_content = r#"
        [[routes]]
        path = "/dashboard"
        component = "Dashboard"
        title_key = "dashboard-title"
        description_key = "dashboard-description"
        language = "en"
        enabled = true

        [[routes]]
        path = "/profile"
        component = "Profile"
        title_key = "profile-title"
        language = "en"
        enabled = true
    "#;

    println!("📋 Loading route configuration from TOML:");
    println!("{}", toml_content);

    // Parse TOML into strongly-typed configuration
    match toml::from_str::<RoutesConfig>(toml_content) {
        Ok(routes_config) => {
            println!("✅ Configuration parsed successfully");
            println!("📊 Found {} routes", routes_config.routes.len());

            // Validate each route
            for route in &routes_config.routes {
                println!("   Route: {} → {}", route.path, route.component);

                // Validate route configuration
                if route.path.is_empty() {
                    println!("   ❌ Error: Empty path");
                    continue;
                }

                if !route.path.starts_with('/') {
                    println!("   ❌ Error: Path must start with '/'");
                    continue;
                }

                if route.component.is_empty() {
                    println!("   ❌ Error: Empty component name");
                    continue;
                }

                if route.title_key.is_empty() {
                    println!("   ❌ Error: Empty title key");
                    continue;
                }

                println!("   ✅ Valid route configuration");
            }

            println!();
            println!("🎯 Ready to build WebAssembly with validated configuration");
        }
        Err(e) => {
            println!("❌ Configuration parsing failed: {}", e);
            println!("   Please fix your TOML configuration before building");
        }
    }
}

/// Example of inspecting generated hydration behavior
///
/// Shows what happens during the hydration process and how it relates
/// to your TOML configuration.
fn inspect_hydration_process() {
    println!("🔬 HYDRATION PROCESS INSPECTION");
    println!("===============================");
    println!();

    println!("🌊 Hydration Flow (generated from your TOML config):");
    println!("1. Browser loads server-rendered HTML");
    println!("2. WebAssembly module initializes");
    println!("3. rustelo_client::hydrate() reads data-leptos-config");
    println!("4. Route resolution using configured routes");
    println!("5. Component hydration based on current path");
    println!("6. State providers activation (theme, i18n, auth)");
    println!("7. Event handlers attachment");
    println!("8. Client-side routing activation");
    println!();

    println!("🎯 What gets hydrated (determined by your routes TOML):");
    println!("   /dashboard     → DashboardComponent");
    println!("   /profile       → ProfileComponent");
    println!("   /settings      → SettingsComponent");
    println!("   /*             → NotFoundComponent");
    println!();

    println!("🔄 Reactive Features (automatic from configuration):");
    println!("   • Language switching triggers content updates");
    println!("   • Theme changes update CSS custom properties");
    println!("   • Route navigation updates without page refresh");
    println!("   • Authentication state syncs across components");
    println!();

    println!("📦 Bundle Analysis (based on enabled routes):");
    println!("   • Main bundle: Common components + routing");
    println!("   • Route chunks: Lazy-loaded per major route");
    println!("   • Feature bundles: Auth, analytics, etc.");
    println!("   • Shared chunks: Common dependencies");
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_basic_configuration_loading() {
        // Test that we can parse basic route configuration
        let toml_content = r#"
            [[routes]]
            path = "/test"
            component = "Test"
            title_key = "test-title"
            language = "en"
            enabled = true
        "#;

        let result: Result<rustelo_core_types::RoutesConfig, _> = toml::from_str(toml_content);
        assert!(result.is_ok());

        let config = result.unwrap();
        assert_eq!(config.routes.len(), 1);
        assert_eq!(config.routes[0].path, "/test");
        assert_eq!(config.routes[0].component, "Test");
    }

    #[test]
    fn test_route_validation() {
        use rustelo_core_types::RouteConfigToml;

        // Test valid route
        let valid_route = RouteConfigToml {
            path: "/dashboard".to_string(),
            component: "Dashboard".to_string(),
            title_key: "dashboard-title".to_string(),
            language: "en".to_string(),
            enabled: true,
            ..Default::default()
        };

        assert!(!valid_route.path.is_empty());
        assert!(valid_route.path.starts_with('/'));
        assert!(!valid_route.component.is_empty());
        assert!(!valid_route.title_key.is_empty());

        // Test invalid route
        let invalid_route = RouteConfigToml {
            path: "invalid-path".to_string(), // Missing leading slash
            component: "".to_string(),        // Empty component
            ..Default::default()
        };

        assert!(!invalid_route.path.starts_with('/')); // Should fail validation
        assert!(invalid_route.component.is_empty()); // Should fail validation
    }
}

/// Main function for testing this example
fn main() {
    println!("🎯 RUSTELO CLIENT BASIC HYDRATION EXAMPLE");
    println!("==========================================");
    println!();

    println!("This example demonstrates the foundational pattern of Rustelo client applications:");
    println!("TOML Configuration → Generated WebAssembly → Interactive Client Application");
    println!();

    validate_configuration_example();
    println!();

    inspect_hydration_process();
    println!();

    println!("💡 Key Takeaways:");
    println!("   • 90% of client functionality comes from TOML configuration");
    println!("   • Zero custom code needed for basic hydration");
    println!("   • Configuration validation catches errors early");
    println!("   • Generated code handles routing, i18n, themes automatically");
    println!("   • WebAssembly bundle size optimized by configuration");
    println!();

    println!("▶️  To see this in action:");
    println!("   1. Configure routes in site/config/routes/*.toml");
    println!("   2. Run: cargo leptos build");
    println!("   3. Open browser to see hydrated application");
    println!("   4. View browser console for hydration logging");

    // Note: In a real WASM environment, you would call hydrate() here
    // hydrate();
}
