# Platform Homepage & Content Pages

## Overview

The Platform Homepage feature provides a customizable, CMS-driven public homepage and content pages for your multi-store marketplace platform at the root domain (e.g., `localhost:8000` or `platform.com`).

**Key Features:**
- ✅ CMS-driven customizable homepage with multiple templates
- ✅ Multiple content pages (About, FAQ, Contact, Terms, Privacy)
- ✅ Dynamic header and footer navigation
- ✅ Responsive design with dark mode support
- ✅ SEO-optimized with meta tags
- ✅ Template selection system (default, minimal, modern)

---

## Architecture

### URL Structure

| URL | Purpose | CMS Slug | Template |
|-----|---------|----------|----------|
| `/` | Platform Homepage | `platform_homepage` | Customizable (default/minimal/modern) |
| `/about` | About Us | `about` | `platform/content-page.html` |
| `/faq` | FAQ | `faq` | `platform/content-page.html` |
| `/contact` | Contact Us | `contact` | `platform/content-page.html` |
| `/terms` | Terms of Service | `terms` | `platform/content-page.html` |
| `/privacy` | Privacy Policy | `privacy` | `platform/content-page.html` |

### Database Model

All platform pages are stored in the `content_pages` table with `store_id = NULL`:

```sql
-- Platform homepage
INSERT INTO content_pages (store_id, slug, title, template, ...)
VALUES (NULL, 'platform_homepage', 'Welcome', 'modern', ...);

-- Content pages
INSERT INTO content_pages (store_id, slug, title, ...)
VALUES (NULL, 'about', 'About Us', ...);
```

### Navigation System

Pages are configured to appear in header/footer navigation using flags:

| Field | Purpose | Example |
|-------|---------|---------|
| `show_in_header` | Display in top navigation | About, FAQ, Contact |
| `show_in_footer` | Display in footer links | All pages |
| `display_order` | Sort order in menus | 1, 2, 3, ... |

---

## File Structure

```
app/
├── templates/platform/
│   ├── base.html                  # Base layout with nav/footer
│   ├── homepage-default.html      # Default homepage template
│   ├── homepage-minimal.html      # Minimal/clean template
│   ├── homepage-modern.html       # Modern template with animations
│   └── content-page.html          # Generic content page template
├── services/
│   └── content_page_service.py    # CMS business logic
└── main.py                        # Platform routes (lines 284-404)

scripts/seed/
└── create_default_content_pages.py  # Seeder script (all platforms)

docs/features/
└── platform-homepage.md           # This file
```

---

## Templates

### 1. Homepage Templates

Three homepage templates are available:

#### **Default Template** (`platform/homepage-default.html`)
- **Style:** Professional, feature-rich
- **Sections:** Hero, Features, Featured Stores, CTA
- **Best for:** Comprehensive platform showcase

#### **Minimal Template** (`platform/homepage-minimal.html`)
- **Style:** Clean, minimalist
- **Sections:** Simple hero, minimal features, simple CTA
- **Best for:** Focus on simplicity

#### **Modern Template** (`platform/homepage-modern.html`)
- **Style:** Trendy, animated, gradient-heavy
- **Sections:** Animated hero, feature cards with hover effects, stats
- **Best for:** Modern, tech-forward branding

### 2. Content Page Template

**Template:** `platform/content-page.html`

Used for all content pages (About, FAQ, Contact, etc.)

**Features:**
- Breadcrumb navigation
- Responsive design
- Enhanced prose styling for content
- Context-aware CTAs (for about/contact pages)
- Last updated timestamp
- Dark mode support

---

## Usage

### Admin CMS Interface (Recommended)

#### Platform Homepage Manager (`/admin/platform-homepage`)

The easiest way to manage your platform homepage is through the admin interface:

1. **Login to Admin Panel:**
   ```
   http://localhost:8000/admin/login
   ```

2. **Navigate to Platform Homepage:**
   - Click "Content Management" in the sidebar
   - Click "Platform Homepage"

3. **Customize Homepage:**
   - **Template Selection:** Choose between Default, Minimal, or Modern templates with visual previews
   - **Page Title:** Edit the main heading
   - **Content:** Add HTML content for the hero section
   - **SEO Settings:** Set meta description and keywords
   - **Publishing:** Toggle published status
   - **Preview:** Click "Preview" button to see live homepage
   - **Save:** Click "Save Changes" to update

