# Pages Foundation System Guide

## Overview

The pages foundation provides a comprehensive page generation and template system for Rustelo applications, supporting both static page components and dynamic content-driven page generation.

## Core Concepts

### 1. Page Components
Pre-built Leptos components for common page types:

```rust
use pages::{HomePage, AboutPage, ContactPage};

// Direct component usage
#[component]
fn App() -> impl IntoView {
    view! {
        <Router>
            <Routes>
                <Route path="/" view=HomePage />
                <Route path="/about" view=AboutPage />
                <Route path="/contact" view=ContactPage />
            </Routes>
        </Router>
    }
}
```

### 2. Content-Driven Pages
Dynamic pages generated from content configuration:

```rust
use pages::{ContentIndexPage, ContentCategoryPage};

// Content-based routing
view! {
    <Routes>
        // Blog index page
        <Route path="/blog" view=move || {
            ContentIndexPage {
                content_type: "blog".to_string(),
                layout: "grid".to_string(),
                per_page: Some(10),
            }
        } />
        
        // Category pages
        <Route path="/blog/:category" view=ContentCategoryPage />
    </Routes>
}
```

### 3. Page Generation System
Static page generation for build-time optimization:

```rust
use pages::{PageGenerator, PageGenerationConfig, ContentSource};

#[tokio::main]
async fn main() -> Result<(), PageError> {
    let config = PageGenerationConfig::builder()
        .content_source(ContentSource::Directory("content/".into()))
        .template_directory("templates/".into())
        .output_directory("generated/".into())
        .languages(vec!["en", "es", "fr"])
        .content_types(vec!["blog", "docs", "portfolio"])
        .enable_i18n(true)
        .enable_seo(true)
        .build();

    let generator = PageGenerator::new(config);
    generator.generate_all().await?;
    
    println!("Generated {} pages", generator.page_count());
    Ok(())
}
```

## Page Component Architecture

### Unified Page Pattern
Each page type provides both direct and unified implementations:

```rust
// Direct usage - simple component
use pages::AboutPage;

view! { <AboutPage /> }

// Unified usage - configurable component  
use pages::UnifiedAboutPage;

view! {
    <UnifiedAboutPage
        title="About Our Company"
        subtitle="Learn about our mission and values"
        content_source="content/about.md"
        layout="centered"
        show_team=true
        show_history=true
    />
}
```

### Page Configuration
Configure pages through props and configuration objects:

```rust
use pages::{PageConfig, LayoutConfig, SeoConfig};

let page_config = PageConfig::builder()
    .title("Custom Page Title")
    .description("Page description for SEO")
    .keywords(vec!["rust", "web", "leptos"])
    .layout(LayoutConfig {
        sidebar: true,
        breadcrumbs: true,
        table_of_contents: true,
        ..Default::default()
    })
    .seo(SeoConfig {
        canonical_url: Some("https://example.com/page".to_string()),
        og_image: Some("/images/page-og.jpg".to_string()),
        schema_type: Some("Article".to_string()),
        ..Default::default()
    })
    .build();

view! {
    <UnifiedCustomPage config=page_config>
        // Page content
    </UnifiedCustomPage>
}
```

## Content Integration

### Markdown Processing
Process markdown files with frontmatter:

```rust
use pages::{MarkdownProcessor, FrontmatterConfig};

let processor = MarkdownProcessor::new()
    .content_directory("content/blog/")
    .frontmatter_config(FrontmatterConfig {
        required_fields: vec!["title", "date", "author"],
        optional_fields: vec!["tags", "category", "featured"],
        date_format: "%Y-%m-%d".to_string(),
    })
    .markdown_options(MarkdownOptions {
        enable_tables: true,
        enable_strikethrough: true,
        enable_code_highlighting: true,
        enable_math: true,
    });

let processed_content = processor.process_file("my-post.md").await?;
println!("Title: {}", processed_content.frontmatter.title);
```

### Content Source Abstraction
Support multiple content sources:

```rust
use pages::{ContentSource, DatabaseSource, APISource};

// File system source
let fs_source = ContentSource::Directory("content/".into());

// Database source  
let db_source = ContentSource::Database(DatabaseSource {
    connection_string: "postgresql://...".to_string(),
    table_name: "posts".to_string(),
    content_field: "body".to_string(),
    metadata_fields: vec!["title", "author", "created_at"],
});

// API source
let api_source = ContentSource::API(APISource {
    base_url: "https://api.example.com".to_string(),
    endpoints: vec![
        ("posts", "/posts"),
        ("pages", "/pages"),
    ].into_iter().collect(),
    auth_header: Some("Bearer token".to_string()),
});

let generator = PageGenerator::new(config)
    .with_content_source(fs_source)
    .with_fallback_source(db_source);
```

## Template System

### Built-in Templates
Use pre-defined page templates:

```rust
use pages::{PageTemplate, TemplateConfig};

// Blog post template
let blog_template = PageTemplate::Blog(BlogTemplateConfig {
    show_author: true,
    show_date: true,
    show_tags: true,
    show_related_posts: true,
    enable_comments: true,
    sidebar_position: SidebarPosition::Right,
});

// Documentation template
let docs_template = PageTemplate::Documentation(DocsTemplateConfig {
    show_toc: true,
    show_breadcrumbs: true,
    show_edit_link: true,
    show_last_updated: true,
    navigation_position: NavigationPosition::Left,
});

// Landing page template
let landing_template = PageTemplate::Landing(LandingTemplateConfig {
    hero_section: true,
    features_section: true,
    testimonials_section: true,
    cta_section: true,
    layout: LandingLayout::Modern,
});
```

### Custom Templates
Create custom page templates:

```rust
use pages::{CustomTemplate, TemplateBuilder};

#[component]
fn MyCustomTemplate(
    #[prop(into)] title: String,
    #[prop(into)] content: String,
    #[prop(optional)] sidebar: Option<View>,
    children: Children,
) -> impl IntoView {
    view! {
        <div class="custom-template">
            <header class="template-header">
                <h1>{title}</h1>
            </header>
            
            <div class="template-body">
                <main class="template-content">
                    <div class="content-body" inner_html=content />
                    {children()}
                </main>
                
                {sidebar.map(|s| view! {
                    <aside class="template-sidebar">
                        {s}
                    </aside>
                })}
            </div>
        </div>
    }
}

// Register custom template
let template_registry = TemplateRegistry::new()
    .register("my-custom", MyCustomTemplate::template_definition())
    .register_helper("format_date", format_date_helper)
    .register_partial("author_bio", author_bio_partial);
```

## Page Generation Pipeline

### Generation Process
The page generation system follows a structured pipeline:

```rust
use pages::{GenerationPipeline, GenerationStage};

let pipeline = GenerationPipeline::new()
    .add_stage(GenerationStage::ContentDiscovery)  // Find all content
    .add_stage(GenerationStage::FrontmatterParsing) // Parse metadata
    .add_stage(GenerationStage::ContentProcessing) // Process markdown/content
    .add_stage(GenerationStage::TemplateApplication) // Apply templates
    .add_stage(GenerationStage::I18nProcessing)    // Handle translations
    .add_stage(GenerationStage::SEOOptimization)   // Add SEO metadata
    .add_stage(GenerationStage::OutputGeneration)  // Write final files
    .add_stage(GenerationStage::IndexGeneration);  // Create indexes/sitemaps

// Execute pipeline with progress tracking
pipeline.execute_with_progress(|stage, progress| {
    println!("Stage {}: {}% complete", stage, progress);
}).await?;
```

### Build Integration
Integrate with Rust build systems:

```rust
// In build.rs
use pages::{BuildTimeGenerator, BuildConfig};

fn main() {
    let config = BuildConfig::from_env()
        .unwrap_or_else(BuildConfig::default);
    
    if config.enable_page_generation {
        let generator = BuildTimeGenerator::new(config);
        generator.generate_all()
            .expect("Failed to generate pages");
            
        println!("cargo:rerun-if-changed=content/");
        println!("cargo:rerun-if-changed=templates/");
    }
}
```

## Internationalization Support

### Multi-language Page Generation
Generate pages for multiple languages:

```rust
use pages::{I18nConfig, LanguageConfig, TranslationSource};

let i18n_config = I18nConfig::builder()
    .default_language("en")
    .supported_languages(vec![
        LanguageConfig {
            code: "en",
            name: "English",
            locale: "en-US",
            direction: TextDirection::LeftToRight,
        },
        LanguageConfig {
            code: "es", 
            name: "Español",
            locale: "es-ES",
            direction: TextDirection::LeftToRight,
        },
        LanguageConfig {
            code: "ar",
            name: "العربية", 
            locale: "ar-SA",
            direction: TextDirection::RightToLeft,
        },
    ])
    .translation_source(TranslationSource::Fluent("locales/"))
    .url_strategy(UrlStrategy::PathPrefix) // /en/page, /es/page
    .fallback_strategy(FallbackStrategy::DefaultLanguage)
    .build();

let generator = PageGenerator::new(config)
    .with_i18n(i18n_config);

// Generates: /en/about, /es/about, /ar/about
generator.generate_all().await?;
```

### Content Translation
Handle translated content:

```rust
use pages::{TranslatableContent, ContentTranslation};

let translatable_content = TranslatableContent::new()
    .add_translation("en", ContentTranslation {
        title: "About Us".to_string(),
        content: "We are a technology company...".to_string(),
        metadata: hashmap!{
            "author" => "John Doe",
            "category" => "company",
        },
    })
    .add_translation("es", ContentTranslation {
        title: "Acerca de Nosotros".to_string(), 
        content: "Somos una empresa de tecnología...".to_string(),
        metadata: hashmap!{
            "author" => "Juan Pérez",
            "category" => "empresa", 
        },
    });

// Generate page for specific language
let spanish_page = generator
    .generate_page(translatable_content, "es")
    .await?;
```

## SEO and Performance Optimization

