# Components Foundation Usage Patterns

## Overview
The components foundation provides multiple usage patterns to fit different application needs, from simple component imports to complex themed applications.

## Pattern 1: Direct Component Import (Simplest)

**Best for**: Simple applications, specific component needs

```rust
use components::{
    navigation::BrandHeader,
    content::UnifiedContentCard,
    ui::SpaLink,
};

#[component]
fn HomePage() -> impl IntoView {
    view! {
        <BrandHeader />
        <main>
            <UnifiedContentCard title="Welcome">
                <p>"Hello World"</p>
                <SpaLink href="/about">"Learn More"</SpaLink>
            </UnifiedContentCard>
        </main>
    }
}
```

**What you get**:
- Individual components as needed
- Minimal bundle size
- Full component functionality

**Customization**: Component props and CSS classes

## Pattern 2: Category Import

**Best for**: Using multiple related components

```rust
use components::{
    navigation::*,  // BrandHeader, Footer, NavMenu, etc.
    content::*,     // All content components
    ui::*,          // All UI utilities
};

#[component]
fn AppLayout() -> impl IntoView {
    view! {
        <BrandHeader>
            <NavMenu />
        </BrandHeader>
        
        <main>
            <UnifiedContentCard title="Content">
                <SimpleContentGrid>
                    // Content items
                </SimpleContentGrid>
            </UnifiedContentCard>
        </main>
        
        <Footer />
    }
}
```

**What you get**:
- All components from specific categories
- Consistent component families
- Easy access to related functionality

**Customization**: Mix and match components from different categories

## Pattern 3: Themed Application

**Best for**: Applications with consistent branding and theming

```rust
use components::{
    theme::{ThemeProvider, ThemeConfig, use_theme},
    navigation::*,
    content::*,
};

#[component]
pub fn ThemedApp() -> impl IntoView {
    let theme_config = ThemeConfig::builder()
        .primary_color("#007acc")
        .secondary_color("#f0f8ff")
        .font_family("Inter, sans-serif")
        .font_size_base("16px")
        .border_radius("8px")
        .build();

    view! {
        <ThemeProvider config=theme_config>
            <AppContent />
        </ThemeProvider>
    }
}

#[component]
fn AppContent() -> impl IntoView {
    let theme = use_theme();
    
    view! {
        <div style=format!("background: {}", theme.primary_color())>
            <BrandHeader />
            <main style=format!("font-family: {}", theme.font_family())>
                <UnifiedContentCard>
                    "Themed content"
                </UnifiedContentCard>
            </main>
        </div>
    }
}
```

**What you get**:
- Consistent theming across all components
- Theme context available to custom components
- Built-in dark/light mode support

**Customization**: Custom theme configuration, theme switching

## Pattern 4: Extended Components

**Best for**: Custom functionality built on foundation components

```rust
use components::{
    content::{UnifiedContentCard, ContentManager},
    ui::SpaLink,
    theme::use_theme,
};

// Extend foundation components with custom logic
#[component]
pub fn BlogCard(
    #[prop(into)] title: String,
    #[prop(into)] excerpt: String,
    #[prop(into)] slug: String,
    #[prop(into)] date: String,
) -> impl IntoView {
    let theme = use_theme();
    
    view! {
        <UnifiedContentCard title=title>
            <div class="blog-card-content">
                <p class="excerpt">{excerpt}</p>
                <div class="blog-meta">
                    <span class="date" style=format!("color: {}", theme.text_muted())>
                        {date}
                    </span>
                    <SpaLink href=format!("/blog/{}", slug) class="read-more">
                        "Read More →"
                    </SpaLink>
                </div>
            </div>
        </UnifiedContentCard>
    }
}

// Create custom component collections
#[component]
pub fn BlogGrid(posts: ReadSignal<Vec<BlogPost>>) -> impl IntoView {
    view! {
        <div class="blog-grid">
            <For
                each=move || posts.get()
                key=|post| post.id.clone()
                children=move |post| {
                    view! {
                        <BlogCard
                            title=post.title
                            excerpt=post.excerpt
                            slug=post.slug
                            date=post.published_date
                        />
                    }
                }
            />
        </div>
    }
}
```

**What you get**:
- Custom components built on foundation
- Reusable component patterns
- Integration with foundation theming

**Customization**: Full control over extended component behavior

## Pattern 5: Modular Composition

**Best for**: Complex applications with feature-based component organization

```rust
use components::{
    navigation::{BrandHeader, Footer},
    content::ContentManager,
    ui::{SpaLink, MobileMenu},
    theme::ThemeProvider,
    admin::{AdminLayout, AdminCard},
};

// Feature-based component modules
pub mod blog_components {
    use super::*;
    
    #[component]
    pub fn BlogHeader() -> impl IntoView {
        view! {
            <BrandHeader>
                <nav class="blog-nav">
                    <SpaLink href="/blog">"Blog"</SpaLink>
                    <SpaLink href="/blog/categories">"Categories"</SpaLink>
                    <SpaLink href="/blog/archive">"Archive"</SpaLink>
                </nav>
            </BrandHeader>
        }
    }
    
    #[component]
    pub fn BlogLayout(children: Children) -> impl IntoView {
        view! {
            <div class="blog-layout">
                <BlogHeader />
                <main class="blog-main">
                    {children()}
                </main>
                <Footer />
            </div>
        }
    }
}

pub mod admin_components {
    use super::*;
    
    #[component]
    pub fn AdminBlogManager() -> impl IntoView {
        view! {
            <AdminLayout title="Blog Management">
                <AdminCard title="Recent Posts">
                    <ContentManager content_type="blog" limit=10 />
                </AdminCard>
                
                <AdminCard title="Quick Actions">
                    <div class="admin-actions">
                        <SpaLink href="/admin/blog/new" class="btn btn-primary">
                            "New Post"
                        </SpaLink>
                        <SpaLink href="/admin/blog/drafts" class="btn btn-secondary">
                            "Drafts"
                        </SpaLink>
                    </div>
                </AdminCard>
            </AdminLayout>
        }
    }
}

// Main app composition
#[component]
pub fn App() -> impl IntoView {
    view! {
        <ThemeProvider>
            <Router>
                <Routes>
                    <Route path="/blog/*" view=blog_components::BlogLayout />
                    <Route path="/admin/*" view=admin_components::AdminBlogManager />
                </Routes>
            </Router>
        </ThemeProvider>
    }
}
```