**Features:**
- ✅ Visual template selector with previews
- ✅ Real-time save with success/error feedback
- ✅ Character counter for SEO fields
- ✅ One-click preview
- ✅ Dark mode support

#### Content Pages Manager (`/admin/content-pages`)

Manage all platform content pages from a single interface:

1. **Navigate to Content Pages:**
   - Click "Content Management" in the sidebar
   - Click "Content Pages"

2. **View All Pages:**
   - **Tabs:** Switch between All Pages, Platform Defaults, or Store Overrides
   - **Search:** Type to filter by title, slug, or store name
   - **Table View:** See status, navigation settings, and last updated

3. **Edit Existing Page:**
   - Click the edit icon (pencil) next to any page
   - Modify content, SEO, navigation settings
   - Click "Update Page" to save

4. **Create New Page:**
   - Click "Create Page" button
   - Fill in:
     - Page title and URL slug
     - Content format (HTML or Markdown)
     - Content (large textarea)
     - SEO metadata
     - Navigation settings (header/footer visibility)
     - Display order
   - Click "Create Page"

5. **Delete Page:**
   - Click the delete icon (trash) next to any page
   - Confirm deletion

**Features:**
- ✅ Tabbed interface for easy filtering
- ✅ Real-time search
- ✅ Status badges (Published/Draft, Platform/Store)
- ✅ Navigation badges (Header/Footer)
- ✅ Quick edit and delete actions
- ✅ Empty state with helpful CTAs

### Creating Platform Pages

#### Method 1: Using the Seeder Script

```bash
# Create all default platform pages
python scripts/seed/create_default_content_pages.py
```

This creates (for all platforms):
- Platform Homepage (with modern template)
- About Us
- Contact Us
- FAQ
- Shipping Policy
- Return & Refund Policy
- Privacy Policy
- Terms of Service
- Privacy Policy

#### Method 2: Via API

**Create Platform Homepage:**
```bash
POST /api/v1/admin/content-pages/platform
{
  "slug": "platform_homepage",
  "title": "Welcome to Our Marketplace",
  "content": "<p>Your custom content...</p>",
  "template": "modern",
  "store_id": null,
  "is_published": true,
  "show_in_header": false,
  "show_in_footer": false
}
```

**Create Content Page:**
```bash
POST /api/v1/admin/content-pages/platform
{
  "slug": "about",
  "title": "About Us",
  "content": "<h2>Our Story</h2><p>...</p>",
  "store_id": null,
  "is_published": true,
  "show_in_header": true,
  "show_in_footer": true,
  "display_order": 1
}
```

#### Method 3: Programmatically

```python
from app.core.database import SessionLocal
from app.services.content_page_service import content_page_service

db = SessionLocal()

# Create homepage
homepage = content_page_service.create_page(
    db,
    slug="platform_homepage",
    title="Welcome",
    content="<p>Content...</p>",
    template="modern",  # default, minimal, or modern
    store_id=None,
    is_published=True,
    show_in_header=False,
    show_in_footer=False
)

# Create content page
about = content_page_service.create_page(
    db,
    slug="about",
    title="About Us",
    content="<h2>Our Story</h2>",
    store_id=None,
    is_published=True,
    show_in_header=True,  # Show in top nav
    show_in_footer=True,  # Show in footer
    display_order=1
)

db.close()
```

---

## Customization

### Changing Homepage Template

Update the `template` field in the database:

```sql
UPDATE content_pages
SET template = 'minimal'  -- or 'default', 'modern'
WHERE slug = 'platform_homepage' AND store_id IS NULL;
```

Or via API:
```bash
PUT /api/v1/admin/content-pages/{id}
{
  "template": "minimal"
}
```

### Customizing Navigation

**Add page to header menu:**
```python
content_page_service.update_page(
    db,
    page_id=page.id,
    show_in_header=True,
    display_order=2  # Position in menu
)
```

**Remove page from footer:**
```python
content_page_service.update_page(
    db,
    page_id=page.id,
    show_in_footer=False
)
```

### Updating Page Content

```python
content_page_service.update_page(
    db,
    page_id=page.id,
    title="New Title",
    content="<h1>Updated Content</h1>",
    meta_description="New SEO description",
    template="modern"  # Change template
)
```

