# Core Lib Foundation Library

Core runtime library for Rustelo web applications providing **configuration-driven architecture** with build-time code generation, language-agnostic i18n, content management, and state management.

> **🏗️ Configuration-First Architecture**: This library follows Rustelo's PAP (Project Architecture Principles) - configure your application through TOML files, let the build system generate the code.

## Quick Start

### Pattern 1: Configuration-Driven Setup (90% of use cases)
```toml
# site/config/routes/en.toml
[[routes]]
path = "/about"
component = "About"
title_key = "about-title"
description_key = "about-description"

# content/content-kinds.toml
[page]
title = "Static Pages"
directory = "page"
enabled = true
is_default = true
```

```rust
// Your application automatically gets:
use core_lib::{RouteComponent, resolve_unified_route, generate_ssr_render_component};

// Components generated at build-time from configuration
include!(concat!(env!("OUT_DIR"), "/generated_routes.rs"));
include!(concat!(env!("OUT_DIR"), "/generated_components.rs"));

fn handle_route(path: &str, lang: &str) -> String {
    match resolve_unified_route(path, lang).unwrap() {
        RouteResolution::Page { component, .. } => {
            // Component implementation generated from TOML config
            generate_ssr_render_component(&component, path, lang, &HashMap::new())
        }
        _ => "Not found".to_string()
    }
}
```

### Pattern 2: Extension When Configuration Isn't Enough (10% of use cases)
```rust
// build.rs - only when you need custom logic
use core_lib::build::{generate_shared_resources, CustomPageTemplate};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Foundation generates base components from TOML config
    generate_shared_resources()?;
    
    // Add custom templates only when standard ones aren't enough
    generate_custom_landing_page()?;
    Ok(())
}

fn generate_custom_landing_page() -> Result<(), Box<dyn std::error::Error>> {
    // Custom component generation when configuration can't express your needs
    let custom_template = r#"
        #[component]
        pub fn CustomLandingPage() -> impl IntoView {
            // Custom Rust code for complex business logic
            view! {
                <div class="custom-landing">
                    <ComplexInteractiveWidget />
                    <ThirdPartyIntegration />
                </div>
            }
        }
    "#;
    
    std::fs::write(concat!(env!("OUT_DIR"), "/custom_landing.rs"), custom_template)?;
    Ok(())
}
```

### Generated Components Integration
```rust
// Your build.rs generates this automatically from TOML configuration:
use core_lib::{AppStateProvider, use_app_state, use_current_language};
use leptos::*;

// Generated from site/config/routes/*.toml
include!(concat!(env!("OUT_DIR"), "/generated_app.rs"));

// The foundation generates your main app structure:
#[component]
fn GeneratedApp() -> impl IntoView {
    view! {
        // Provider hierarchy generated from config
        <AppStateProvider>
            <LanguageProvider>
                <ThemeProvider>
                    <ContentLoaderProvider>
                        // Routes generated from TOML files
                        <GeneratedRouter />
                    </ContentLoaderProvider>
                </ThemeProvider>
            </LanguageProvider>
        </AppStateProvider>
    }
}

// Example of generated route component (from TOML config):
#[component] 
fn GeneratedHomePage(
    #[prop(optional)] lang: String,
    #[prop(optional)] params: HashMap<String, String>,
) -> impl IntoView {
    let current_lang = use_current_language();
    
    // Content and layout generated from configuration
    view! {
        <div class="page-container home-page">
            // Generated from title_key, description_key in TOML
            <PageHeader title_key="home-title" />
            <PageContent sections=generated_sections />
        </div>
    }
}
```

### Build System Integration (Configuration-Driven)
```rust
// build.rs - Foundation handles configuration → code generation
use core_lib::build::{generate_shared_resources_with_cache, SmartCache};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Reads your TOML configuration and generates Leptos components
    println!("🔧 Generating components from configuration...");
    
    // Automatically processes:
    // - site/config/routes/*.toml → RouteComponent enum + page components
    // - content/content-kinds.toml → content type handlers  
    // - content/locales/* → i18n setup
    // - config/design-system.toml → theme configuration
    let built = generate_shared_resources_with_cache()?;
    
    if built {
        println!("✅ Generated new components from configuration");
        println!("   - RouteComponent enum with your routes");
        println!("   - Page components with proper i18n");
        println!("   - Content type resolvers");
        println!("   - Generated routing logic");
    } else {
        println!("⚡ Using cached generated components");
    }
    
    Ok(())
}
```

