# Builder Package - Architecture Documentation

## Table of Contents

1. [Overview](#overview)
2. [Directory Structure](#directory-structure)
3. [Class Architecture](#class-architecture)
4. [Data Flow](#data-flow)
5. [Storage Architecture](#storage-architecture)
6. [Route Architecture](#route-architecture)
7. [Extension Points](#extension-points)
8. [How to Add Features](#how-to-add-features)

## Overview

The **bongo/builder** package is a Laravel-based visual page builder that provides:

- **764+ pre-built HTML/CSS blocks** organized into components, designs, and layouts
- **File-based storage** with vendor/resource override pattern
- **Admin interface** for managing and customizing blocks
- **JSON API** for frontend integration
- **ContentBuilder JS** integration for WYSIWYG editing
- **Shortcode support** for dynamic content insertion

### Key Design Principles

1. **Single Model, Multiple Types**: BuilderItem handles components, designs, and layouts polymorphically
2. **File-Based Storage**: No database tables; blocks stored as Blade templates and PNG thumbnails
3. **Override Pattern**: User customizations override vendor originals without modifying package files
4. **Facade Access**: Clean API via Component, Design, and Layout facades
5. **Automatic Bootstrapping**: Extends AbstractServiceProvider for zero-config setup

## Directory Structure

```
bongo/builder/
│
├── src/
│   ├── BuilderServiceProvider.php         # Service provider with facade registration
│   │
│   ├── Config/
│   │   └── builder.php                    # Configuration (paths, categories, icons)
│   │
│   ├── Models/
│   │   └── BuilderItem.php                # Core file-based polymorphic model
│   │
│   ├── Facades/
│   │   ├── ComponentFacade.php            # Component facade
│   │   ├── DesignFacade.php               # Design facade
│   │   └── LayoutFacade.php               # Layout facade
│   │
│   ├── Http/
│   │   ├── Controllers/
│   │   │   ├── Api/                       # 21 API controllers
│   │   │   │   ├── ComponentController.php
│   │   │   │   ├── DesignController.php
│   │   │   │   ├── IconController.php
│   │   │   │   ├── ImageController.php
│   │   │   │   ├── FileController.php
│   │   │   │   ├── FontController.php
│   │   │   │   ├── ButtonController.php
│   │   │   │   ├── StyleController.php
│   │   │   │   ├── SymbolController.php
│   │   │   │   ├── SnippetController.php
│   │   │   │   ├── ModuleController.php
│   │   │   │   ├── PostController.php
│   │   │   │   ├── ProjectController.php
│   │   │   │   ├── ReviewController.php
│   │   │   │   ├── ReviewSummaryController.php
│   │   │   │   ├── GalleryController.php
│   │   │   │   ├── FormController.php
│   │   │   │   ├── MenuController.php
│   │   │   │   ├── CarouselController.php
│   │   │   │   ├── SliderController.php
│   │   │   │   └── ValidationController.php
│   │   │   │
│   │   │   └── Backend/                   # 4 admin controllers
│   │   │       ├── ComponentController.php
│   │   │       ├── DesignController.php
│   │   │       ├── LayoutController.php
│   │   │       └── IconController.php
│   │   │
│   │   └── Middleware/
│   │       └── HasShortCodes.php          # Shortcode processing middleware
│   │
│   ├── Routes/
│   │   ├── api.php                        # Authenticated API routes
│   │   ├── backend.php                    # Admin routes (auth + employee)
│   │   └── custom.php                     # Public API routes (no auth)
│   │
│   ├── Views/
│   │   ├── frontend/                      # 764+ block templates
│   │   │   ├── component/                 # Components (18 categories)
│   │   │   │   ├── headline/
│   │   │   │   │   ├── header-01/
│   │   │   │   │   │   ├── index.blade.php
│   │   │   │   │   │   └── preview.png
│   │   │   │   │   └── header-02/
│   │   │   │   │       ├── index.blade.php
│   │   │   │   │       └── preview.png
│   │   │   │   ├── buttons/
│   │   │   │   ├── features/
│   │   │   │   └── ... (15 more)
│   │   │   │
│   │   │   ├── design/                    # Designs (14 categories)
│   │   │   │   ├── banners/
│   │   │   │   ├── ctas/
│   │   │   │   ├── contact/
│   │   │   │   └── ... (11 more)
│   │   │   │
│   │   │   ├── layout/                    # Layouts (3 categories)
│   │   │   │   ├── headers/
│   │   │   │   ├── headings/
│   │   │   │   └── footers/
│   │   │   │
│   │   │   ├── posts/                     # Post templates
│   │   │   ├── projects/                  # Project templates
│   │   │   ├── carousels/                 # Carousel templates
│   │   │   └── sliders/                   # Slider templates
│   │   │
│   │   ├── backend/                       # Admin UI views
│   │   │   ├── component/
│   │   │   │   ├── index.blade.php
│   │   │   │   ├── create.blade.php
│   │   │   │   ├── edit.blade.php
│   │   │   │   ├── show.blade.php
│   │   │   │   └── partials/
│   │   │   ├── design/
│   │   │   │   └── ... (same structure)
│   │   │   └── layout/
│   │   │       └── ... (same structure)
│   │   │
│   │   └── api/                           # API response templates
│   │       ├── icons.blade.php
│   │       ├── images.blade.php
│   │       ├── files.blade.php
│   │       ├── fonts.blade.php
│   │       ├── buttons.blade.php
│   │       ├── styles.blade.php
│   │       ├── symbols.blade.php
│   │       └── modules/
│   │
│   ├── Seeders/
│   │   ├── DataSeeder.php                 # Master seeder
│   │   ├── ComponentSeeder.php            # Import components from JSON
│   │   ├── DesignSeeder.php               # Import designs from JSON
│   │   ├── components.json                # 722KB component library
│   │   └── designs.json                   # 745KB design library
│   │
│   ├── Exceptions/
│   │   ├── ComponentException.php
│   │   └── DesignException.php
│   │
│   └── Translations/
│       └── en/
│           └── backend.php
│
├── resources/                             # Source assets
│   ├── backend/
│   │   ├── js/
│   │   │   ├── contentbuilder/            # ContentBuilder JS library
│   │   │   │   ├── contentbuilder.js
│   │   │   │   ├── fa-solid.json          # 1,400 solid icons
│   │   │   │   ├── fa-regular.json        # 160 regular icons
│   │   │   │   └── fa-brand.json          # 490 brand icons
│   │   │   └── editor.js                  # Backend editor entry
│   │   └── sass/
│   │       └── editor.scss                # Backend styles
│   │
│   └── frontend/
│       ├── js/
│       │   └── box.js                     # Frontend interactions
│       └── sass/
│           └── box.scss                   # Frontend styles
│
├── public/                                # Compiled assets
│   ├── backend/
│   │   ├── editor.css
│   │   └── editor.js
│   └── frontend/
│       ├── box.css
│       └── box.js
│
├── tests/                                 # PHPUnit tests
│
├── composer.json
├── package.json
├── webpack.mix.js
└── phpunit.xml
```

## Class Architecture

### Core Classes

```
┌─────────────────────────────────────────────────────────────────┐
│                   BuilderServiceProvider                        │
│  extends AbstractServiceProvider                                │
│                                                                 │
│  - Registers singleton instances for each type                 │
│  - Registers global facade aliases                             │
│  - Publishes frontend assets                                   │
│  - Registers hasShortCodes middleware                          │
└─────────────────────────────────────────────────────────────────┘
                              │
                              │ bootstraps
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                       BuilderItem                               │
│  (File-based polymorphic model)                                │
│                                                                 │
│  Properties:                                                    │
│  + type: string ('component', 'design', 'layout')              │
│  + name: ?string (slugified)                                   │
│  + key: ?string (unique identifier)                            │
│  + category: ?string (slugified)                               │
│  + html: ?string (rendered Blade)                              │
│  + thumbnail: ?string (base64 PNG)                             │
│  + relativePath: ?string                                       │
│  + absolutePath: ?string                                       │
│  + ... (more path properties)                                  │
│                                                                 │
│  Methods:                                                       │
│  + all(): Collection                                           │
│  + allByCategory(): array                                      │
│  + allAsJson(): false|string                                   │
│  + categories(): array                                         │
│  + categoriesAsJson(): false|string                            │
│  + find(string $key): mixed                                    │
│  + findOrFail(string $key): mixed                              │
│  + findByCategory(string $category): Collection                │
│  + save(): void                                                │
│  + delete(): void                                              │
│  + createFromFile(SplFileInfo $file): BuilderItem              │
│  + getBasePath(): string                                       │
│  + getResourcePath(): string                                   │
│  + getAllFiles(): array                                        │
│  + getVendorFiles(): array                                     │
│  + getResourceFiles(): array                                   │
│  + getHtml(): ?string                                          │
│  + getRawHtml(): ?string                                       │
│  + getThumbnail(): ?string                                     │
│  + getRawThumbnail(): ?string                                  │
│  + ... (getters/setters)                                       │
└─────────────────────────────────────────────────────────────────┘
         ▲                    ▲                    ▲
         │                    │                    │
         │ accesses           │ accesses           │ accesses
         │                    │                    │
┌────────┴────────┐  ┌───────┴────────┐  ┌────────┴────────┐
│ComponentFacade  │  │ DesignFacade   │  │ LayoutFacade    │
│                 │  │                │  │                 │
│ Accessor:       │  │ Accessor:      │  │ Accessor:       │
│ 'component'     │  │ 'design'       │  │ 'layout'        │
│                 │  │                │  │                 │
│ Global Alias:   │  │ Global Alias:  │  │ Global Alias:   │
│ Component       │  │ Design         │  │ Layout          │
└─────────────────┘  └────────────────┘  └─────────────────┘
```

### Controller Hierarchy

```
AbstractApiController (from bongo/framework)
    │
    ├── ComponentController        # GET /api/builder (all components)
    ├── DesignController          # GET /api/builder/designs
    ├── IconController            # GET /api/builder/icons
    ├── ImageController           # GET /api/builder/images
    ├── FileController            # GET /api/builder/files
    ├── FontController            # GET /api/builder/fonts
    ├── ButtonController          # GET /api/builder/buttons
    ├── StyleController           # GET /api/builder/styles
    ├── SymbolController          # GET /api/builder/symbols
    ├── SnippetController         # GET /api/builder/snippets
    ├── ModuleController          # GET /api/builder/modules/{module}
    ├── PostController            # GET /api/builder/post
    ├── ProjectController         # GET /api/builder/project
    ├── ReviewController          # GET /api/builder/review
    ├── ReviewSummaryController   # GET /api/builder/review-summary
    ├── GalleryController         # GET /api/builder/gallery-builder
    ├── FormController            # GET /api/builder/form-builder
    ├── MenuController            # GET /api/builder/menu-builder
    ├── CarouselController        # GET /api/builder/carousels/{carousel}
    ├── SliderController          # GET /api/builder/sliders/{slider}
    └── ValidationController      # GET /api/builder/validation

AbstractController (from bongo/framework)
    │
    ├── Backend\ComponentController   # Admin CRUD for components
    ├── Backend\DesignController      # Admin CRUD for designs
    ├── Backend\LayoutController      # Admin CRUD for layouts
    └── Backend\IconController        # View FontAwesome icons
```

### Middleware

```
HasShortCodes Middleware
    │
    ├── Intercepts Response
    ├── Parses Shortcodes: [component key="header-02"]
    ├── Replaces with Rendered HTML
    └── Returns Modified Response
```

## Data Flow

### Loading Blocks (Read Operation)

```
User Request
    │
    ├─→ Component::all()
    │       │
    │       ├─→ Check Cache (10 min TTL)
    │       │       │
    │       │       ├─→ Cache Hit → Return Collection
    │       │       │
    │       │       └─→ Cache Miss
    │       │               │
    │       │               ├─→ getAllFiles()
    │       │               │       │
    │       │               │       ├─→ getVendorFiles()
    │       │               │       │       └─→ Scan vendor/bongo/builder/src/Views/frontend/component/
    │       │               │       │
    │       │               │       ├─→ getResourceFiles()
    │       │               │       │       └─→ Scan resources/views/vendor/builder/frontend/component/
    │       │               │       │
    │       │               │       └─→ array_replace() → Merge (resource overrides vendor)
    │       │               │
    │       │               ├─→ Loop Through Files
    │       │               │       │
    │       │               │       ├─→ createFromFile()
    │       │               │       │       │
    │       │               │       │       ├─→ Parse category/name from path
    │       │               │       │       ├─→ Set properties
    │       │               │       │       └─→ Return BuilderItem
    │       │               │       │
    │       │               │       └─→ Add to Collection
    │       │               │
    │       │               ├─→ Cache for 10 minutes
    │       │               │
    │       │               └─→ Return Collection
    │       │
    │       └─→ Return to User
    │
    └─→ Render in View or Return as JSON
```

### Saving Blocks (Write Operation)

```
User Submits Form
    │
    ├─→ Backend\ComponentController::store()
    │       │
    │       ├─→ Validate Input
    │       │       │
    │       │       ├─→ name (required)
    │       │       ├─→ category (required)
    │       │       ├─→ html (required)
    │       │       └─→ thumbnail (required)
    │       │
    │       ├─→ Create BuilderItem
    │       │       │
    │       │       ├─→ setName($name)      → Slugify
    │       │       ├─→ setKey($name)       → Make unique key
    │       │       ├─→ setCategory($cat)   → Slugify
    │       │       ├─→ setHtml($html)
    │       │       └─→ setThumbnail($img)
    │       │
    │       ├─→ save()
    │       │       │
    │       │       ├─→ Determine Save Location
    │       │       │       └─→ resources/views/vendor/builder/frontend/component/{category}/{name}/
    │       │       │
    │       │       ├─→ Create Directory (if not exists)
    │       │       │       └─→ File::makeDirectory($path, 0755, true)
    │       │       │
    │       │       ├─→ Write preview.png
    │       │       │       └─→ File::put($thumbnailPath, $thumbnail)
    │       │       │
    │       │       ├─→ Write index.blade.php
    │       │       │       └─→ File::put($htmlPath, $html)
    │       │       │
    │       │       └─→ Clear Cache
    │       │               └─→ Cache::forget('component_files')
    │       │
    │       └─→ Redirect with Success Message
    │
    └─→ Block Now Available
            │
            └─→ Next Component::all() will include new block
```

### Deleting Blocks

```
User Clicks Delete
    │
    ├─→ Backend\ComponentController::destroy($key)
    │       │
    │       ├─→ Find BuilderItem by $key
    │       │
    │       ├─→ delete()
    │       │       │
    │       │       ├─→ Check if Resource Version Exists
    │       │       │       └─→ resources/views/vendor/builder/frontend/component/{category}/{name}/
    │       │       │
    │       │       ├─→ If Exists → Delete Directory
    │       │       │       └─→ File::deleteDirectory($path)
    │       │       │
    │       │       └─→ Clear Cache
    │       │               └─→ Cache::forget('component_files')
    │       │
    │       └─→ Redirect with Success Message
    │
    └─→ Block Reverts to Vendor Version (if exists) or Removed Entirely
```

### Shortcode Processing Flow

```
HTTP Request
    │
    ├─→ Route → Controller → Generate Response
    │
    ├─→ HasShortCodes Middleware (after response)
    │       │
    │       ├─→ Get Response Content
    │       │       └─→ HTML with shortcodes: <div>[component key="header-02"]</div>
    │       │
    │       ├─→ ShortCode::parse($content)
    │       │       │
    │       │       ├─→ Find Pattern: \[component key="(.+?)"\]
    │       │       │
    │       │       ├─→ Component::find('header-02')
    │       │       │       └─→ Get BuilderItem
    │       │       │
    │       │       ├─→ $item->getHtml()
    │       │       │       └─→ Render Blade Template
    │       │       │
    │       │       └─→ Replace Shortcode with HTML
    │       │
    │       ├─→ Set Modified Content
    │       │
    │       └─→ Return Response
    │
    └─→ User Receives HTML with Rendered Components
```

## Storage Architecture

### File Structure

Each block is stored as a directory containing two files:

```
{type}/{category}/{name}/
    ├── index.blade.php     # The HTML/Blade template
    └── preview.png         # Thumbnail image (base64-encoded for display)
```

Example:
```
frontend/component/headline/header-02/
    ├── index.blade.php
    └── preview.png
```

### Dual-Location Pattern

**Vendor Location** (Read-Only):
```
vendor/bongo/builder/src/Views/frontend/
    ├── component/
    ├── design/
    └── layout/
```

- Original, unmodified templates from package
- Never modified by users
- Always available as fallback

**Resource Location** (User Customizations):
```
resources/views/vendor/builder/frontend/
    ├── component/
    ├── design/
    └── layout/
```

- User-created and modified blocks
- Created automatically on first save
- Overrides vendor versions

### Override Mechanism

```php
public function getAllFiles(): array
{
    return array_replace(
        $this->getVendorFiles(),    // Load vendor originals
        $this->getResourceFiles()   // Override with user customizations
    );
}
```

**Key Behavior**:
- Vendor blocks are always available
- Resource blocks override vendor blocks with same path
- Delete operation removes only resource version
- Vendor version becomes active again after delete

### Caching Strategy

```php
Cache::remember($this->type . '_files', 600, function () {
    // Expensive file scanning operations
    // Returns Collection of BuilderItem objects
});
```

**Cache Key Pattern**:
- `component_files` - All components
- `design_files` - All designs
- `layout_files` - All layouts

**Cache Invalidation**:
- Automatically cleared on `save()`
- Automatically cleared on `delete()`
- 10-minute TTL (600 seconds)

## Route Architecture

### API Routes (Authenticated)

**File**: `src/Routes/api.php`
**Middleware**: `auth:sanctum` (applied by AbstractServiceProvider)
**Prefix**: `/api/builder`

```
GET  /api/builder                  → ComponentController::index()
GET  /api/builder/buttons          → ButtonController::index()
GET  /api/builder/designs          → DesignController::index()
GET  /api/builder/snippets         → SnippetController::index()
GET  /api/builder/files            → FileController::index()
GET  /api/builder/fonts            → FontController::index()
GET  /api/builder/images           → ImageController::index()
GET  /api/builder/icons            → IconController::index()
GET  /api/builder/symbols          → SymbolController::index()
GET  /api/builder/styles           → StyleController::index()
GET  /api/builder/modules/{module} → ModuleController::index()
```

### Custom Routes (Public, No Auth)

**File**: `src/Routes/custom.php`
**Middleware**: None (no session, CSRF, or auth)
**Prefix**: `/api/builder`

Used for external integrations (webhooks, public APIs):

```
GET  /api/builder/carousels/{carousel}    → CarouselController::index()
GET  /api/builder/sliders/{slider}        → SliderController::index()
GET  /api/builder/validation              → ValidationController::index()
GET  /api/builder/post                    → PostController::index()
GET  /api/builder/project                 → ProjectController::index()
GET  /api/builder/review                  → ReviewController::index()
GET  /api/builder/review-summary          → ReviewSummaryController::index()
GET  /api/builder/form-builder            → FormController::index()
GET  /api/builder/menu-builder            → MenuController::index()
GET  /api/builder/gallery-builder         → GalleryController::index()
```

### Backend Routes (Admin)

**File**: `src/Routes/backend.php`
**Middleware**: `auth`, `employee` (applied by AbstractServiceProvider)
**Prefixes**: Configurable via `config('builder.{type}_prefix')`

**Component Routes** (Prefix: `/admin/components`):
```
GET    /admin/components                 → index()
GET    /admin/components/create          → create()
POST   /admin/components/store           → store()
GET    /admin/components/{key}           → show()
GET    /admin/components/{key}/edit      → edit()
POST   /admin/components/{key}/update    → update()
DELETE /admin/components/{key}/delete    → destroy()
```

**Design Routes** (Prefix: `/admin/sections`):
```
(Same pattern as components)
```

**Layout Routes** (Prefix: `/admin/layouts`):
```
(Same pattern as components)
```

**Icon Routes**:
```
GET  /admin/icons  → IconController::index()
```

## Extension Points

### 1. Adding a New Block Type

To add a fourth type (e.g., "snippet"):

**Step 1**: Update configuration (`src/Config/builder.php`):

```php
'snippet_prefix' => 'snippets',
'snippet_path' => 'frontend/snippet/',
'snippet_categories' => [
    '301' => 'Code Blocks',
    '302' => 'Embeds',
],
```

**Step 2**: Register singleton in service provider:

```php
$this->app->singleton('snippet', fn () => new BuilderItem('snippet'));
```

**Step 3**: Create facade (`src/Facades/SnippetFacade.php`):

```php
class SnippetFacade extends Facade
{
    protected static function getFacadeAccessor(): string
    {
        return 'snippet';
    }
}
```

**Step 4**: Register alias:

```php
AliasLoader::getInstance()->alias('Snippet', SnippetFacade::class);
```

**Step 5**: Create controllers and routes following existing patterns.

### 2. Adding a New Category

**Step 1**: Add to config (`src/Config/builder.php`):

```php
'component_categories' => [
    '109' => 'Achievements',
    // ... existing categories
    '124' => 'Testimonials',  // New category
],
```

**Step 2**: Create directory structure:

```
src/Views/frontend/component/testimonials/
    └── testimonial-01/
        ├── index.blade.php
        └── preview.png
```

**Step 3**: Blocks are automatically discovered via file scanning.

### 3. Adding a New API Controller

**Step 1**: Create controller (`src/Http/Controllers/Api/NewController.php`):

```php
namespace Bongo\Builder\Http\Controllers\Api;

use Bongo\Framework\Http\Controllers\Api\AbstractApiController;

class NewController extends AbstractApiController
{
    public function index()
    {
        // Return data
        return response()->json([
            'data' => 'value',
        ]);
    }
}
```

**Step 2**: Add route (`src/Routes/api.php` or `custom.php`):

```php
Route::get('endpoint', [NewController::class, 'index'])
    ->name('endpoint.index');
```

**Step 3**: Optional: Create view template (`src/Views/api/endpoint.blade.php`):

```blade
@php
    echo json_encode($data);
@endphp
```

### 4. Customizing Block Rendering

Override the `getHtml()` method by extending BuilderItem:

```php
class CustomBuilderItem extends BuilderItem
{
    public function getHtml(): ?string
    {
        $html = parent::getHtml();

        // Add custom processing
        $html = $this->processCustomTags($html);

        return $html;
    }

    protected function processCustomTags(string $html): string
    {
        // Custom logic
        return $html;
    }
}
```

### 5. Adding Custom Middleware

Register in service provider:

```php
protected array $middlewares = [
    'hasShortCodes' => HasShortCodes::class,
    'customMiddleware' => CustomMiddleware::class,
];
```

Apply to routes:

```php
Route::get('endpoint', [Controller::class, 'index'])
    ->middleware('customMiddleware');
```

### 6. Integrating with Other Packages

The builder already integrates with:

- **bongo/image** - Image library
- **bongo/post** - Blog post listings
- **bongo/gallery** - Gallery builder
- **bongo/menu** - Menu builder
- **bongo/form** - Form builder

To add new integration:

**Step 1**: Create API controller:

```php
class NewIntegrationController extends AbstractApiController
{
    public function index()
    {
        // Fetch data from other package
        $data = app(OtherPackageService::class)->getData();

        return view('builder::api.new-integration', compact('data'));
    }
}
```

**Step 2**: Create view template with JSON response.

**Step 3**: Add route to `custom.php` for public access.

## How to Add Features

### Adding a New Block

**1. Create Directory Structure**:

```bash
mkdir -p src/Views/frontend/component/new-category/new-block
```

**2. Create Template** (`index.blade.php`):

```blade
<div class="new-block">
    <h1>New Block</h1>
    <p>Block content here</p>
</div>
```

**3. Create Thumbnail** (`preview.png`):

- Create PNG image (recommended ~1202 bytes)
- Place in same directory as template

**4. Block is Automatically Discovered**:

```php
Component::all();  // Includes new block
```

### Adding a New API Endpoint

**1. Create Controller**:

```php
namespace Bongo\Builder\Http\Controllers\Api;

class TagController extends AbstractApiController
{
    public function index()
    {
        $tags = [
            ['name' => 'Tag 1', 'slug' => 'tag-1'],
            ['name' => 'Tag 2', 'slug' => 'tag-2'],
        ];

        return response()->json($tags);
    }
}
```

**2. Add Route** (`src/Routes/api.php`):

```php
Route::get('tags', [TagController::class, 'index'])
    ->name('tag.index');
```

**3. Test Endpoint**:

```bash
GET /api/builder/tags
Authorization: Bearer {token}
```

### Adding Frontend Assets

**1. Create Source Files**:

```javascript
// resources/frontend/js/new-feature.js
export default class NewFeature {
    init() {
        console.log('New feature initialized');
    }
}
```

```scss
// resources/frontend/sass/new-feature.scss
.new-feature {
    color: blue;
}
```

**2. Import in Main Files**:

```javascript
// resources/frontend/js/box.js
import NewFeature from './new-feature';

const feature = new NewFeature();
feature.init();
```

```scss
// resources/frontend/sass/box.scss
@import 'new-feature';
```

**3. Compile Assets**:

```bash
npm run dev
```

**4. Published Assets Update**:

```bash
php artisan vendor:publish --tag=builder:assets --force
```

### Adding a Seeder

**1. Create Seeder Class**:

```php
namespace Bongo\Builder\Seeders;

use Illuminate\Database\Seeder;

class LayoutSeeder extends Seeder
{
    public function run(): void
    {
        $layouts = json_decode(
            file_get_contents(__DIR__ . '/layouts.json'),
            true
        );

        foreach ($layouts as $layoutData) {
            // Process and save layouts
        }
    }
}
```

**2. Create JSON Data File** (`src/Seeders/layouts.json`).

**3. Call from DataSeeder**:

```php
public function run(): void
{
    $this->call([
        ComponentSeeder::class,
        DesignSeeder::class,
        LayoutSeeder::class,  // New seeder
    ]);
}
```

**4. Run Seeder**:

```bash
php artisan db:seed --class="Bongo\Builder\Seeders\DataSeeder"
```

## Performance Considerations

### Caching

- File lists cached for 10 minutes
- Reduces filesystem scans
- Automatically invalidated on save/delete

### File Scanning

- Only scans directories once per cache period
- Uses `File::allFiles()` for efficiency
- Filters by `.php` extension

### Lazy Loading

- Templates rendered on-demand via `getHtml()`
- Thumbnails loaded only when requested
- Collection items created lazily

### Optimization Tips

1. **Keep preview images small** (~1-2KB)
2. **Use simple Blade templates** (minimize logic)
3. **Limit number of blocks per category** (< 100 for best performance)
4. **Consider CDN** for compiled assets
5. **Use production builds** (`npm run production`)

## Security Considerations

### Authentication

- API routes require `auth:sanctum` middleware
- Backend routes require `auth` + `employee` middleware
- Custom routes are public (use with caution)

### Input Validation

- Validate all user input in controllers
- Sanitize HTML before saving
- Validate file uploads (thumbnails)

### File System Access

- Restrict writes to resource path only
- Never modify vendor path
- Use `File::exists()` before operations

### XSS Prevention

- Blade templates auto-escape output
- Use `{!! !!}` only when necessary
- Sanitize user HTML input

## Troubleshooting

### Blocks Not Appearing

1. Check cache: `Cache::forget('component_files')`
2. Verify directory structure: `{category}/{name}/index.blade.php`
3. Check file permissions: `chmod -R 755 resources/views/vendor/builder/`

### Thumbnails Not Displaying

1. Verify `preview.png` exists in block directory
2. Check file size (recommended ~1-2KB)
3. Ensure PNG format (not JPEG or GIF)

### Routes Not Working

1. Clear route cache: `php artisan route:clear`
2. Verify middleware in route file
3. Check route prefix in config

### Assets Not Compiling

1. Install dependencies: `npm install`
2. Check `webpack.mix.js` configuration
3. Run with verbose: `npm run dev -- --verbose`

---

This architecture documentation provides a comprehensive overview of the builder package structure, patterns, and extension points. For specific implementation details, refer to the source code and inline documentation.
