# Rustelo Components

Welcome to the Rustelo Components documentation! This section covers all the built-in components and utilities available in the Rustelo framework.

## 📦 Available Components

### Authentication Components
- **[Authentication System](./auth.md)** - User authentication, JWT tokens, and session management
- Login/Register forms
- Password reset functionality
- User profile management
- Role-based access control

### Content Management
- **[Content System](./content.md)** - Content creation, editing, and management
- Markdown rendering
- File uploads and media management
- Content versioning
- Search functionality

### Email System
- **[Email Components](./email.md)** - Email sending and template management
- SMTP configuration
- Email templates
- Queue management
- Notification system

### Configuration
- **[Configuration System](./config.md)** - Application configuration management
- Environment-based configs
- Feature toggles
- Runtime configuration
- Validation and schema

### Templates & UI
- **[Template System](./templates.md)** - UI templates and components
- Responsive layouts
- Theme system
- Component library
- Style utilities

## 🎯 Component Architecture

Rustelo follows a modular component architecture where each component is:

- **Self-contained** - Each component manages its own state and dependencies
- **Configurable** - Components can be enabled/disabled via features
- **Extensible** - Easy to customize and extend for your needs
- **Well-documented** - Complete API documentation and examples

## 🚀 Getting Started

### Enable Components

Components are enabled through Cargo features:

```toml
[dependencies]
server = { path = "../server", features = ["auth", "content-db", "email"] }
```

### Basic Usage

```rust
use rustelo::components::{Auth, Content, Email};

// Initialize components
let auth = Auth::new(config.auth)?;
let content = Content::new(config.content)?;
let email = Email::new(config.email)?;
```

## 📋 Component Status

| Component | Status | Features | Documentation |
|-----------|--------|----------|---------------|
| Authentication | ✅ Complete | `auth` | [View](./auth.md) |
| Content Management | ✅ Complete | `content-db` | [View](./content.md) |
| Email System | ✅ Complete | `email` | [View](./email.md) |
| Configuration | ✅ Complete | Always enabled | [View](./config.md) |
| Templates | ✅ Complete | Always enabled | [View](./templates.md) |

## 🔧 Component Development

### Creating Custom Components

```rust
use rustelo::Component;

pub struct MyComponent {
    config: MyConfig,
}

impl Component for MyComponent {
    type Config = MyConfig;
    
    fn new(config: Self::Config) -> Result<Self, Error> {
        Ok(Self { config })
    }
    
    fn initialize(&mut self) -> Result<(), Error> {
        // Initialize component
        Ok(())
    }
}
```

### Component Lifecycle

1. **Configuration** - Load component configuration
2. **Initialization** - Set up component state
3. **Registration** - Register routes and handlers
4. **Runtime** - Handle requests and events
5. **Cleanup** - Graceful shutdown

## 🎨 Frontend Components

### Leptos Components

```rust
use leptos::*;
use rustelo::components::*;

#[component]
pub fn App() -> impl IntoView {
    view! {
        <AuthProvider>
            <ContentProvider>
                <Router>
                    <Routes>
                        <Route path="/" view=HomePage/>
                        <Route path="/login" view=LoginPage/>
                        <Route path="/dashboard" view=DashboardPage/>
                    </Routes>
                </Router>
            </ContentProvider>
        </AuthProvider>
    }
}
```

### Styling Components

```rust
use rustelo::ui::*;

#[component]
pub fn MyPage() -> impl IntoView {
    view! {
        <Page title="My Page">
            <Card>
                <CardHeader>
                    <h2>"Welcome"</h2>
                </CardHeader>
                <CardBody>
                    <p>"Content goes here"</p>
                </CardBody>
            </Card>
        </Page>
    }
}
```

## 🔍 Component APIs

### Authentication API

```rust
// Check if user is authenticated
let is_authenticated = auth.is_authenticated(&request)?;

// Get current user
let user = auth.get_current_user(&request)?;

// Login user
let token = auth.login(&credentials)?;
```

### Content API

```rust
// Create content
let content = content_manager.create(CreateContentRequest {
    title: "My Article".to_string(),
    body: "Article content...".to_string(),
    content_type: ContentType::Article,
})?;

// Get content
let content = content_manager.get_by_id(content_id)?;
```

### Email API

```rust
// Send email
email_service.send(SendEmailRequest {
    to: "user@example.com".to_string(),
    subject: "Welcome!".to_string(),
    template: "welcome".to_string(),
    data: serde_json::json!({
        "name": "John Doe"
    }),
})?;
```

## 📊 Performance Considerations

### Component Optimization

- **Lazy Loading** - Components are initialized only when needed
- **Caching** - Built-in caching for frequently accessed data
- **Connection Pooling** - Efficient database and external service connections
- **Async Operations** - Non-blocking I/O operations

### Resource Management

```rust
// Components automatically manage resources
impl Drop for MyComponent {
    fn drop(&mut self) {
        // Cleanup resources
        self.cleanup();
    }
}
```

## 🧪 Testing Components

### Unit Tests

```rust
#[cfg(test)]
mod tests {
    use super::*;
    use rustelo::testing::*;
    
    #[tokio::test]
    async fn test_auth_component() {
        let config = test_config();
        let auth = Auth::new(config.auth).unwrap();
        
        // Test authentication
        assert!(auth.is_authenticated(&test_request()).is_ok());
    }
}
```

### Integration Tests

```rust
#[tokio::test]
async fn test_component_integration() {
    let app = test_app().await;
    
    // Test component interactions
    let response = app.post("/api/auth/login")
        .json(&login_request())
        .send()
        .await?;
        
    assert_eq!(response.status(), 200);
}
```

## 🔐 Security

### Security Best Practices

- **Input Validation** - All inputs are validated and sanitized
- **Authentication** - Secure token-based authentication
- **Authorization** - Role-based access control
- **CSRF Protection** - Built-in CSRF token validation
- **Rate Limiting** - Configurable rate limiting

### Security Configuration

```toml
[security]
csrf_protection = true
rate_limiting = true
secure_cookies = true
https_only = true
```

## 📚 Next Steps

1. **[Authentication Guide](./auth.md)** - Set up user authentication
2. **[Content Management](./content.md)** - Manage application content
3. **[Email System](./email.md)** - Configure email functionality
4. **[Configuration](./config.md)** - Understand configuration options
5. **[Templates](./templates.md)** - Customize UI templates

## 🆘 Getting Help

- **[Common Issues](../../troubleshooting/common.md)** - Solutions to common problems
- **[API Reference](../../api/overview.md)** - Complete API documentation
- **[Examples](../../advanced/integrations.md)** - Real-world examples
- **Community Support** - Discord, GitHub Issues, Stack Overflow

---

**Happy building with Rustelo components!** 🦀✨