## Configuration-First Architecture Patterns

### Pattern 1: Pure Configuration (Recommended)

**Add new pages by editing TOML, not writing Rust code:**
```toml
# site/config/routes/en.toml - This generates Rust components automatically
[[routes]]
path = "/services"
component = "Services"
title_key = "services-title"
description_key = "services-description"
menu_group = "main"
menu_order = 2
show_in_sitemap = true

# Add sections to your page
[routes.sections]
hero = { template = "hero-with-cta", background = "gradient" }
features = { template = "feature-grid", columns = 3 }
testimonials = { template = "testimonial-carousel" }
```

**The build system automatically generates:**
```rust
// Generated in OUT_DIR/generated_routes.rs
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum RouteComponent {
    Home,
    Services,  // ← Your new route added here automatically
    // ... other configured routes
}

// Generated in OUT_DIR/generated_pages.rs
#[component]
pub fn ServicesPage(  // ← Generated from your TOML config
    #[prop(optional)] lang: String,
    #[prop(optional)] params: HashMap<String, String>,
) -> impl IntoView {
    view! {
        <div class="page-container services-page">
            <HeroWithCta background="gradient" />
            <FeatureGrid columns=3 />
            <TestimonialCarousel />
        </div>
    }
}
```

**Your application code stays simple:**
```rust
use core_lib::{resolve_unified_route, RouteComponent};

// Components already generated from your TOML config
include!(concat!(env!("OUT_DIR"), "/generated_routes.rs"));
include!(concat!(env!("OUT_DIR"), "/generated_pages.rs"));

// Route resolution automatically handles your new pages
fn handle_request(path: &str, lang: &str) -> String {
    match resolve_unified_route(path, lang).unwrap() {
        RouteResolution::Page { component: RouteComponent::Services, .. } => {
            // ServicesPage component already generated from TOML
            render_services_page(lang)
        }
        // ... other routes handled automatically
    }
}
```

### Pattern 2: Automatic Language Discovery (Configuration-Driven)

**Languages discovered automatically from your content structure:**
```
content/
├── locales/
│   ├── en/
│   │   ├── common.ftl      # ← Foundation discovers English
│   │   └── pages.ftl
│   ├── es/
│   │   ├── common.ftl      # ← Foundation discovers Spanish  
│   │   └── pages.ftl
│   └── fr/
│       ├── common.ftl      # ← Foundation discovers French
│       └── pages.ftl
└── blog/
    ├── en/                 # ← Content structure confirms languages
    ├── es/
    └── fr/
```

**Generated i18n system (no manual setup required):**
```rust
use core_lib::{discover_available_languages, t, resolve_unified_route};

// Generated automatically from your content structure
include!(concat!(env!("OUT_DIR"), "/generated_i18n.rs"));
include!(concat!(env!("OUT_DIR"), "/generated_translations.rs"));

fn demonstrate_automatic_i18n() {
    // Languages discovered automatically from content/locales/
    let languages = discover_available_languages();
    println!("Discovered: {:?}", languages); // ["en", "es", "fr"]
    
    // Translations loaded automatically from .ftl files
    for lang in languages {
        let greeting = t_for_language("greeting", &lang);
        println!("{}: {}", lang, greeting);
        
        // Routes automatically generated for each language
        let about_url = get_localized_route("about", &lang).unwrap();
        println!("{} about page: {}", lang, about_url);
    }
}

// Multi-language routing generated automatically
fn handle_multilingual_routes(path: &str) -> String {
    // Language detection from URL path  
    let (detected_lang, clean_path) = extract_lang_and_path(path);
    
    match resolve_unified_route(path, &detected_lang) {
        Ok(RouteResolution::Page { component, .. }) => {
            // Component renders in detected language automatically
            generate_ssr_render_component(&component, &clean_path, &detected_lang, &HashMap::new())
        }
        _ => generate_404_page(&detected_lang)
    }
}
```

### Pattern 3: Content Types from Configuration

**Define content types through configuration, not code:**
```toml
# content/content-kinds.toml - This generates content type handlers
[blog]
title = "Blog Posts"
directory = "blog"
enabled = true
icon = "📝"
color = "#3B82F6"
features = ["categories", "tags", "comments"]
template = "blog-post"

[services]
title = "Services"
directory = "services"
enabled = true
icon = "🛠️"  
color = "#10B981"
features = ["pricing", "testimonials"]
template = "service-page"

[portfolio]
title = "Portfolio Items"
directory = "portfolio"
enabled = true
icon = "🎨"
color = "#8B5CF6"
features = ["gallery", "case-study"]
template = "portfolio-item"
```

