# Solution Design Document

## Validation Checklist

- [x] All required sections are complete
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] All context sources are listed with relevance ratings
- [x] Project commands are discovered from actual project files
- [x] Constraints → Strategy → Design → Implementation path is logical
- [x] Architecture pattern is clearly stated with rationale
- [x] Every component in diagram has directory mapping
- [x] Every interface has specification
- [x] Error handling covers all error types
- [x] Quality requirements are specific and measurable
- [x] Every quality requirement has test coverage
- [x] **All architecture decisions confirmed by user**
- [x] Component names consistent across diagrams
- [x] A developer could implement from this design

---

## Constraints

**CON-1 Technology Stack**: Must work within existing PHP 8.x / Slim 2.6.2 / Twig 1.44.8 stack. No React/Vue adoption. Bootstrap 5.3 adopted as CSS framework (replacing Bootstrap 3). No build tools requiring Node.js in production.

**CON-2 Browser Support**: Chrome, Firefox, Safari, Edge (latest 2 versions). CSS custom properties (variables) are required - IE11 is NOT supported. Target 97%+ global browser coverage.

**CON-3 Performance Targets**:
- Final minified CSS bundle: <200KB (currently ~1.5MB total)
- First paint: No blocking CSS beyond admin.min.css bundle
- No external font loading delays (Inter font already in use)

**CON-4 Deployment Integration**: Must work with existing `deploy.sh` → Envoyer.io pipeline. CSS build step must be optional or run pre-deploy (no runtime compilation).

**CON-5 Hard Cutover Requirement**: Per PRD, this is a hard cutover - legacy Bootstrap 3 CSS must be completely removed upon deployment. Partial migration or dual-system operation is NOT acceptable.

**CON-6 Admin Panel Scope**: Changes limited to admin routes (`/admin/*`, `/workspace/*`). Public-facing pages out of scope.

**CON-7 JavaScript Updates**: Bootstrap 5 bundle replaces Bootstrap 3 JS. Existing functionality (buyQueue.js, DataTables, Select2) must continue to work. Modal/dropdown data attributes change from `data-toggle` to `data-bs-toggle`. Masonry.js added for variable-height card grids.

## Implementation Context

**IMPORTANT**: You MUST read and analyze ALL listed context sources to understand constraints, patterns, and existing architecture.

### Required Context Sources

**ICO-1 Design System Documentation**
```yaml
# The authoritative design system specification
- doc: docs/guides/style-guide.md
  relevance: CRITICAL
  why: "Master design system reference with all tokens, components, and patterns. This is the single source of truth."

# Product requirements for this feature
- doc: docs/specs/006-css-design-system/product-requirements.md
  relevance: HIGH
  why: "Business requirements and acceptance criteria that must be met"
```

**ICO-2 Modern CSS Reference Files**
```yaml
# Files that exemplify the target CSS architecture
- file: public_html/css/workspace/workspace.css
  relevance: CRITICAL
  sections: [":root variables", ".workspace-layout", ".content-card"]
  why: "Best example of CSS variable usage with 131 var() references. Template for all new CSS."

- file: public_html/css/workspace/comeback-cash.css
  relevance: HIGH
  sections: ["@keyframes animations", ".cc-event-card", ".cc-status-badge"]
  why: "Modern component patterns with 296 var() usages, includes animations"

- file: public_html/css/workspace/support.css
  relevance: MEDIUM
  why: "367 var() usages - demonstrates comprehensive variable adoption"
```

**ICO-3 Legacy CSS Files (for migration reference)**
```yaml
# Files that must be replaced or migrated
- file: public_html/css/bootstrap-3.3.2.css
  relevance: HIGH
  why: "138KB legacy file to be completely removed - need to understand what depends on it"

- file: public_html/css/backstock-home.css
  relevance: HIGH
  sections: [".stat-card", ".panel", ".badge patterns"]
  why: "Example of partially-modern page still using hardcoded colors and Bootstrap patterns"

- file: public_html/css/bootstrap-custom.css
  relevance: LOW
  why: "Minimal overrides (23 lines) - review for any critical customizations"
```

**ICO-4 Template Files (CSS consumers)**
```yaml
# Templates that load CSS and use classes
- file: userfrosting/templates/themes/default/workspace/layouts/workspace-head.html
  relevance: HIGH
  why: "Shows how modern workspace pages load CSS directly via <link> tags"

- file: userfrosting/initialize.php
  relevance: HIGH
  sections: ["PageSchema CSS registration", "lines 258-344"]
  why: "Legacy CSS registration system - PageSchema for common/group CSS bundles"
```

### Implementation Boundaries

- **Must Preserve**:
  - All JavaScript functionality (buyQueue.js, DataTables, Select2, modals, form validation)
  - Twig template structure and partial includes
  - Existing HTML class names where JavaScript binds to them (e.g., `.dataTables_*`, `.select2-*`)
  - PageSchema registration API (for gradual migration)
  - All existing user workflows and visual layouts (though appearance will change to modern design)

- **Can Modify**:
  - All CSS files in `public_html/css/` (except vendor libraries with JS dependencies)
  - Twig template class attributes for styling purposes
  - CSS file loading approach in templates
  - PageSchema CSS registrations in `initialize.php`
  - HTML markup classes for styling (not for JS binding)

- **Must Not Touch**:
  - `public_html/css/datatables/` - DataTables CSS has tight JS coupling
  - `public_html/css/select2/` - Select2 library CSS
  - `public_html/css/iCheck/` - iCheck checkbox library
  - `public_html/css/fancyBox/` - Lightbox library
  - `public_html/css/front/` - Marketing/public pages (out of scope)
  - JavaScript files (any `.js` files)
  - Backend PHP business logic

### External Interfaces

This is a CSS-only implementation with minimal external interfaces. No API integrations, databases, or backend services are involved.