### SEO Features
Built-in SEO optimization:

```rust
use pages::{SEOConfig, MetaTagGenerator, StructuredDataGenerator};

let seo_config = SEOConfig::builder()
    .site_name("My Website")
    .default_author("Website Author")
    .default_image("/images/default-og.jpg")
    .twitter_handle("@mywebsite")
    .enable_structured_data(true)
    .enable_open_graph(true)
    .enable_twitter_cards(true)
    .enable_sitemap_generation(true)
    .build();

// Automatic meta tag generation
let meta_generator = MetaTagGenerator::new(seo_config);
let meta_tags = meta_generator.generate_for_page(&page_content);

// Structured data generation
let structured_data = StructuredDataGenerator::new()
    .generate_article_schema(&blog_post)
    .generate_breadcrumb_schema(&breadcrumbs)
    .generate_website_schema(&site_config);
```

### Performance Optimization
Built-in performance features:

```rust
use pages::{PerformanceConfig, OptimizationLevel};

let perf_config = PerformanceConfig::builder()
    .optimization_level(OptimizationLevel::High)
    .enable_image_optimization(true)
    .enable_css_minification(true)
    .enable_html_minification(true)
    .enable_preloading(true)
    .enable_lazy_loading(true)
    .critical_css_extraction(true)
    .build();

let optimized_pages = generator
    .with_performance_config(perf_config)
    .generate_optimized().await?;
```

## Error Handling and Validation

### Content Validation
Validate content before generation:

```rust
use pages::{ContentValidator, ValidationRule, ValidationResult};

let validator = ContentValidator::new()
    .add_rule(ValidationRule::RequiredFrontmatter(vec!["title", "date"]))
    .add_rule(ValidationRule::ValidDateFormat("%Y-%m-%d"))
    .add_rule(ValidationRule::MinContentLength(100))
    .add_rule(ValidationRule::ValidImageReferences)
    .add_rule(ValidationRule::ValidInternalLinks)
    .add_rule(ValidationRule::SEORequirements);

match validator.validate_content(&content) {
    ValidationResult::Valid => println!("Content is valid"),
    ValidationResult::Invalid(errors) => {
        for error in errors {
            eprintln!("Validation error: {}", error);
        }
    }
}
```

### Error Recovery
Handle generation errors gracefully:

```rust
use pages::{ErrorRecovery, GenerationError};

let recovery = ErrorRecovery::new()
    .on_missing_content(|path| {
        eprintln!("Missing content: {}", path);
        Ok(default_content_for_path(path))
    })
    .on_template_error(|template, error| {
        eprintln!("Template error in {}: {}", template, error);
        Ok(fallback_template())
    })
    .on_i18n_missing(|key, language| {
        eprintln!("Missing translation: {} for {}", key, language);
        Ok(fallback_translation(key, language))
    });

let generator = PageGenerator::new(config)
    .with_error_recovery(recovery);
```

## Testing and Development

### Development Mode
Special development features:

```rust
use pages::{DevelopmentConfig, HotReload};

let dev_config = DevelopmentConfig::builder()
    .enable_hot_reload(true)
    .enable_debug_output(true)
    .enable_content_validation(true)
    .enable_template_debugging(true)
    .watch_directories(vec!["content/", "templates/"])
    .build();

let dev_generator = PageGenerator::new(config)
    .with_development_config(dev_config);

// Start development server with hot reload
dev_generator.start_dev_server("localhost:3030").await?;
```

### Testing Utilities
Test page generation:

```rust
use pages::{PageTester, TestConfig};

#[tokio::test]
async fn test_page_generation() {
    let test_config = TestConfig::builder()
        .test_content_dir("tests/fixtures/content/")
        .test_templates_dir("tests/fixtures/templates/") 
        .expected_output_dir("tests/expected/")
        .build();

    let tester = PageTester::new(test_config);
    
    let result = tester
        .generate_test_pages()
        .await
        .expect("Page generation failed");
    
    assert_eq!(result.pages_generated, 15);
    assert_eq!(result.errors.len(), 0);
    
    // Validate generated content matches expectations
    tester.validate_against_expected().await.unwrap();
}
```

## Best Practices

### 1. Content Organization
- Use consistent frontmatter structure
- Organize content in logical directory hierarchies
- Use meaningful file naming conventions
- Include required metadata in all content files

### 2. Template Design
- Create reusable template components
- Use semantic HTML structure
- Implement responsive design patterns
- Include proper accessibility features

### 3. Performance Considerations
- Optimize images and assets during generation
- Use lazy loading for non-critical content
- Implement proper caching headers
- Minimize generated HTML and CSS

### 4. SEO Optimization
- Include proper meta tags and structured data
- Generate XML sitemaps automatically
- Optimize page loading performance
- Use semantic URL structures

### 5. Internationalization
- Plan URL structure for multiple languages
- Use consistent translation keys
- Implement proper RTL support when needed
- Test with actual translated content

The pages foundation provides a complete system for building content-rich websites with excellent developer experience, performance, and maintainability.