**Generated content management system:**
```rust
// Generated from content-kinds.toml
include!(concat!(env!("OUT_DIR"), "/content_types_generated.rs"));
include!(concat!(env!("OUT_DIR"), "/content_resolvers.rs"));

// Content types automatically available
use core_lib::{resolve_content_type_from_route, load_content_by_type};

async fn demonstrate_generated_content_system() -> Result<(), Box<dyn std::error::Error>> {
    // Content types discovered from your TOML config
    let available_types = get_available_content_types();
    println!("Content types: {:?}", available_types); // ["blog", "services", "portfolio"]
    
    // Route resolution automatically handles your content types
    let test_routes = vec!["/blog/my-post", "/services/web-design", "/portfolio/awesome-project"];
    
    for route in test_routes {
        if let Some(content_type) = resolve_content_type_from_route(route) {
            println!("Route {} → Content type: {}", route, content_type);
            
            // Content loading automatically configured from TOML
            match load_content_by_type(&content_type, "en").await {
                Ok(content_index) => {
                    println!("  Loaded {} {} items", content_index.items.len(), content_type);
                    
                    // Template and features automatically applied from config
                    for item in content_index.items.iter().take(2) {
                        println!("    - {}", item.title);
                    }
                }
                Err(e) => println!("  Error: {}", e),
            }
        }
    }
    
    Ok(())
}

// Generated content type enum from your TOML config
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum GeneratedContentType {
    Blog,      // ← From [blog] in TOML
    Services,  // ← From [services] in TOML  
    Portfolio, // ← From [portfolio] in TOML
}
```

### Pattern 4: State Management with Leptos

Comprehensive state management for Leptos applications:
```rust
use core_lib::{
    AppStateProvider, use_app_state, use_app_state_summary,
    use_auth_state, use_theme, use_current_language,
    use_content_loader, use_route_state,
    AppState, AuthState, ThemeState
};
use leptos::*;

#[component]
fn StateManagementExample() -> impl IntoView {
    // Access different state providers
    let app_state = use_app_state();
    let app_summary = use_app_state_summary();
    let auth_state = use_auth_state();
    let theme_state = use_theme();
    let current_lang = use_current_language();
    let content_loader = use_content_loader();
    let route_state = use_route_state();

    // Create effects to respond to state changes
    create_effect(move |_| {
        let state = app_state.get();
        logging::log!("App state changed: ready={}, loading={}", state.ready, state.loading);
    });

    view! {
        <div class="state-example">
            <h2>Application State</h2>
            <p>"Ready: " {move || app_state.get().ready.to_string()}</p>
            <p>"Theme: " {move || theme_state.get().current_theme.clone()}</p>
            <p>"Language: " {move || current_lang.get()}</p>
            <p>"Authenticated: " {move || auth_state.get().is_authenticated.to_string()}</p>
            
            <StateControls />
        </div>
    }
}

#[component]
fn StateControls() -> impl IntoView {
    let app_state = use_app_state();
    let theme_state = use_theme();
    
    let toggle_loading = move |_| {
        app_state.update(|state| state.loading = !state.loading);
    };
    
    let switch_theme = move |_| {
        theme_state.update(|state| {
            state.current_theme = if state.current_theme == "light" {
                "dark".to_string()
            } else {
                "light".to_string()
            };
        });
    };

    view! {
        <div class="controls">
            <button on:click=toggle_loading>"Toggle Loading"</button>
            <button on:click=switch_theme>"Switch Theme"</button>
        </div>
    }
}
```

### Pattern 5: Advanced Routing Integration