#### System Context Diagram

```mermaid
graph TB
    subgraph "Bootstrap 5 Framework"
        Bootstrap5CSS[bootstrap.min.css]
        Bootstrap5JS[bootstrap.bundle.min.js]
    end

    subgraph "BuyerKiosk Theme Layer"
        TokensCSS[tokens.css]
        ThemeCSS[admin-theme.css]
        ModulesCSS[modules/*.css]
        BuildScript[conductor build-css]
    end

    subgraph "External Resources"
        GoogleFonts[Google Fonts CDN]
        FontAwesome[Font Awesome 6]
        MasonryJS[masonry.pkgd.min.js]
    end

    subgraph "Consumers"
        TwigTemplates[Twig Templates]
        AdminPages[Admin Pages]
        WorkspacePages[Workspace Pages]
    end

    GoogleFonts -->|Inter font family| TwigTemplates
    FontAwesome -->|Icon classes| TwigTemplates
    Bootstrap5CSS -->|Base framework| TwigTemplates
    Bootstrap5JS -->|Modals, dropdowns| TwigTemplates
    MasonryJS -->|Card grid layouts| TwigTemplates
    BuildScript -->|Concatenates| ThemeBundle[admin-theme.min.css]
    TokensCSS --> BuildScript
    ThemeCSS --> BuildScript
    ModulesCSS --> BuildScript
    ThemeBundle --> TwigTemplates
    TwigTemplates --> AdminPages
    TwigTemplates --> WorkspacePages
```

#### Interface Specifications

```yaml
# Framework Dependencies
framework:
  - name: "Bootstrap 5.3 CSS"
    type: CDN/Local
    url: "https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
    local: "public_html/css/vendor/bootstrap.min.css"
    criticality: CRITICAL
    why: "Base CSS framework - replaces Bootstrap 3"

  - name: "Bootstrap 5.3 JS Bundle"
    type: CDN/Local
    url: "https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
    local: "public_html/js/vendor/bootstrap.bundle.min.js"
    criticality: CRITICAL
    why: "Required for modals, dropdowns, tooltips - includes Popper.js"

  - name: "Masonry.js"
    type: CDN/Local
    url: "https://cdn.jsdelivr.net/npm/masonry-layout@4.2.2/dist/masonry.pkgd.min.js"
    local: "public_html/js/vendor/masonry.pkgd.min.js"
    criticality: MEDIUM
    why: "Variable-height card grid layouts for event listings"

# External Resources (CDN dependencies)
external:
  - name: "Google Fonts - Inter"
    type: CDN
    url: "https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap"
    criticality: MEDIUM
    fallback: "System fonts (-apple-system, BlinkMacSystemFont)"
    why: "Typography system requires Inter font family"

  - name: "Font Awesome 6"
    type: Local/CDN
    file: "public_html/css/font-awesome-6.min.css"
    criticality: HIGH
    why: "Icon system throughout admin panel"

# Theme Bundle Output (layered on top of Bootstrap 5)
output:
  - name: "Admin Theme Bundle"
    file: "public_html/css/admin/admin-theme.min.css"
    format: "Minified CSS"
    size_target: "<50KB"
    consumers: "All admin and workspace pages"
    note: "This is ADDED to Bootstrap 5, not a replacement"

# Template Integration Points
templates:
  - name: "Admin Page Base"
    file: "userfrosting/templates/themes/default/admin/base.html"
    integration: "{% block stylesheets %} includes admin.min.css"

  - name: "Workspace Layout"
    file: "userfrosting/templates/themes/default/workspace/layouts/workspace-head.html"
    integration: "Direct <link> tags for workspace CSS"
```

### Cross-Component Boundaries

Not applicable - this is a single-team frontend CSS implementation. No cross-team coordination required.

- **CSS Ownership**: All CSS files in `public_html/css/admin/` owned by frontend team
- **Breaking Changes**: Any class name removals require corresponding template updates before deployment

### Project Commands

```bash
# CSS Design System Development
Location: public_html/css/admin/

## Environment Setup
# Bootstrap 5 and Masonry loaded via CDN or local vendor files
# No Node.js or npm required

## Build Commands (NEW - via Conductor CLI)
Build Theme CSS:     php userfrosting/conductor build-css              # Concatenates theme CSS files
Watch Mode:          php userfrosting/conductor build-css --watch      # Rebuilds on file changes
Production Build:    php userfrosting/conductor build-css --minify     # Full minification for deploy

## Validation Commands
Legacy Check:        grep -r "\.panel\|\.label-\|data-toggle" userfrosting/templates/  # Find BS3 patterns
BS5 Data Attrs:      grep -r "data-bs-" userfrosting/templates/        # Verify BS5 migration

## Bootstrap 3 → 5 Migration Helpers
Find panels:         grep -rl "panel" userfrosting/templates/ | wc -l
Find labels:         grep -rl "label-" userfrosting/templates/ | wc -l
Find btn-default:    grep -rl "btn-default" userfrosting/templates/ | wc -l

## Existing Deployment
Run Tests:           ./test.sh                         # PHPUnit tests (existing)
Deploy:              ./test.sh --deploy                # Triggers Envoyer.io deployment

## PHP Dependencies (existing)
Install:             cd userfrosting && composer install

## Development Server
Local Dev:           Access via https://dev2.buyerkiosk.com (configured externally)
```

## Solution Strategy

### Architecture Pattern: Bootstrap 5 with Theme Override Layer

The architecture leverages Bootstrap 5 as the base framework, with a thin customization layer for BuyerKiosk branding:

```
┌─────────────────────────────────────────────┐
│           BOOTSTRAP 5.3 (base framework)    │  ← Grid, components, utilities
├─────────────────────────────────────────────┤
│           1. TOKENS (CSS variables)         │  ← Brand colors override BS5 defaults
├─────────────────────────────────────────────┤
│           2. THEME (component overrides)    │  ← BuyerKiosk styling on BS5 components
├─────────────────────────────────────────────┤
│           3. MODULES (page-specific)        │  ← Backstock, Comeback Cash, etc.
└─────────────────────────────────────────────┘

+ MASONRY.JS (loaded on pages with variable-height card grids)
+ BOOTSTRAP 5 JS BUNDLE (modals, dropdowns, tooltips)
```

### Integration Approach

1. **Bootstrap 5 Base**: Load Bootstrap 5.3 CSS as the foundation (CDN or local)
2. **Theme Layer**: Load `admin-theme.min.css` AFTER Bootstrap to override defaults with brand styling
3. **Template Migration**: Update Twig templates from BS3 → BS5 class names (`.panel` → `.card`, etc.)
4. **JS Migration**: Update data attributes (`data-toggle` → `data-bs-toggle`) and load BS5 bundle
5. **Masonry Integration**: Add `data-masonry` attribute to card grids that need variable-height layout
6. **Hard Cutover**: Once all templates migrated, remove Bootstrap 3 CSS/JS entirely

### Justification

- **Bootstrap 5**: Modern, well-documented framework with built-in CSS variables and dark mode support
- **Minimal Custom CSS**: Theme layer is small (~50KB) since Bootstrap provides most components
- **Community Support**: Stack Overflow, documentation, and updates handled by Bootstrap team
- **Easy Migration**: Most BS3 → BS5 class mappings are direct (grid, forms work similarly)
- **Masonry Built-in**: Bootstrap 5 has official Masonry integration via data attributes

### Key Decisions

1. **Bootstrap 5 over Custom CSS**: Leverage existing framework vs building from scratch - reduces maintenance burden
2. **CSS Variable Overrides**: Override Bootstrap's CSS variables rather than Sass compilation - simpler, no Node.js required
3. **CDN with Local Fallback**: Load from CDN for caching benefits, keep local copies for reliability
4. **Vendor CSS Preserved**: DataTables, Select2, iCheck CSS remains untouched to avoid breaking JS integrations
5. **Font Awesome 6 Only**: Consolidate all icons to FA6, remove legacy versions
6. **Masonry for Event Cards**: Variable-height card grids (Comeback Cash, Backstock Events) use Masonry layout

## Building Block View

### Components

```mermaid
graph TB
    subgraph "Bootstrap 5 Framework (External)"
        bs5css[bootstrap.min.css<br/>Grid, Components, Utilities]
        bs5js[bootstrap.bundle.min.js<br/>Modals, Dropdowns, Tooltips]
    end

    subgraph "BuyerKiosk Theme Layer"
        subgraph "Layer 1: Tokens"
            tokens[tokens.css<br/>Brand CSS Variables]
        end

        subgraph "Layer 2: Theme Overrides"
            theme[admin-theme.css<br/>BS5 Component Customizations]
        end

        subgraph "Layer 3: Modules"
            backstock[backstock.css]
            comebackCash[comeback-cash.css]
            workbook[workbook.css]
        end

    end

    subgraph "JavaScript (External)"
        masonry[masonry.pkgd.min.js<br/>Variable-height card grids]
    end

    subgraph "Build Output"
        themeBundle[admin-theme.min.css]
    end

    bs5css --> tokens
    tokens --> theme
    theme --> backstock
    theme --> comebackCash
    theme --> workbook
    backstock --> themeBundle
    comebackCash --> themeBundle
    workbook --> themeBundle
    bs5js --> masonry
```

### Directory Map

**NEW: Vendor Libraries (Bootstrap 5 + Masonry)**
```
public_html/css/vendor/                   # NEW: Framework CSS
├── bootstrap.min.css                     # NEW: Bootstrap 5.3.3 (~230KB)
└── bootstrap.min.css.map                 # NEW: Source map for debugging

public_html/js/vendor/                    # NEW: Framework JS
├── bootstrap.bundle.min.js               # NEW: Bootstrap 5 JS + Popper (~80KB)
└── masonry.pkgd.min.js                   # NEW: Masonry layout (~25KB)
```

**NEW: BuyerKiosk Theme Layer**
```
public_html/css/admin/                    # NEW: Theme root directory
├── tokens.css                            # NEW: Brand CSS variables (~100 lines)
│                                         #      Overrides Bootstrap 5 defaults
│
├── admin-theme.css                       # NEW: Component customizations (~300 lines)
│                                         #      Cards, buttons, forms with brand styling
│
├── modules/                              # Page-specific overrides
│   ├── backstock.css                     # MIGRATE: From css/backstock-home.css
│   ├── comeback-cash.css                 # MIGRATE: From css/workspace/comeback-cash.css
│   └── workbook.css                      # MIGRATE: From css/workspace/workbook.css
│
├── vendor/                               # Third-party integration styles
│   └── datatables-theme.css              # NEW: DataTables brand integration
│
└── admin-theme.min.css                   # BUILD OUTPUT: Theme bundle (~50KB)
```

**MODIFY: Template CSS Loading**
```
userfrosting/templates/themes/default/
├── layouts/
│   └── admin-base.html                   # MODIFY: Load Bootstrap 5 + theme CSS
├── workspace/layouts/
│   └── workspace-head.html               # MODIFY: Replace BS3 with BS5 + theme
└── partials/
    └── admin-head.html                   # MODIFY: New CSS loading order
```

**MODIFY: Template JS Loading**
```
userfrosting/templates/themes/default/
├── components/
│   └── scripts.html                      # MODIFY: Load Bootstrap 5 JS bundle
├── partials/
│   └── admin-scripts.html                # MODIFY: Add Masonry for card grids
└── workspace/layouts/
    └── workspace-scripts.html            # MODIFY: Load Bootstrap 5 JS for workspace pages
```