---

## How It Works

### 1. Request Flow

```
User visits: http://localhost:8000/
  ↓
StoreContextMiddleware (no store detected, platform mode)
  ↓
ContextMiddleware (context = unknown)
  ↓
Route: platform_homepage() in main.py:284
  ↓
Load page from CMS (slug='platform_homepage', store_id=NULL)
  ↓
Load header/footer navigation pages
  ↓
Render template: platform/homepage-{template}.html
  ↓
Response with navigation menu
```

### 2. CMS Lookup Logic

**For Homepage (`/`):**
1. Query: `SELECT * FROM content_pages WHERE slug='platform_homepage' AND store_id IS NULL`
2. If found → Render with selected template (default/minimal/modern)
3. If not found → Render fallback static template

**For Content Pages (`/about`, `/faq`, etc.):**
1. Query: `SELECT * FROM content_pages WHERE slug='{slug}' AND store_id IS NULL`
2. If found → Render `platform/content-page.html`
3. If not found → Return 404

**Navigation Loading:**
```python
# Header pages (show_in_header=True)
header_pages = content_page_service.list_pages_for_store(
    db, store_id=None, header_only=True
)

# Footer pages (show_in_footer=True)
footer_pages = content_page_service.list_pages_for_store(
    db, store_id=None, footer_only=True
)
```

### 3. Template Rendering

**Homepage:**
```python
# In main.py:284
if homepage:
    template_name = homepage.template or "default"  # Get from CMS
    template_path = f"platform/homepage-{template_name}.html"
    return templates.TemplateResponse(template_path, context)
```

**Content Page:**
```python
# In main.py:349
return templates.TemplateResponse(
    "platform/content-page.html",
    {
        "request": request,
        "page": page,
        "header_pages": header_pages,
        "footer_pages": footer_pages
    }
)
```

---

## Navigation Menu Example

Given these pages in the database:

| Slug | Title | show_in_header | show_in_footer | display_order |
|------|-------|----------------|----------------|---------------|
| `about` | About Us | ✅ | ✅ | 1 |
| `faq` | FAQ | ✅ | ✅ | 2 |
| `contact` | Contact Us | ✅ | ✅ | 3 |
| `terms` | Terms of Service | ❌ | ✅ | 10 |
| `privacy` | Privacy Policy | ❌ | ✅ | 11 |

**Header Navigation:**
```
Marketplace  |  About Us  |  FAQ  |  Contact Us  |  🌙
```

**Footer Navigation:**
```
Quick Links
  - About Us
  - FAQ
  - Contact Us
  - Terms of Service
  - Privacy Policy
```

---

## SEO Optimization

All pages support SEO meta tags:

```python
content_page_service.create_page(
    db,
    slug="about",
    title="About Our Platform",
    meta_description="Learn about our mission to democratize e-commerce...",
    meta_keywords="about us, mission, vision, values, merchant",
    # ...
)
```

**Rendered in template:**
```html
<title>About Our Platform - Marketplace</title>
<meta name="description" content="Learn about our mission...">
<meta name="keywords" content="about us, mission, vision...">
```

---

## Testing

### Manual Testing

1. **Visit homepage:**
   ```
   http://localhost:8000/
   ```
   Should show platform homepage with selected template.

2. **Visit content pages:**
   ```
   http://localhost:8000/about
   http://localhost:8000/faq
   http://localhost:8000/contact
   http://localhost:8000/terms
   http://localhost:8000/privacy
   ```

3. **Check navigation:**
   - Header should show: About Us, FAQ, Contact Us
   - Footer should show all pages

4. **Test dark mode:**
   - Click moon icon in header
   - Verify dark mode works on all pages

5. **Test responsive design:**
   - Resize browser window
   - Verify mobile menu works
   - Check layouts on different screen sizes

### API Testing

**Get page content:**
```bash
GET /api/v1/storefront/content-pages/about
```

**Get navigation:**
```bash
GET /api/v1/storefront/content-pages/navigation
```

---

## Advanced Features

### Multiple Homepage Templates

Create custom homepage templates:

1. Create template file:
   ```
   app/templates/platform/homepage-custom.html
   ```

2. Update CMS page:
   ```python
   content_page_service.update_page(
       db,
       page_id=homepage.id,
       template="custom"
   )
   ```