Custom routing system with language support:
```rust
use core_lib::{
    resolve_unified_route, get_localized_route, 
    get_language_switch_url, get_menu_navigation,
    detect_language_from_path, extract_lang_and_path,
    RouteResolution, NavigationItem
};

fn routing_example() -> Result<(), Box<dyn std::error::Error>> {
    // Resolve routes with language support
    let route_info = resolve_unified_route("/en/blog/my-post", "en")?;
    match route_info {
        RouteResolution::Content { component, content_type, slug, .. } => {
            println!("Content route: component={:?}, type={}, slug={}", 
                    component, content_type, slug);
        }
        RouteResolution::Page { component, .. } => {
            println!("Page route: component={:?}", component);
        }
        RouteResolution::NotFound => {
            println!("Route not found");
        }
    }
    
    // Language detection and extraction
    if let Some(detected_lang) = detect_language_from_path("/es/servicios") {
        println!("Detected language: {}", detected_lang);
        
        let (lang, path) = extract_lang_and_path("/es/servicios");
        println!("Extracted - lang: {}, path: {}", lang, path);
    }
    
    // Get localized route URLs
    let english_url = get_localized_route("services", "en")?;
    let spanish_url = get_localized_route("servicios", "es")?;
    println!("English: {}, Spanish: {}", english_url, spanish_url);
    
    // Generate language switch URLs
    let switch_url = get_language_switch_url("/en/about", "es")?;
    println!("Switch to Spanish: {}", switch_url);
    
    // Get navigation menu
    let navigation = get_menu_navigation("en")?;
    for item in navigation {
        println!("Menu item: {} -> {}", item.title, item.url);
    }
    
    Ok(())
}
```

## Available Features

### Core Features (Always Available)
- **Configuration System** - Environment-based configuration with TOML support
- **Language Discovery** - Automatic language detection from content structure
- **Content Type Resolution** - Dynamic content type discovery and validation
- **State Management** - Leptos reactive state providers and utilities
- **Utility Functions** - Text processing, slug generation, path resolution

### Optional Features (Feature-Gated)

#### Content Management (`content-static`)
- Fluent template processing
- Markdown content loading
- Static file serving integration
- Content caching and optimization

#### Hot Reload (`hot-reload`)
- File system watching
- Auto-reload on content changes
- Development mode optimizations

#### Caching (`cache`)
- Multi-level cache system (L1/L2/L3)
- Smart cache invalidation
- Performance monitoring
- Cache statistics and reporting

#### SSR Support (`ssr`)
- Server-side rendering utilities
- Hydration management
- SSR-safe state providers

## Core Components

### Configuration System
```rust
use core_lib::config::{ContentManageConfig, get_dynamic_content_config};

// Load configuration from environment
let config = ContentManageConfig::from_env();
let dynamic_config = get_dynamic_content_config();
```

### i18n and Language Management
```rust
use core_lib::{
    discover_available_languages, get_supported_languages,
    t, t_for_language, localize_url, url_localizer
};

// Dynamic language discovery
let languages = discover_available_languages();

// Translation functions
let text = t("greeting");
let text_spanish = t_for_language("greeting", "es");

// URL localization
let localized_url = localize_url("/about", "es");
```

### Content Management
```rust
use core_lib::{
    get_available_content_types, resolve_content_type_from_route,
    load_content_by_type, load_content_by_slug,
    ContentIndex, ContentPost
};

// Content type management
let content_types = get_available_content_types();
let resolved_type = resolve_content_type_from_route("/blog/post");

// Content loading
let posts = load_content_by_type("blog", "en").await?;
let specific_post = load_content_by_slug("blog", "my-post", "en").await?;
```

### Caching System
```rust
use core_lib::{Cache, CacheConfig, ContentCacheKey};

// Cache configuration
let cache_config = CacheConfig::default();
let cache = Cache::new(cache_config);

// Cache operations
let key = ContentCacheKey::new("blog", "en", "my-post");
cache.set(key, content).await?;
let cached_content = cache.get(&key).await?;
```

### Routing Engine
```rust
use core_lib::{
    resolve_unified_route, get_localized_route,
    RouteResolution, NavigationItem
};

// Route resolution
let resolution = resolve_unified_route("/en/blog/my-post", "en")?;

// Navigation generation
let nav_items = get_menu_navigation("en")?;
```

### State Providers
```rust
use core_lib::{
    AppStateProvider, LanguageProvider, ThemeProvider,
    ContentLoaderProvider, use_app_state, use_current_language
};

// Leptos components for state management
view! {
    <AppStateProvider>
        <LanguageProvider>
            <ThemeProvider>
                <ContentLoaderProvider>
                    // Your app components
                </ContentLoaderProvider>
            </ThemeProvider>
        </LanguageProvider>
    </AppStateProvider>
}
```

## Build System Integration

### Smart Cache System
```rust
// build.rs
use core_lib::build::{generate_shared_resources_with_cache, SmartCache};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Use smart cache for incremental builds
    let built = generate_shared_resources_with_cache()?;
    if built {
        println!("Resources generated successfully");
    } else {
        println!("Using cached resources");
    }
    Ok(())
}
```