**What you get**:
- Feature-organized component modules
- Selective component usage
- Clean separation of concerns

**Customization**: Module-based customization and feature flags

## Responsive Design Patterns

### Mobile-First Components
```rust
use components::{
    navigation::BrandHeader,
    ui::{MobileMenu, MobileMenuToggle},
    theme::use_theme,
};

#[component]
pub fn ResponsiveHeader() -> impl IntoView {
    let (mobile_menu_open, set_mobile_menu_open) = create_signal(false);
    
    view! {
        <BrandHeader>
            // Desktop navigation
            <nav class="hidden md:block">
                <SpaLink href="/">"Home"</SpaLink>
                <SpaLink href="/about">"About"</SpaLink>
                <SpaLink href="/contact">"Contact"</SpaLink>
            </nav>
            
            // Mobile menu toggle
            <div class="md:hidden">
                <MobileMenuToggle 
                    is_open=mobile_menu_open
                    on_toggle=move |_| set_mobile_menu_open.update(|open| *open = !*open)
                />
            </div>
        </BrandHeader>
        
        // Mobile menu
        <MobileMenu 
            is_open=mobile_menu_open
            on_close=move |_| set_mobile_menu_open.set(false)
        >
            <SpaLink href="/">"Home"</SpaLink>
            <SpaLink href="/about">"About"</SpaLink>
            <SpaLink href="/contact">"Contact"</SpaLink>
        </MobileMenu>
    }
}
```

## Error Handling Patterns

### Component Error Boundaries
```rust
use components::{content::UnifiedContentCard, ui::SpaLink};

#[component]
pub fn SafeContentCard(
    #[prop(into)] title: String,
    #[prop(optional)] fallback: Option<View>,
) -> impl IntoView {
    let content = create_resource(
        || (), 
        |_| async move { load_content().await }
    );
    
    view! {
        <UnifiedContentCard title=title>
            <Suspense fallback=|| view! { <div>"Loading..."</div> }>
                <ErrorBoundary fallback=move |errors| {
                    match fallback {
                        Some(fallback_view) => fallback_view,
                        None => view! {
                            <div class="error-state">
                                <p>"Unable to load content"</p>
                                <SpaLink href="/" class="btn btn-primary">
                                    "Go Home"
                                </SpaLink>
                            </div>
                        }.into_view(),
                    }
                }>
                    {move || {
                        content.get()
                            .map(|result| match result {
                                Ok(content) => view! { <div>{content}</div> },
                                Err(_) => view! { <div>"Error loading content"</div> },
                            })
                    }}
                </ErrorBoundary>
            </Suspense>
        </UnifiedContentCard>
    }
}
```

## Performance Optimization Patterns

### Lazy Loading Components
```rust
use components::{content::ContentManager, ui::SpaLink};

#[component]
pub fn LazyContentSection(
    #[prop(into)] section_id: String,
) -> impl IntoView {
    let (is_visible, set_is_visible) = create_signal(false);
    let section_ref = create_node_ref::<html::Div>();
    
    // Intersection observer for lazy loading
    create_effect(move |_| {
        if let Some(section) = section_ref.get() {
            let observer = web_sys::IntersectionObserver::new(&wasm_bindgen::Closure::wrap(
                Box::new(move |entries: js_sys::Array, _observer| {
                    if entries.length() > 0 {
                        set_is_visible.set(true);
                    }
                }) as Box<dyn Fn(js_sys::Array, web_sys::IntersectionObserver)>
            ).into_js_value().unchecked_into()).unwrap();
            
            observer.observe(&section);
        }
    });
    
    view! {
        <div node_ref=section_ref class="lazy-section">
            {move || {
                if is_visible.get() {
                    view! {
                        <ContentManager 
                            content_type="section"
                            filter=section_id.clone()
                        />
                    }
                } else {
                    view! {
                        <div class="lazy-placeholder">
                            "Loading section..."
                        </div>
                    }
                }
            }}
        </div>
    }
}
```

## Choosing the Right Pattern

| Need | Pattern | Complexity | Bundle Size | Flexibility |
|------|---------|------------|-------------|-------------|
| Single component | Direct Import | Low | Minimal | Low |
| Related components | Category Import | Low | Small | Medium |
| Consistent styling | Themed Application | Medium | Medium | Medium |
| Custom functionality | Extended Components | Medium | Variable | High |
| Complex apps | Modular Composition | High | Optimized | Maximum |

## Migration Path

1. **Start Simple**: Use direct imports for initial development
2. **Add Theming**: Introduce ThemeProvider when styling becomes complex
3. **Create Extensions**: Build custom components as needs grow
4. **Organize Modularly**: Structure into feature modules for large apps

Each pattern builds on the foundation components, so migration is incremental and non-breaking.