**DELETE: Legacy CSS/JS (after migration)**
```
public_html/css/
├── bootstrap-3.3.2.css                   # DELETE: 138KB legacy file
├── bootstrap-custom.css                  # DELETE: Bootstrap 3 overrides
├── backstock-home.css                    # DELETE: Migrated to modules/backstock.css
└── survey-results.css                    # DELETE: Migrated to components

public_html/js/
├── bootstrap.min.js                      # DELETE: Bootstrap 3 JS
└── bootstrap.js                          # DELETE: Bootstrap 3 JS (unminified)
```

**PRESERVE: Vendor CSS (no changes)**
```
public_html/css/
├── datatables/                           # PRESERVE: DataTables library
├── select2/                              # PRESERVE: Select2 library
├── iCheck/                               # PRESERVE: Checkbox library
├── fancyBox/                             # PRESERVE: Lightbox library
├── datepicker/                           # PRESERVE: Date picker library
└── font-awesome-6.min.css                # PRESERVE: Icon library
```

### Interface Specifications

For a CSS design system, "interfaces" are the CSS class APIs that developers use in templates.

#### CSS Class Naming Convention (Interface Contract)

```yaml
# Naming Pattern: component-modifier or component-element
pattern: "[component]-[element]" or "[component]-[modifier]"

examples:
  - .btn                       # Base button
  - .btn-primary               # Primary variant
  - .btn-sm                    # Size modifier
  - .card                      # Base card
  - .card-header               # Card child element
  - .stat-card                 # Compound component
  - .stat-card-value           # Stat card child
  - .badge-success             # Badge variant
```

#### Component Class API Reference

**Buttons** (`components/buttons.css`)
```css
/* Base */
.btn                           /* Base button styles */

/* Variants */
.btn-primary                   /* Primary gradient button */
.btn-secondary                 /* White/bordered button */
.btn-ghost                     /* Transparent background */
.btn-destructive               /* Red/danger actions */

/* Sizes */
.btn-sm                        /* Small: padding 0.5rem 1rem */
.btn-lg                        /* Large: padding 1.25rem 2.5rem */

/* Modifiers */
.btn-pill                      /* Rounded pill shape */
.btn-icon                      /* Icon-only button */
.btn-block                     /* Full-width button */
```

**Cards** (`components/cards.css`)
```css
/* Base */
.card                          /* White bg, border, shadow */
.card-header                   /* Card header section */
.card-body                     /* Card content area */
.card-footer                   /* Card footer section */

/* Stat Cards (KPI display) */
.stat-card                     /* Stat card container */
.stat-card-icon                /* Icon container */
.stat-card-value               /* Large number display */
.stat-card-label               /* Description text */
.stat-card-primary             /* Purple theme variant */
.stat-card-success             /* Green theme variant */
.stat-card-warning             /* Amber theme variant */
.stat-card-danger              /* Rose theme variant */
.stat-card-info                /* Blue theme variant */
```

**Badges** (`components/badges.css`)
```css
/* Base */
.badge                         /* Inline badge/pill */

/* Semantic Variants */
.badge-primary                 /* Purple/primary */
.badge-success                 /* Green/success */
.badge-warning                 /* Amber/warning */
.badge-danger                  /* Rose/error */
.badge-info                    /* Blue/info */
.badge-muted                   /* Gray/neutral */
```

**Forms** (`components/forms.css`)
```css
/* Inputs */
.form-input                    /* Text input styling */
.form-select                   /* Select dropdown */
.form-textarea                 /* Multi-line input */
.form-checkbox                 /* Checkbox styling */
.form-radio                    /* Radio button styling */

/* States */
.form-input-error              /* Error state (red border) */
.form-input-success            /* Success state (green border) */

/* Labels & Help */
.form-label                    /* Input label */
.form-help                     /* Help text below input */
.form-error                    /* Error message text */
```

#### Data Storage Changes

Not applicable - this feature has no database schema changes.

#### API Endpoint Changes

**NEW: Style Guide Reference Page Route**

```yaml
Endpoint: Style Guide Reference Page
  Method: GET
  Path: /admin/style-guide
  Auth: Admin user required
  Response: HTML page (Twig template)
  Purpose: Live component reference for developers
```

#### Integration Points

```yaml
# Template Integration
- from: Twig Templates
  to: CSS Classes
  integration: "Templates reference CSS classes via class attributes"
  contract: "Class names in templates must match design system CSS"

# JavaScript Integration (preserved)
- from: DataTables JS
  to: .dataTables_* classes
  integration: "DataTables generates these classes - CSS must style them"
  contract: "DataTables class names are immutable"

- from: Select2 JS
  to: .select2-* classes
  integration: "Select2 generates these classes - CSS must style them"
  contract: "Select2 class names are immutable"

# External Resources
- from: Google Fonts CDN
  to: Inter font family
  integration: "<link> tag in template head"
  fallback: "System fonts if CDN fails"
```

### Implementation Examples

**Purpose**: Provide strategic code examples to clarify CSS architecture patterns.

#### Example: CSS Variable Token System

**Why this example**: Shows how design tokens should be structured in `tokens.css` for consistency and theming support.