### Build-Time Code Generation
The core-lib automatically generates:
- **Route Components** - From `site/config/routes/*.toml`
- **Content Types** - From content directory structure
- **Configuration Constants** - From environment variables
- **Resource Registry** - Embedded resource mappings

## Environment Configuration

### Required Environment Variables
```bash
# Content paths
SITE_CONTENT_PATH=content
SITE_SERVER_CONTENT_URL=/content

# Language configuration (optional - auto-discovered)
DEFAULT_LANGUAGE=en
SUPPORTED_LANGUAGES=en,es,fr

# Caching (optional)
SITE_DEVTOOLS_PATH=.devtools
FORCE_REBUILD_CACHE=false
SKIP_SHARED_RESOURCES_BUILD=false

# Debug level
SITE_DEBUG=1
```

### Optional Configuration File (config.toml)
```toml
[content]
root_path = "content"
server_url = "/content" 
cache_enabled = true
languages = ["en", "es", "fr"]

[design_system]
theme = "default"
spacing_scale = 1.0
color_scheme = "light"

[routing]
enable_language_prefix = true
fallback_language = "en"
strict_mode = false
```

## API Reference

### Configuration Functions
```rust
// Environment configuration
pub fn load_design_system() -> Result<DesignSystemConfig, Box<dyn std::error::Error>>
pub fn get_configured_content_path(content_type: &str, lang: &str) -> String
pub fn resolve_path(env_var: &str, default_path: &str) -> String
pub fn get_debug_value() -> i8

// Dynamic content configuration
pub fn get_dynamic_content_config() -> DynamicContentConfig
```

### Language and i18n Functions
```rust
// Language discovery
pub fn discover_available_languages() -> Vec<String>
pub fn get_default_language() -> String
pub fn get_supported_languages() -> Vec<String>
pub fn is_supported_language(lang: &str) -> bool
pub fn supported_language_count() -> usize

// Translation functions
pub fn t(key: &str) -> String
pub fn t_for_language(key: &str, language: &str) -> String
pub fn localize_url(url: &str, language: &str) -> String
```

### Content Management Functions
```rust
// Content type resolution
pub fn get_available_content_types() -> Vec<String>
pub fn resolve_content_type_from_route(route: &str) -> Option<String>
pub fn is_valid_content_type(content_type: &str) -> bool
pub fn get_content_type_display_name(content_type: &str) -> String

// Content loading
pub async fn load_content_by_type(content_type: &str, language: &str) -> Result<ContentIndex, Box<dyn std::error::Error>>
pub async fn load_content_by_slug(content_type: &str, slug: &str, language: &str) -> Result<Option<ContentPost>, Box<dyn std::error::Error>>
```

### Routing Functions
```rust
// Route resolution
pub fn resolve_unified_route(path: &str, language: &str) -> Result<RouteResolution, Box<dyn std::error::Error>>
pub fn get_localized_route(route_key: &str, language: &str) -> Result<String, Box<dyn std::error::Error>>
pub fn get_language_switch_url(current_path: &str, target_language: &str) -> Result<String, Box<dyn std::error::Error>>

// Navigation
pub fn get_menu_navigation(language: &str) -> Result<Vec<NavigationItem>, Box<dyn std::error::Error>>
pub fn detect_language_from_path(path: &str) -> Option<String>
pub fn extract_lang_and_path(path: &str) -> (String, String)
```

### State Management Functions
```rust
// Leptos state providers (use within components)
pub fn use_app_state() -> RwSignal<AppState>
pub fn use_app_state_summary() -> Signal<AppStateSummary>
pub fn use_current_language() -> Signal<String>
pub fn use_theme() -> RwSignal<ThemeState>
pub fn use_auth_state() -> RwSignal<AuthState>
pub fn use_content_loader() -> Signal<ReactiveContentLoader>
pub fn use_route_state() -> Signal<RouteState>
```

### Build System Functions
```rust
// Build-time generation
pub fn generate_shared_resources() -> Result<(), Box<dyn std::error::Error>>
pub fn generate_shared_resources_with_cache() -> Result<bool, Box<dyn std::error::Error>>
```