3. Visit homepage → Renders `platform/homepage-custom.html`

### Dynamic Content Loading

Homepage templates can load dynamic data:

```jinja2
{# In template #}
{% if featured_stores %}
  {% for store in featured_stores %}
    <div>{{ store.name }}</div>
  {% endfor %}
{% endif %}
```

Pass data in route handler:

```python
# In main.py
featured_stores = db.query(Store).filter(Store.is_featured==True).all()

return templates.TemplateResponse(
    template_path,
    {
        "request": request,
        "page": homepage,
        "header_pages": header_pages,
        "footer_pages": footer_pages,
        "featured_stores": featured_stores,  # Additional data
    }
)
```

---

## Troubleshooting

### Homepage shows 404

**Problem:** Platform homepage not rendering

**Solutions:**
1. Run seeder script:
   ```bash
   python scripts/seed/create_default_content_pages.py
   ```

2. Verify page exists:
   ```sql
   SELECT * FROM content_pages
   WHERE slug='platform_homepage' AND store_id IS NULL;
   ```

3. Check page is published:
   ```sql
   UPDATE content_pages
   SET is_published=true
   WHERE slug='platform_homepage';
   ```

### Navigation menu is empty

**Problem:** No pages showing in header/footer

**Solutions:**
1. Check navigation flags:
   ```sql
   SELECT slug, title, show_in_header, show_in_footer
   FROM content_pages
   WHERE store_id IS NULL;
   ```

2. Update flags:
   ```sql
   UPDATE content_pages
   SET show_in_header=true, show_in_footer=true
   WHERE slug='about' AND store_id IS NULL;
   ```

### Content page returns 404

**Problem:** `/about` or other pages not found

**Solutions:**
1. Verify slug:
   ```sql
   SELECT slug FROM content_pages WHERE store_id IS NULL;
   ```

2. Check published status:
   ```sql
   UPDATE content_pages
   SET is_published=true
   WHERE slug='about';
   ```

### Wrong template loads

**Problem:** Homepage uses wrong template

**Solution:**
```sql
UPDATE content_pages
SET template='modern'
WHERE slug='platform_homepage' AND store_id IS NULL;
```

---

## Best Practices

1. **Always set SEO meta tags:**
   ```python
   meta_description="Clear 150-160 char description",
   meta_keywords="relevant, keywords, comma, separated"
   ```

2. **Use semantic HTML in content:**
   ```html
   <h2>Main Heading</h2>
   <p>Paragraph text...</p>
   <ul><li>List item</li></ul>
   ```

3. **Set appropriate display_order:**
   ```python
   display_order=1  # First in menu
   display_order=2  # Second in menu
   display_order=10  # Legal pages (lower priority)
   ```

4. **Use navigation flags wisely:**
   - `show_in_header`: Only 3-5 main pages
   - `show_in_footer`: Can include more pages

5. **Keep homepage content concise:**
   - Use templates for structure
   - Add key messaging only
   - Link to detailed content pages

---

## API Reference

### Admin Endpoints

```
POST   /api/v1/admin/content-pages/platform     # Create platform page
GET    /api/v1/admin/content-pages/platform     # List platform pages
GET    /api/v1/admin/content-pages/{id}         # Get specific page
PUT    /api/v1/admin/content-pages/{id}         # Update page
DELETE /api/v1/admin/content-pages/{id}         # Delete page
```

### Storefront (Public) Endpoints

```
GET /api/v1/storefront/content-pages/navigation       # Get nav links
GET /api/v1/storefront/content-pages/{slug}           # Get page content
```

---

## Related Documentation

- [Content Management System](./content-management-system.md) - Full CMS documentation
- [CMS Implementation Guide](./cms-implementation-guide.md) - Technical implementation
- [Admin Frontend Guide](../frontend/admin/page-templates.md) - Admin UI patterns

---

## Summary

The Platform Homepage system provides:

✅ **Customizable homepage** with 3 template options
✅ **Multiple content pages** (About, FAQ, Contact, Terms, Privacy)
✅ **CMS-driven** with full CRUD support
✅ **Dynamic navigation** loaded from database
✅ **SEO-optimized** with meta tags
✅ **Responsive** with dark mode support
✅ **Easy to extend** with custom templates

All pages are managed through the existing CMS system, allowing admins to customize content without touching code.