```css
/* tokens.css - The single source of truth for all design values */
:root {
    /* ===== COLOR TOKENS ===== */

    /* Primary (Purple) - Main brand color */
    --primary-50: #f5f3ff;
    --primary-100: #ede9fe;
    --primary-200: #ddd6fe;
    --primary-300: #c4b5fd;
    --primary-400: #a78bfa;
    --primary-500: #8b5cf6;
    --primary-600: #7c3aed;    /* ← Main accent */
    --primary-700: #6d28d9;
    --primary-800: #5b21b6;
    --primary-900: #4c1d95;

    /* Primary Gradient (for buttons, headers) */
    --gradient-primary: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

    /* Semantic Status Colors */
    --status-success: #22c55e;
    --status-warning: #f59e0b;
    --status-danger: #f43f5e;
    --status-info: #3b82f6;

    /* ===== SPACING TOKENS ===== */
    --space-1: 0.25rem;   /* 4px */
    --space-2: 0.5rem;    /* 8px */
    --space-3: 0.75rem;   /* 12px */
    --space-4: 1rem;      /* 16px */
    --space-6: 1.5rem;    /* 24px */
    --space-8: 2rem;      /* 32px */

    /* ===== TYPOGRAPHY TOKENS ===== */
    --font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
    --font-size-sm: 0.875rem;
    --font-size-base: 1rem;
    --font-size-lg: 1.125rem;
    --font-size-2xl: 1.5rem;

    /* ===== EFFECT TOKENS ===== */
    --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    --radius-md: 0.375rem;
    --radius-lg: 0.5rem;
    --radius-xl: 0.75rem;
    --transition-fast: 150ms ease;
}
```

#### Example: Component Using Tokens

**Why this example**: Demonstrates how components should reference tokens, never hardcode values.

```css
/* components/buttons.css - Always reference tokens */
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: var(--space-2);
    padding: var(--space-4) var(--space-6);
    font-family: var(--font-family);
    font-size: var(--font-size-base);
    font-weight: 600;
    border-radius: var(--radius-lg);
    cursor: pointer;
    transition: all var(--transition-fast);
}

.btn-primary {
    color: #ffffff;
    background: var(--gradient-primary);
    border: none;
    box-shadow: 0 4px 14px 0 rgba(102, 126, 234, 0.4);
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px 0 rgba(102, 126, 234, 0.5);
}

/* WRONG: Never hardcode values */
.btn-wrong {
    padding: 16px 24px;           /* ❌ Should use var(--space-4) var(--space-6) */
    background: #7c3aed;          /* ❌ Should use var(--primary-600) */
    border-radius: 8px;           /* ❌ Should use var(--radius-lg) */
}
```

#### Example: Template Class Usage (Twig)

**Why this example**: Shows how Twig templates should apply design system classes.

```twig
{# CORRECT: Using design system classes #}
<div class="stat-card stat-card-success">
    <div class="stat-card-icon">
        <i class="fa-solid fa-dollar-sign"></i>
    </div>
    <div class="stat-card-value">$12,450</div>
    <div class="stat-card-label">Today's Sales</div>
</div>

<button class="btn btn-primary">
    <i class="fa-solid fa-plus"></i>
    Add Item
</button>

{# WRONG: Using legacy Bootstrap classes #}
<div class="panel panel-default">          {# ❌ Use .card instead #}
    <div class="panel-heading">Title</div>  {# ❌ Use .card-header instead #}
    <div class="panel-body">Content</div>   {# ❌ Use .card-body instead #}
</div>

<span class="label label-success">Active</span>  {# ❌ Use .badge .badge-success #}
```

## Runtime View

### Primary Flow: CSS Loading Sequence

How CSS reaches the browser when an admin page loads:

```mermaid
sequenceDiagram
    actor Browser
    participant Server as Web Server
    participant Twig as Twig Engine
    participant CDN as Google Fonts CDN

    Browser->>Server: GET /admin/backstock
    Server->>Twig: Render admin template
    Twig-->>Server: HTML with CSS links
    Server-->>Browser: HTML response

    par Parallel CSS Loading
        Browser->>CDN: GET Inter font family
        Browser->>Server: GET /css/admin/admin.min.css
        Browser->>Server: GET /css/font-awesome-6.min.css
    end

    CDN-->>Browser: Font files
    Server-->>Browser: CSS bundle
    Server-->>Browser: Icon CSS

    Browser->>Browser: Apply styles, render page
```

### Developer Workflow: Using the Design System

#### Primary Flow: Developer Building New Admin Page
1. Developer opens Style Guide Reference Page at `/admin/style-guide`
2. Developer browses component sections to find needed patterns
3. Developer copies HTML code snippet from reference page
4. Developer pastes into Twig template with appropriate context data
5. Developer previews page - styles apply automatically from `admin.min.css`
6. Developer validates visual appearance matches reference page

#### Primary Flow: Developer Migrating Legacy Page
1. Developer identifies legacy Bootstrap classes in template (`.panel`, `.label-*`)
2. Developer opens Style Guide Reference Page "Migration Guide" section
3. Developer looks up legacy → modern mapping (e.g., `.panel` → `.card`)
4. Developer updates template class attributes
5. Developer removes any legacy-specific CSS overrides
6. Developer validates page appearance matches modern design system

### Error Handling

**CSS Loading Failure**:
- If `admin.min.css` fails to load: Page displays with browser defaults (readable but unstyled)
- If Google Fonts CDN fails: System fonts used as fallback (`-apple-system, BlinkMacSystemFont`)
- If Font Awesome fails: Icons display as empty squares (visible but degraded)

**Development Errors**:
- Missing CSS class: Element renders with no styling - developer checks Style Guide for correct class name
- Incorrect class combination: Developer validates against Style Guide Reference Page examples
- Legacy class still in use: Build lint script warns about deprecated classes

### CSS Build Process

```
PROCESS: CSS Bundle Build
INPUT: Source CSS files in public_html/css/admin/*/
OUTPUT: admin.min.css (minified bundle)

1. CONCATENATE:
   - tokens/tokens.css         (first - defines variables)
   - base/reset.css
   - base/typography.css
   - layouts/grid.css
   - layouts/admin-layout.css
   - components/*.css          (all component files)
   - modules/*.css             (all module files)
   - utilities/*.css           (last - highest specificity)

2. MINIFY:
   - Remove comments
   - Remove whitespace
   - Shorten color values where possible

3. VERSION:
   - Generate hash of content
   - Update cache-busting query parameter

4. OUTPUT:
   - admin.min.css (production bundle)
   - admin.css (development - unminified for debugging)
```