### Resource Loading Functions
```rust
// Resource loading
pub fn load_menu_for_language(lang: &str) -> Result<MenuConfig, Box<dyn std::error::Error>>
pub fn load_reactive_menu_for_language(lang: &str) -> Result<Vec<MenuItem>, Box<dyn std::error::Error>>
pub fn load_footer_for_language(lang: &str) -> Result<FooterConfig, Box<dyn std::error::Error>>
pub fn load_theme(name: &str) -> Result<ThemeConfig, Box<dyn std::error::Error>>
```

## Documentation

- [📚 Usage Patterns](docs/USAGE_PATTERNS.md) - Detailed usage examples and patterns
- [⚙️ Configuration Guide](docs/CONFIGURATION.md) - Complete configuration reference
- [🌍 i18n Guide](docs/I18N_GUIDE.md) - Internationalization system usage
- [📝 Content Management Guide](docs/CONTENT_GUIDE.md) - Content system integration
- [🗂️ State Management Guide](docs/STATE_GUIDE.md) - Leptos state management patterns
- [🧭 Routing Guide](docs/ROUTING_GUIDE.md) - Custom routing system usage
- [🔧 Build System Guide](docs/BUILD_GUIDE.md) - Build-time generation and caching

## Examples

- [📁 examples/](examples/) - Complete usage examples
- [⚙️ Configuration Setup](examples/config_setup.rs) - Configuration system setup
- [🌍 Language Setup](examples/language_setup.rs) - i18n system setup
- [📝 Content Management](examples/content_management.rs) - Content loading and management
- [🗂️ State Management](examples/state_management.rs) - Leptos state provider usage
- [🧭 Routing Examples](examples/routing_examples.rs) - Route resolution and navigation
- [🎨 Theme Integration](examples/theme_integration.rs) - Theme system usage
- [⚡ Build Integration](examples/build_integration.rs) - Build system integration

## Feature Flags

```toml
[dependencies.core-lib]
path = "path/to/core-lib"
features = [
    "content-static",  # Static content management
    "hot-reload",      # Development hot reload
    "cache",           # Multi-level caching system
    "ssr",             # Server-side rendering support
]
```

## Advanced Integration

### Custom Content Types
```rust
// Register custom content types at runtime
use core_lib::{content::traits::ContentManageConfig, create_content_kind_registry};

fn register_custom_content_types() {
    let mut registry = create_content_kind_registry();
    
    registry.insert("tutorial".to_string(), ContentManageConfig {
        name: "tutorial".to_string(),
        directory: "tutorials".to_string(),
        enabled: true,
        is_default: Some(false),
        specialized: Some(vec!["interactive".to_string()]),
        features: Default::default(),
    });
}
```

### Custom State Providers
```rust
use core_lib::{AppStateProvider, use_app_state};
use leptos::*;

#[component]
pub fn CustomStateProvider(children: Children) -> impl IntoView {
    let app_state = use_app_state();
    
    // Add custom initialization logic
    create_effect(move |_| {
        // Initialize custom state
        app_state.update(|state| {
            state.ready = true;
            // Add custom state properties
        });
    });

    view! {
        <div class="custom-state-provider">
            {children()}
        </div>
    }
}
```

## Performance Tips

1. **Use Smart Caching** - Enable the `cache` feature for production builds
2. **Language Discovery** - Languages are automatically discovered; avoid hardcoding
3. **Content Type Resolution** - Use caching for content type lookups
4. **State Management** - Use specific state providers instead of global state
5. **Build-Time Generation** - Use build-time generation for better performance

## Troubleshooting

### Common Issues
1. **Missing generated code** - Ensure `has_generated_resources` cfg is set by build.rs
2. **Language not detected** - Check content structure follows `content/{lang}/` pattern
3. **Content type not found** - Verify content-kinds.toml exists and is valid
4. **State not updating** - Ensure proper provider hierarchy in Leptos components
5. **Cache not working** - Check SITE_DEVTOOLS_PATH environment variable

### Debug Mode
Enable debug logging:
```bash
SITE_DEBUG=2 cargo leptos watch
```

Debug levels:
- 0: No debug output
- 1: Main debug information
- 2: Complementary debug information  
- 3+: Route lookup and rendering traces

## Contributing

The core-lib foundation is designed to be extended:

1. **Add utilities** - Extend utility functions for common tasks
2. **Improve i18n** - Add support for more localization features
3. **Enhance caching** - Implement additional cache strategies
4. **Add state providers** - Create specialized state management
5. **Improve build system** - Optimize build-time generation

## License

MIT License - See LICENSE file for details.