## Deployment View

### Single Application Deployment

- **Environment**: Client-side (browser) - CSS is static assets served from web server
- **Configuration**: No environment variables needed for CSS
- **Dependencies**:
  - Google Fonts CDN (Inter font family)
  - Font Awesome 6 (local file)
- **Performance**:
  - Theme bundle size: <50KB minified (admin-theme.min.css only)
  - Bootstrap 5 CSS: ~230KB (loaded separately from CDN/vendor)
  - Total custom CSS target: <200KB (all project CSS excluding Bootstrap)
  - Cache strategy: Long cache duration (1 year) with hash-based cache busting
  - First paint: CSS should not block rendering beyond initial load

### Deployment Process

**Pre-Deployment (Development)**:
1. Developer runs `php userfrosting/conductor build-css --minify` to generate `admin-theme.min.css`
2. Build script outputs version hash to `public_html/css/admin/version.txt` for cache-busting
3. Developer commits both source files AND built bundle to git
4. Pull request includes CSS diff for review

**Deployment (Envoyer.io)**:
1. Envoyer pulls latest code including pre-built CSS bundle
2. No build step needed on server - CSS is pre-compiled
3. Cache-busting version parameter updated in templates

### Rollback Strategy

**If CSS Issues Detected Post-Deploy**:
1. Git revert to previous commit (CSS is version controlled)
2. Re-deploy via Envoyer.io
3. Previous CSS bundle restored immediately

**Feature Flag Alternative** (optional):
- Could use Twig variable to conditionally load legacy vs new CSS during migration
- Example: `{% if use_new_design_system %}admin.min.css{% else %}legacy-bundle.css{% endif %}`
- Allows gradual rollout per page or user segment

### Hard Cutover Considerations

**Pre-Deployment Checklist**:
- [ ] All Twig templates updated to use new class names
- [ ] All legacy Bootstrap 3 class references removed
- [ ] Style Guide Reference Page tested with all components
- [ ] Visual regression testing on all major admin pages
- [ ] CSS build script runs successfully
- [ ] Theme bundle size under 50KB (admin-theme.min.css)
- [ ] Total custom CSS under 200KB (excluding Bootstrap)

**Post-Deployment Verification**:
- [ ] Admin login page renders correctly
- [ ] Backstock home page stat cards display
- [ ] Comeback Cash event cards display
- [ ] All modals open with gradient headers
- [ ] DataTables styling intact
- [ ] Select2 dropdowns functional

## Cross-Cutting Concepts

### Pattern Documentation

```yaml
# Existing patterns used in this feature
- pattern: @docs/guides/style-guide.md
  relevance: CRITICAL
  why: "Master design system documentation - all CSS must conform to these standards"

# New patterns to be created
- pattern: @docs/patterns/css-design-system.md (NEW)
  relevance: HIGH
  why: "Document the CSS architecture layers and build process for future maintainers"

- pattern: @docs/patterns/css-migration-guide.md (NEW)
  relevance: MEDIUM
  why: "Bootstrap 3 to design system class mapping for migration reference"
```

### Interface Specifications

```yaml
# Existing interface documentation
- interface: @docs/guides/style-guide.md (CSS Variables section)
  relevance: CRITICAL
  why: "Defines all CSS custom property names and values"

# New interface documentation
- interface: @docs/interfaces/css-class-api.md (NEW)
  relevance: HIGH
  why: "Documents all component class names and their expected HTML structure"
```

### System-Wide Patterns

- **Security**: Not applicable - CSS has no security concerns beyond XSS (which is handled by Twig escaping)
- **Error Handling**: CSS gracefully degrades - missing classes result in unstyled elements, not errors
- **Performance**:
  - Single CSS bundle reduces HTTP requests
  - CSS variables computed once by browser
  - Long cache duration with hash-based cache busting
- **i18n/L10n**: CSS supports RTL via logical properties where appropriate (not implemented this phase)
- **Logging/Auditing**: Build script logs which files are concatenated and final bundle size

### Multi-Component Patterns

Not applicable - single CSS bundle serves all admin pages.

### Implementation Patterns

#### CSS Code Patterns and Conventions

**File Organization**:
- One component per file (e.g., `buttons.css`, `cards.css`)
- Comment blocks separating major sections within files
- Alphabetical ordering of properties within rules (recommended)

**Naming Conventions**:
- Component classes: `.component-name` (e.g., `.stat-card`)
- Child elements: `.component-element` (e.g., `.stat-card-value`)
- Modifier classes: `.component-modifier` (e.g., `.stat-card-success`)
- State classes: `.is-active`, `.is-disabled`, `.has-error`
- Utility classes: `.utility-value` (e.g., `.mt-4`, `.text-center`)

**Variable Naming**:
```css
/* Colors: --color-shade (e.g., --primary-600) */
/* Spacing: --space-number (e.g., --space-4) */
/* Typography: --font-property (e.g., --font-size-lg) */
/* Effects: --effect-size (e.g., --shadow-md) */
/* Radius: --radius-size (e.g., --radius-lg) */
```

#### State Management Patterns

CSS handles visual states through:
- **Interactive states**: `:hover`, `:focus`, `:active`, `:disabled`
- **Validation states**: `.has-error`, `.has-success`
- **Visibility states**: `.is-hidden`, `.is-collapsed`, `.is-loading`
- **Theme states**: `[data-theme="dark"]` selector (future)

#### Performance Characteristics

**Selector Efficiency**:
- Prefer class selectors over element or attribute selectors
- Avoid deeply nested selectors (max 3 levels)
- No ID selectors for styling

**File Size Optimization**:
- Use shorthand properties where applicable
- Avoid redundant declarations
- Share common values through CSS variables

#### CSS Component Structure Pattern

```pseudocode
COMPONENT: .component-name
  BASE_STYLES:
    - Display, position, sizing
    - Box model (margin, padding, border)
    - Background, colors
    - Typography
    - Effects (shadows, transitions)

  CHILD_ELEMENTS:
    .component-header: Header area styles
    .component-body: Main content styles
    .component-footer: Footer area styles

  VARIANTS:
    .component-primary: Primary color theme
    .component-success: Success/green theme
    .component-warning: Warning/amber theme

  STATES:
    :hover: Interactive hover effect
    :focus: Keyboard focus indicator
    .is-active: Active/selected state
    .is-disabled: Disabled state

  RESPONSIVE:
    @media (max-width: 767px): Mobile adjustments
    @media (max-width: 991px): Tablet adjustments
```

#### Test Pattern: Visual Validation

```pseudocode
TEST_SCENARIO: "Component renders correctly"
  SETUP:
    - Load Style Guide Reference Page
    - Navigate to component section

  VERIFY_VISUAL:
    - Colors match design tokens
    - Spacing consistent with spacing scale
    - Typography uses correct font sizes
    - Hover states apply correctly
    - Focus states visible for accessibility
    - Responsive layout works at breakpoints

  VERIFY_CROSS_BROWSER:
    - Chrome: renders correctly
    - Firefox: renders correctly
    - Safari: renders correctly
    - Edge: renders correctly
```

### Integration Points

- **Connection Points**:
  - Twig templates load CSS via `<link>` tags
  - HTML elements reference CSS classes via `class` attributes
  - JavaScript libraries (DataTables, Select2) generate DOM with CSS classes

- **Data Flow**:
  - CSS is static - no runtime data flow
  - Design tokens flow: STYLE_GUIDE.md → tokens.css → component CSS → browser

- **Events**: Not applicable - CSS does not emit or consume events

## Architecture Decisions

- [x] **ADR-1 CSS Architecture**: Layered ITCSS-inspired architecture with tokens → base → layouts → components → modules → utilities
  - Rationale: Prevents specificity conflicts, scales well, proven in workspace.css
  - Trade-offs: Requires developer discipline to place CSS in correct layer
  - Alternatives considered: Flat file structure, Atomic CSS, CSS-in-JS
  - **User confirmed: ✅ Yes**

- [x] **ADR-2 No CSS Preprocessor**: Use plain CSS with native CSS variables instead of Sass/Less
  - Rationale: CSS variables are sufficient, avoids build complexity, better runtime theming support
  - Trade-offs: No nesting (requires flat selectors), no mixins (use utility classes instead)
  - Alternatives considered: Sass, Less, PostCSS
  - **User confirmed: ✅ Yes**

- [x] **ADR-3 Single Bundle Strategy**: All admin CSS in one `admin.min.css` bundle
  - Rationale: Reduces HTTP requests, simplifies caching, easier deployment
  - Trade-offs: Larger initial download vs multiple smaller files loaded on demand
  - Alternatives considered: Per-page CSS, critical CSS extraction
  - **User confirmed: ✅ Yes**

- [x] **ADR-4 Hard Cutover Migration**: Remove Bootstrap 3 entirely, no gradual migration
  - Rationale: Cleaner codebase, no dual maintenance, forced consistency
  - Trade-offs: Higher risk at deployment, requires thorough template updates
  - Alternatives considered: Gradual page-by-page migration, Bootstrap 3→5 upgrade
  - **User confirmed: ✅ Yes**

- [x] **ADR-5 Conductor CLI Build**: PHP-based build via `php userfrosting/conductor build-css` command
  - Rationale: No Node.js dependency, integrates with existing Conductor CLI pattern, simple PHP concatenation/minification
  - Trade-offs: Less feature-rich than Webpack/Vite, no source maps, no auto-prefixing
  - Alternatives considered: Shell script, Webpack, Vite, Gulp
  - **User confirmed: ✅ Yes**

- [x] **ADR-6 Vendor CSS Preserved**: Keep DataTables, Select2, iCheck CSS unchanged
  - Rationale: These libraries have tight JS coupling, changing risks breaking functionality
  - Trade-offs: Visual inconsistency with these components, duplicate styling effort
  - Alternatives considered: Custom theming for each vendor library
  - **User confirmed: ✅ Yes**

## Quality Requirements

- **Performance**:
  - Bundle size: <200KB minified (current target)
  - First contentful paint: No CSS-caused blocking beyond initial bundle load
  - CSS selector performance: Max 3 levels of nesting, prefer class selectors

- **Usability**:
  - Style Guide Reference Page: All components visible and copy-paste ready
  - Consistent visual language: All admin pages use design system components
  - Developer experience: Find any component in Style Guide within 30 seconds

- **Accessibility**:
  - Focus states visible on all interactive elements
  - Color contrast: 4.5:1 for body text, 3:1 for large text
  - Touch targets: Minimum 44x44px for interactive elements
  - Respect `prefers-reduced-motion` media query

- **Maintainability**:
  - CSS variables for all design tokens (no hardcoded values in components)
  - One component per file for easy location
  - Consistent naming convention across all files

- **Reliability**:
  - Graceful degradation if CSS fails to load
  - Fallback fonts if Google Fonts unavailable
  - No JavaScript required for styling (CSS-only)

## Risks and Technical Debt

### Known Technical Issues

- **Bootstrap 3 Deep Integration**: 267 Bootstrap class references across root CSS files - removing without template updates will break styling
- **Vendor CSS Coupling**: DataTables, Select2, iCheck have JavaScript that generates specific class names - cannot rename without breaking JS
- **Hardcoded Colors**: ~606 hardcoded color values in workspace CSS alone - migration to variables is incomplete
- **Multiple Font Awesome Versions**: FA4, FA5, and FA6 may all be loaded - need to consolidate to FA6 only

### Technical Debt

- **Duplicate Styling**: Similar stat-card patterns exist in backstock-home.css and comeback-cash.css - should be unified
- **Inconsistent Variable Naming**: `--admin-text-*` vs `--font-size-*` naming inconsistency
- **Legacy CSS Bundle**: `min/common.min.css` last built January 2019 - stale and unused
- **No Cache Busting**: Workspace CSS files lack version parameters for cache invalidation

### Implementation Gotchas

- **CSS Load Order Matters**: Tokens must load first, utilities last - incorrect concatenation breaks cascade
- **Bootstrap Reset Conflicts**: Bootstrap's reset CSS may conflict with new design system reset - test thoroughly
- **DataTables Specificity**: DataTables CSS has high specificity - design system styles may not override without `!important`
- **Select2 Container Classes**: Select2 generates `.select2-container--*` classes dynamically - must style by attribute or container
- **Twig Raw Blocks**: Handlebars-style `{{ }}` in templates must be wrapped in `{% raw %}` blocks
- **Class Name JavaScript Bindings**: Some JavaScript uses class names like `.panel` for selection - verify no JS depends on legacy class names before removal

## Test Specifications

### Critical Test Scenarios

**Scenario 1: Style Guide Reference Page Loads**
```gherkin
Given: User is authenticated as admin
When: User navigates to /admin/style-guide
Then: Page loads without CSS errors
And: All component sections are visible
And: Color swatches display correctly
And: Code snippets are copy-able
```

**Scenario 2: Component Visual Consistency**
```gherkin
Given: Style Guide Reference Page is loaded
When: User views each component section
Then: Components match STYLE_GUIDE.md specifications
And: Primary color is #7c3aed
And: Font family is Inter
And: Border radius values match design tokens
```

**Scenario 3: Admin Page Migration**
```gherkin
Given: Backstock home page with new CSS classes
When: User loads /admin/:typeNum/backstock
Then: Stat cards display with correct styling
And: Tables have DataTables styling applied
And: Buttons use gradient primary style
And: No Bootstrap 3 `.panel` classes visible in DOM
```

**Scenario 4: CSS Bundle Performance**
```gherkin
Given: Production CSS bundle is built
When: Bundle size is measured
Then: admin.min.css is less than 200KB
And: No duplicate CSS rules exist
And: All CSS variables are defined
```

**Scenario 5: Cross-Browser Rendering**
```gherkin
Given: Style Guide Reference Page
When: Page is viewed in Chrome, Firefox, Safari, Edge
Then: Components render consistently across browsers
And: CSS variables are supported
And: Gradients display correctly
And: Transitions animate smoothly
```

**Scenario 6: Responsive Layout**
```gherkin
Given: Admin page using design system
When: Viewport is resized to mobile (375px)
Then: Stat cards stack vertically
And: Tables are horizontally scrollable
And: Buttons remain touch-friendly (44px min)
And: Navigation collapses appropriately
```

### Test Coverage Requirements

- **Visual Validation**:
  - All component variants render correctly
  - Color tokens match hex values in STYLE_GUIDE.md
  - Typography uses correct font sizes
  - Spacing follows design token scale

- **Accessibility**:
  - Focus states visible on all interactive elements
  - Color contrast passes WCAG 2.1 AA
  - Reduced motion respected when preference set

- **Integration**:
  - DataTables styling applies correctly
  - Select2 dropdowns maintain styling
  - Modals open with gradient headers
  - Forms validate with error/success states

- **Build Process**:
  - CSS concatenation produces valid CSS
  - Minification reduces file size without breaking styles
  - Cache-busting version parameter is generated

- **Migration Validation**:
  - No Bootstrap 3 classes remain in migrated templates
  - All legacy `.panel` converted to `.card`
  - All legacy `.label-*` converted to `.badge-*`

---

## Glossary

### Domain Terms

| Term | Definition | Context |
|------|------------|---------|
| Design Token | A named value (color, spacing, etc.) that defines a design decision | CSS variables like `--primary-600` |
| Component | A reusable UI element with consistent styling | Buttons, cards, badges |
| Style Guide | Documentation of design patterns and components | `/admin/style-guide` page |
| Hard Cutover | Removing legacy code entirely in one deployment | Bootstrap 3 → Design System migration |

### Technical Terms

| Term | Definition | Context |
|------|------------|---------|
| CSS Variable | Custom property defined with `--name: value` syntax | `--primary-600: #7c3aed` |
| ITCSS | Inverted Triangle CSS - layered architecture methodology | tokens → base → layouts → components |
| BEM | Block Element Modifier - CSS naming convention | `.block__element--modifier` (modified version used) |
| Specificity | CSS rule precedence based on selector type | Class selectors preferred over ID/element |
| CSS Reset | Styles that normalize browser defaults | `reset.css` removes inconsistencies |

### API/Interface Terms

| Term | Definition | Context |
|------|------------|---------|
| Class API | The public CSS classes available for use | `.btn`, `.card`, `.badge-success` |
| Modifier Class | A class that changes a component's appearance | `.btn-primary`, `.stat-card-success` |
| Utility Class | Single-purpose helper class | `.mt-4`, `.text-center` |
| Vendor CSS | Third-party library stylesheets | DataTables, Select2, iCheck |

### Legacy Terms (Bootstrap 3)

| Legacy Class | Modern Replacement | Notes |
|--------------|-------------------|-------|
| `.panel` | `.card` | Container component |
| `.panel-heading` | `.card-header` | Card top section |
| `.panel-body` | `.card-body` | Card content area |
| `.label` | `.badge` | Inline status indicator |
| `.label-success` | `.badge-success` | Green status badge |
| `.btn-default` | `.btn-secondary` | Secondary button style |
