# Frontend Dashboard

## Overview

The **Bakery-IA Frontend Dashboard** is a modern, responsive React-based web application that provides bakery owners and operators with comprehensive real-time visibility into their operations. Built with TypeScript and cutting-edge React ecosystem tools, it delivers an intuitive interface for demand forecasting, inventory management, production planning, and operational analytics.

## Key Features

### AI-Powered Demand Forecasting
- **Visual Forecast Charts** - Interactive Chart.js visualizations of demand predictions
- **Multi-Day Forecasts** - View predictions up to 30 days ahead
- **Confidence Intervals** - Visual representation of prediction uncertainty
- **Historical Comparison** - Compare forecasts with actual sales
- **Forecast Accuracy Metrics** - Track model performance over time
- **Weather Integration** - See how weather impacts demand
- **One-Click Forecast Generation** - Generate forecasts for all products instantly

### Real-Time Operational Dashboard
- **Live KPI Cards** - Real-time metrics for sales, inventory, production
- **Alert Stream (SSE)** - Instant notifications for critical events
- **AI Impact Showcase** - Celebrate AI wins with handling rate and savings metrics
- **Prevented Issues Card** - Highlights problems AI automatically resolved
- **Production Status** - Live view of current production batches
- **Inventory Levels** - Color-coded stock levels with expiry warnings
- **Order Pipeline** - Track customer orders from placement to fulfillment

### Enriched Alert System (NEW)
- **Multi-Dimensional Priority Scoring** - Intelligent 0-100 priority scores with 4 weighted factors
  - Business Impact (40%): Financial consequences, affected orders
  - Urgency (30%): Time sensitivity, deadlines
  - User Agency (20%): Can you take action?
  - AI Confidence (10%): Prediction certainty
- **Smart Alert Classification** - 5 alert types for clear user intent
  - 🔴 ACTION_NEEDED: Requires your decision or action
  - 🎉 PREVENTED_ISSUE: AI already handled (celebration!)
  - 📊 TREND_WARNING: Pattern detected, early warning
  - ⏱️ ESCALATION: Auto-action pending, can cancel
  - ℹ️ INFORMATION: FYI only, no action needed
- **3-Tab Alert Hub** - Organized navigation (All Alerts / For Me / Archived)
- **Auto-Action Countdown** - Real-time timer for escalation alerts with one-click cancel
- **Priority Score Explainer** - Educational modal showing exact scoring formula
- **Trend Visualizations** - Inline sparklines and directional indicators for trend warnings
- **Action Consequence Previews** - See outcomes before taking action (financial impact, affected systems, reversibility)
- **Response Time Gamification** - Track your alert response performance by priority level with benchmarks
- **Email Digests** - Daily/weekly summaries with celebration-first messaging
- **Full Internationalization** - Complete translations (English, Spanish, Basque)

### Panel de Control (Dashboard Redesign - NEW)
A comprehensive dashboard redesign focused on Jobs-To-Be-Done principles, progressive disclosure, and mobile-first UX.

#### **New Dashboard Components**
- **GlanceableHealthHero** - Traffic light status system (🟢🟡🔴)
  - Understand bakery health in 3 seconds (5 AM test)
  - Collapsible checklist with progressive disclosure
  - Shows urgent action count prominently
  - Real-time SSE integration for critical alerts
  - Mobile-optimized with large touch targets (44x44px minimum)
- **SetupWizardBlocker** - Full-page setup wizard
  - Blocks dashboard access when <50% setup complete
  - Step-by-step wizard interface with numbered steps
  - Progress bar (0-100%) with completion indicators
  - Clear CTAs for each configuration section
  - Ensures critical data exists before AI can function
- **CollapsibleSetupBanner** - Compact reminder banner
  - Appears when 50-99% setup complete
  - Collapsible (default: collapsed) to minimize distraction
  - Dismissible for 7 days via localStorage
  - Shows remaining sections with item counts
  - Links directly to incomplete sections
- **UnifiedActionQueueCard** - Consolidated action queue
  - Time-based grouping (Urgent / Today / This Week)
  - Smart actions with embedded delivery workflows
  - Escalation badges show pending duration
  - StockReceiptModal integration for delivery actions
  - Real-time updates via SSE
- **ExecutionProgressTracker** - Plan vs actual tracking
  - Visual progress bars for production, deliveries, approvals
  - Shows what's on track vs behind schedule
  - Business impact highlights (orders at risk)
- **IntelligentSystemSummaryCard** - AI insights dashboard
  - Shows what AI has done and why
  - Celebration-focused messaging for prevented issues
  - Recommendations with confidence scores

#### **Three-State Setup Flow Logic**
```
Progress < 50%  → SetupWizardBlocker (BLOCKS dashboard access)
Progress 50-99% → CollapsibleSetupBanner (REMINDS but allows access)
Progress 100%   → Hidden (COMPLETE, no reminder)
```

**Setup Progress Calculation**:
- **Inventory**: Minimum 3 ingredients, recommended 10
- **Suppliers**: Minimum 1 supplier, recommended 3
- **Recipes**: Minimum 1 recipe, recommended 3
- **Quality**: Optional, recommended 2 templates

**Rationale**: Critical data (ingredients, suppliers, recipes) must exist for AI to function. Recommended data improves AI but isn't required. Progressive disclosure prevents overwhelming new users while reminding them of missing features.

#### **Design Principles**
- **Glanceable First (5-Second Test)** - User should understand status in 3 seconds at 5 AM on phone
- **Mobile-First / One-Handed** - All critical actions in thumb zone, 44x44px min touch targets
- **Progressive Disclosure** - Show 20% that matters 80% of the time, hide complexity until requested
- **Outcome-Focused** - Show business impact ($€, time saved) not just features
- **Trust-Building** - Always show AI reasoning, escalation tracking, financial impact transparency

#### **StockReceiptModal Integration Pattern**
Cross-component communication using CustomEvents for opening stock receipt modal from dashboard alerts:

```typescript
// Emit from smartActionHandlers.ts
window.dispatchEvent(new CustomEvent('stock-receipt:open', {
  detail: {
    receipt_id?: string,
    po_id: string,
    tenant_id: string,
    mode: 'create' | 'edit'
  }
}));

// Listen in UnifiedActionQueueCard.tsx
useEffect(() => {
  const handler = (e: CustomEvent) => {
    setStockReceiptData({
      isOpen: true,
      receipt: e.detail
    });
  };
  window.addEventListener('stock-receipt:open', handler);
  return () => window.removeEventListener('stock-receipt:open', handler);
}, []);
```

**Workflow**: Delivery alerts (`DELIVERY_ARRIVING_SOON`, `STOCK_RECEIPT_INCOMPLETE`) trigger modal opening with PO context. User completes stock receipt with lot-level tracking and expiration dates. Confirmation triggers `delivery.received` event, auto-resolving related alerts.

#### **Deleted Components (Cleanup Rationale)**
The dashboard redesign replaced or merged 7 legacy components:
- `HealthStatusCard.tsx` → Replaced by **GlanceableHealthHero** (traffic light system)
- `InsightsGrid.tsx` → Merged into **IntelligentSystemSummaryCard**
- `ProductionTimelineCard.tsx` → Replaced by **ExecutionProgressTracker**
- `ActionQueueCard.tsx` → Replaced by **UnifiedActionQueueCard** (time-based grouping)
- `ConfigurationProgressWidget.tsx` → Replaced by **SetupWizardBlocker** + **CollapsibleSetupBanner**
- `AlertContextActions.tsx` → Merged into Alert Hub
- `OrchestrationSummaryCard.tsx` → Merged into system summary

**Net Impact**: Deleted ~1,200 lines of old code, added ~811 lines of new focused components, saved ~390 lines overall while improving UX.

#### **Dashboard Layout Order**
1. **Setup Flow** - Blocker or banner (contextual)
2. **GlanceableHealthHero** - Traffic light status
3. **UnifiedActionQueueCard** - What needs attention
4. **ExecutionProgressTracker** - Plan vs actual
5. **AI Impact Showcase** - Celebration cards for prevented issues
6. **IntelligentSystemSummaryCard** - What AI did and why
7. **Quick Action Links** - Navigation shortcuts

### Inventory Management
- **Stock Overview** - All ingredients with current levels and locations
- **Low Stock Alerts** - Automatic warnings when stock falls below thresholds
- **Expiration Tracking** - Prioritize items by expiration date
- **FIFO Compliance** - First-in-first-out consumption tracking
- **Stock Movements** - Complete audit trail of all inventory changes
- **Barcode Scanning Integration** - Quick stock updates via barcode

### Production Planning
- **Production Schedules** - Daily and weekly production calendars
- **Batch Tracking** - Monitor all active production batches
- **Quality Control** - Digital quality check forms and templates
- **Equipment Management** - Track equipment usage and maintenance
- **Recipe Execution** - Step-by-step recipe guidance for production staff
- **Capacity Planning** - Optimize production capacity utilization

### Procurement & Supplier Management
- **Automated Purchase Orders** - AI-generated procurement recommendations
- **Supplier Portal** - Manage supplier relationships and performance
- **Price Comparisons** - Compare supplier pricing across items
- **Delivery Tracking** - Track inbound shipments
- **Supplier Scorecards** - Rate suppliers on quality, delivery, and price

### Sales & Orders
- **Customer Order Management** - Process and track customer orders
- **Sales Analytics** - Revenue trends, product performance, customer insights
- **POS Integration** - Automatic sales data sync from Square/Toast/Lightspeed
- **Sales History** - Complete historical sales data with filtering and export

### Onboarding Wizard
- **Multi-Step Onboarding** - Guided 15-step setup process for new bakeries
- **POI Detection Step** - Automatic detection of nearby Points of Interest using bakery location
- **Progress Tracking** - Visual progress indicators and step completion
- **Data Persistence** - Save progress at each step
- **Smart Navigation** - Dynamic step dependencies and validation

### Multi-Tenant Administration
- **Tenant Settings** - Configure bakery-specific preferences
- **User Management** - Invite team members and assign roles
- **Subscription Management** - View and upgrade subscription plans
- **Billing Portal** - Stripe-powered billing and invoices

### ML Model Training
- **Training Dashboard** - Monitor ML model training progress
- **WebSocket Live Updates** - Real-time training status and metrics
- **Model Performance** - Compare model versions and accuracy
- **Training History** - Complete log of all training runs

## Technical Capabilities

### Modern React Architecture
- **React 18** - Latest React with concurrent features
- **TypeScript** - Type-safe development with full IntelliSense
- **Vite** - Lightning-fast build tool and dev server
- **Component-Based** - Modular, reusable components
- **Hooks-First** - Modern React patterns with custom hooks

### State Management
- **Zustand** - Lightweight global state management
- **TanStack Query (React Query)** - Server state management with caching
- **Local Storage Persistence** - Persist user preferences
- **Optimistic Updates** - Instant UI feedback before server confirmation

### UI/UX Components
- **Radix UI** - Accessible, unstyled component primitives
- **Tailwind CSS** - Utility-first CSS framework
- **Responsive Design** - Mobile, tablet, and desktop optimized
- **Dark Mode** (planned) - User-selectable theme
- **Accessible** - WCAG 2.1 AA compliant

### Data Visualization
- **Chart.js** - Interactive forecast and analytics charts
- **Recharts** - Declarative React charts for dashboards
- **Custom Visualizations** - Specialized charts for bakery metrics

### Forms & Validation
- **React Hook Form** - Performant form management
- **Zod** - TypeScript-first schema validation
- **Error Handling** - User-friendly validation messages
- **Auto-Save** - Background form persistence

### Real-Time Communication
- **Server-Sent Events (SSE)** - Real-time alert stream from gateway
- **WebSocket** - Live ML training progress updates
- **Auto-Reconnect** - Resilient connection management
- **Event Notifications** - Toast notifications for real-time events

### Internationalization
- **i18next** - Multi-language support
- **Spanish** - Default language for Spanish market
- **English** - Secondary language for international users
- **Date/Number Formatting** - Locale-aware formatting

### API Integration
- **TanStack Query** - Declarative data fetching with caching
- **Axios/Fetch** - HTTP client for REST APIs
- **JWT Authentication** - Token-based auth with auto-refresh
- **Request Interceptors** - Automatic token injection
- **Error Handling** - Centralized error boundary and retry logic

## Business Value

### For Bakery Owners
- **Time Savings** - 15-20 hours/week saved on manual planning
- **Reduced Waste** - Visual demand forecasts reduce overproduction by 20-40%
- **Better Decisions** - Data-driven insights replace guesswork
- **Mobile Access** - Manage bakery from anywhere (responsive design)
- **No Training Required** - Intuitive interface, minimal learning curve

### For Bakery Staff
- **Production Guidance** - Step-by-step recipes on screen
- **Quality Consistency** - Digital quality checklists
- **Inventory Visibility** - Know what's in stock without checking fridges
- **Task Prioritization** - Alerts show what needs immediate attention

### For Multi-Location Bakeries
- **Centralized Control** - Manage all locations from one dashboard
- **Performance Comparison** - Compare KPIs across locations
- **Standardized Processes** - Same interface at all locations

### For Platform Operations
- **Reduced Support Costs** - Intuitive UI reduces support tickets
- **User Engagement** - Real-time updates keep users engaged
- **Feature Discovery** - Guided onboarding increases feature adoption

## Technology Stack

### Core Framework
- **React 18.3** - JavaScript library for user interfaces
- **TypeScript 5.3** - Type-safe JavaScript superset
- **Vite 5.0** - Next-generation frontend tooling

### State Management & Data Fetching
- **Zustand 4.4** - Lightweight state management
- **TanStack Query (React Query) 5.8** - Async state management
- **Axios** - HTTP client

### UI & Styling
- **Radix UI** - Accessible component primitives
  - `@radix-ui/react-dialog` - Modal dialogs
  - `@radix-ui/react-dropdown-menu` - Dropdown menus
  - `@radix-ui/react-select` - Select components
  - `@radix-ui/react-tabs` - Tab navigation
- **Tailwind CSS 3.4** - Utility-first CSS framework
- **Headless UI** - Unstyled accessible components
- **Lucide React** - Beautiful, consistent icons

### Data Visualization
- **Chart.js 4.4** - Flexible JavaScript charting
- **react-chartjs-2** - React wrapper for Chart.js
- **Recharts 2.10** - Composable React charts
- **date-fns** - Modern date utility library

### Forms & Validation
- **React Hook Form 7.49** - Performant form library
- **Zod 3.22** - TypeScript-first schema validation
- **@hookform/resolvers** - Zod integration for React Hook Form

### Routing & Navigation
- **React Router 6.20** - Declarative routing for React
- **React Router DOM** - DOM bindings for React Router

### Internationalization
- **i18next 23.7** - Internationalization framework
- **react-i18next 13.5** - React bindings for i18next

### Real-Time Communication
- **EventSource API** - Native SSE support
- **WebSocket API** - Native WebSocket support
- **react-use-websocket** - React WebSocket hook

### Notifications & Feedback
- **react-hot-toast** - Beautiful toast notifications
- **react-loading-skeleton** - Loading placeholders

### Development Tools
- **ESLint** - JavaScript linter
- **Prettier** - Code formatter
- **TypeScript ESLint** - TypeScript linting rules
- **Vite Plugin React** - Fast refresh and JSX transform

## Application Structure

```
frontend/
├── src/
│   ├── components/          # Reusable UI components
│   │   ├── ui/              # Base UI components (buttons, inputs, etc.)
│   │   ├── charts/          # Chart components
│   │   ├── forms/           # Form components
│   │   ├── layout/          # Layout components (header, sidebar, etc.)
│   │   └── domain/          # Domain-specific components
│   │       └── onboarding/  # Onboarding wizard components
│   │           ├── steps/   # Individual step components
│   │           │   ├── POIDetectionStep.tsx  # POI detection UI
│   │           │   ├── SetupStep.tsx
│   │           │   └── ...
│   │           ├── context/ # Onboarding wizard context
│   │           └── WizardLayout.tsx
│   ├── pages/               # Page components (routes)
│   │   ├── Dashboard/       # Main dashboard
│   │   ├── Forecasting/     # Forecast management
│   │   ├── Inventory/       # Inventory management
│   │   ├── Production/      # Production planning
│   │   ├── Orders/          # Order management
│   │   ├── Suppliers/       # Supplier management
│   │   ├── Procurement/     # Procurement planning
│   │   ├── Settings/        # User settings
│   │   └── Auth/            # Login/register pages
│   ├── hooks/               # Custom React hooks
│   │   ├── useAuth.ts       # Authentication hook
│   │   ├── useSSE.ts        # Server-sent events hook
│   │   ├── useWebSocket.ts  # WebSocket hook
│   │   └── useQuery.ts      # API query hooks
│   ├── stores/              # Zustand stores
│   │   ├── authStore.ts     # Authentication state
│   │   ├── alertStore.ts    # Alert state
│   │   └── uiStore.ts       # UI state (sidebar, theme, etc.)
│   ├── api/                 # API client functions
│   │   ├── client/          # API client configuration
│   │   │   └── apiClient.ts # Axios client with tenant injection
│   │   ├── services/        # Service API modules
│   │   │   ├── onboarding.ts     # Onboarding API
│   │   │   ├── geocodingApi.ts   # Geocoding/address API
│   │   │   └── poiContextApi.ts  # POI detection API
│   │   ├── auth.ts          # Auth API
│   │   ├── forecasting.ts   # Forecasting API
│   │   ├── inventory.ts     # Inventory API
│   │   └── ...              # Other service APIs
│   ├── types/               # TypeScript type definitions
│   │   ├── api.ts           # API response types
│   │   ├── models.ts        # Domain model types
│   │   └── components.ts    # Component prop types
│   ├── utils/               # Utility functions
│   │   ├── date.ts          # Date formatting
│   │   ├── currency.ts      # Currency formatting
│   │   ├── validation.ts    # Validation helpers
│   │   └── format.ts        # General formatting
│   ├── locales/             # i18n translation files
│   │   ├── es/              # Spanish translations
│   │   └── en/              # English translations
│   ├── App.tsx              # Root component
│   ├── main.tsx             # Application entry point
│   └── router.tsx           # Route configuration
├── public/                  # Static assets
│   ├── icons/               # App icons
│   └── images/              # Images
├── index.html               # HTML template
├── vite.config.ts           # Vite configuration
├── tailwind.config.js       # Tailwind CSS configuration
├── tsconfig.json            # TypeScript configuration
└── package.json             # Dependencies
```

## Key Pages & Routes

### Public Routes
- `/login` - User login
- `/register` - User registration
- `/forgot-password` - Password reset

### Onboarding Routes
- `/onboarding` - Multi-step onboarding wizard (15 steps)
- `/onboarding/bakery-type-selection` - Choose bakery type
- `/onboarding/setup` - Basic bakery setup
- `/onboarding/poi-detection` - **POI Detection** - Automatic location context detection
- `/onboarding/upload-sales-data` - Upload historical sales
- `/onboarding/inventory-review` - Review detected products
- `/onboarding/initial-stock-entry` - Initial inventory levels
- `/onboarding/product-categorization` - Product categories
- `/onboarding/suppliers-setup` - Supplier configuration
- `/onboarding/recipes-setup` - Recipe management
- `/onboarding/ml-training` - AI model training
- `/onboarding/setup-review` - Review configuration
- `/onboarding/completion` - Onboarding complete

### Protected Routes (Require Authentication)
- `/dashboard` - Main operational dashboard
- `/forecasting` - Demand forecasting management
- `/forecasting/train` - ML model training
- `/inventory` - Inventory management
- `/inventory/stock` - Stock levels and movements
- `/production` - Production planning
- `/production/batches` - Production batch tracking
- `/production/quality` - Quality control
- `/recipes` - Recipe management
- `/orders` - Customer order management
- `/suppliers` - Supplier management
- `/procurement` - Procurement planning
- `/sales` - Sales analytics
- `/pos` - POS integration settings
- `/settings` - User and tenant settings
- `/settings/team` - Team member management
- `/settings/subscription` - Subscription management

## API Integration

### Authentication Flow
1. **Login**: User enters credentials → API returns access token + refresh token
2. **Token Storage**: Tokens stored in Zustand store + localStorage
3. **Request Interceptor**: Axios interceptor adds `Authorization: Bearer {token}` to all requests
4. **Token Refresh**: On 401 error, automatically refresh token and retry request
5. **Logout**: Clear tokens and redirect to login

### TanStack Query Configuration
```typescript
// Automatic background refetching
refetchOnWindowFocus: true
refetchOnReconnect: true

// Stale-while-revalidate caching
staleTime: 5 minutes
cacheTime: 30 minutes

// Retry on failure
retry: 3
retryDelay: exponential backoff
```

### API Client Structure
```typescript
// Base client
const apiClient = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 30000,
})

// Request interceptor (add JWT)
apiClient.interceptors.request.use((config) => {
  const token = authStore.getState().accessToken
  config.headers.Authorization = `Bearer ${token}`
  return config
})

// Response interceptor (handle token refresh)
apiClient.interceptors.response.use(
  (response) => response,
  async (error) => {
    if (error.response?.status === 401) {
      await refreshToken()
      return apiClient.request(error.config)
    }
    throw error
  }
)
```

## Real-Time Features

### Server-Sent Events (SSE) for Alerts
```typescript
const useAlertStream = () => {
  useEffect(() => {
    const eventSource = new EventSource(
      `${API_URL}/api/v1/alerts/stream`,
      { withCredentials: true }
    )

    eventSource.onmessage = (event) => {
      const alert = JSON.parse(event.data)
      alertStore.addAlert(alert)
      toast.notification(alert.message)
    }

    eventSource.onerror = () => {
      // Auto-reconnect on error
      setTimeout(() => eventSource.close(), 5000)
    }

    return () => eventSource.close()
  }, [])
}
```

### WebSocket for Training Progress
```typescript
const useTrainingWebSocket = (trainingId: string) => {
  const { lastMessage, readyState } = useWebSocket(
    `${WS_URL}/api/v1/training/ws?training_id=${trainingId}`
  )

  useEffect(() => {
    if (lastMessage) {
      const progress = JSON.parse(lastMessage.data)
      updateTrainingProgress(progress)
    }
  }, [lastMessage])
}
```

## Configuration

### Environment Variables

**API Configuration:**
- `VITE_API_URL` - Backend API gateway URL (e.g., `https://api.bakery-ia.com`)
- `VITE_WS_URL` - WebSocket URL (e.g., `wss://api.bakery-ia.com`)

**Feature Flags:**
- `VITE_ENABLE_DEMO_MODE` - Enable demo mode features (default: false)
- `VITE_ENABLE_ANALYTICS` - Enable analytics tracking (default: true)

**External Services:**
- `VITE_STRIPE_PUBLIC_KEY` - Stripe publishable key for payments
- `VITE_SENTRY_DSN` - Sentry error tracking DSN (optional)

**Build Configuration:**
- `VITE_APP_VERSION` - Application version (from package.json)
- `VITE_BUILD_TIME` - Build timestamp

### Example .env file
```env
VITE_API_URL=http://localhost:8000
VITE_WS_URL=ws://localhost:8000
VITE_ENABLE_DEMO_MODE=true
VITE_STRIPE_PUBLIC_KEY=pk_test_...
```

## Development Setup

### Prerequisites
- Node.js 18+ and npm/yarn/pnpm
- Access to Bakery-IA backend API

### Local Development
```bash
# Install dependencies
cd frontend
npm install

# Set environment variables
cp .env.example .env
# Edit .env with your configuration

# Run development server
npm run dev

# Open browser to http://localhost:5173
```

### Build for Production
```bash
# Create optimized production build
npm run build

# Preview production build locally
npm run preview
```

### Code Quality
```bash
# Run linter
npm run lint

# Run type checking
npm run type-check

# Format code
npm run format
```

## Testing

### Unit Tests (Vitest)
```bash
# Run unit tests
npm run test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch
```

### E2E Tests (Playwright - planned)
```bash
# Run E2E tests
npm run test:e2e

# Run E2E tests in headed mode
npm run test:e2e:headed
```

## Performance Optimization

### Build Optimization
- **Code Splitting** - Lazy load routes for faster initial load
- **Tree Shaking** - Remove unused code from bundles
- **Minification** - Minify JavaScript and CSS
- **Gzip Compression** - Compress assets for faster transfer
- **Image Optimization** - Optimized image formats and sizes

### Runtime Optimization
- **React.memo** - Prevent unnecessary re-renders
- **useMemo/useCallback** - Memoize expensive computations
- **Virtual Scrolling** - Efficiently render large lists
- **Debouncing** - Limit API calls from user input
- **Lazy Loading** - Load components and routes on demand

### Caching Strategy
- **TanStack Query Cache** - 5-minute stale time for most queries
- **Service Worker** (planned) - Offline-first PWA support
- **Asset Caching** - Browser cache for static assets
- **API Response Cache** - Cache GET requests in TanStack Query

## Accessibility (a11y)

### WCAG 2.1 AA Compliance
- **Keyboard Navigation** - All features accessible via keyboard
- **Screen Reader Support** - ARIA labels and semantic HTML
- **Color Contrast** - 4.5:1 contrast ratio for text
- **Focus Indicators** - Visible focus states for interactive elements
- **Alt Text** - Descriptive alt text for images
- **Form Labels** - Proper label associations for inputs

### Radix UI Accessibility
- Built-in keyboard navigation
- ARIA attributes automatically applied
- Focus management
- Screen reader announcements

## Security Measures

### Authentication & Authorization
- **JWT Tokens** - Secure token-based authentication
- **Automatic Token Refresh** - Seamless token renewal
- **HttpOnly Cookies** (planned) - More secure token storage
- **CSRF Protection** - CSRF tokens for state-changing operations

### Data Protection
- **HTTPS Only** (Production) - All communication encrypted
- **XSS Prevention** - React's built-in XSS protection
- **Content Security Policy** - Restrict resource loading
- **Input Sanitization** - Validate and sanitize all user inputs

### Dependency Security
- **npm audit** - Regular security audits
- **Dependabot** - Automatic dependency updates
- **License Scanning** - Ensure license compliance

## Deployment

### Docker Deployment
```dockerfile
# Multi-stage build
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
```

### Kubernetes Deployment
- **Deployment** - Multiple replicas for high availability
- **Service** - Load balancing across pods
- **Ingress** - HTTPS termination and routing
- **ConfigMap** - Environment-specific configuration
- **HPA** - Horizontal pod autoscaling based on CPU

### CI/CD Pipeline
1. **Lint & Type Check** - Ensure code quality
2. **Unit Tests** - Run test suite
3. **Build** - Create production build
4. **Docker Build** - Create container image
5. **Push to Registry** - Push to container registry
6. **Deploy to Kubernetes** - Update deployment

## Browser Support

- **Chrome** - Latest 2 versions
- **Firefox** - Latest 2 versions
- **Safari** - Latest 2 versions
- **Edge** - Latest 2 versions
- **Mobile Browsers** - iOS Safari 14+, Chrome Android 90+

## Competitive Advantages

1. **Modern Tech Stack** - React 18, TypeScript, Vite for fast development
2. **Real-Time Updates** - SSE and WebSocket for instant feedback
3. **Mobile-First** - Responsive design works on all devices
4. **Offline Support** (planned) - PWA capabilities for unreliable networks
5. **Accessible** - WCAG 2.1 AA compliant for inclusive access
6. **Fast Performance** - Code splitting and caching for sub-second loads
7. **Spanish-First** - UI designed for Spanish bakery workflows

## Future Enhancements

- **Progressive Web App (PWA)** - Offline support and installable
- **Dark Mode** - User-selectable theme
- **Mobile Apps** - React Native iOS/Android apps
- **Advanced Analytics** - Custom dashboard builder
- **Multi-Language** - Support for additional languages
- **Voice Commands** - Hands-free operation in production environment
- **Barcode Scanning** - Native camera integration for inventory
- **Print Templates** - Custom print layouts for labels and reports

---

**For VUE Madrid Business Plan**: The Bakery-IA Frontend Dashboard represents a modern, professional SaaS interface built with industry-leading technologies. The real-time capabilities, mobile-first design, and accessibility compliance make it suitable for bakeries of all sizes, from small artisanal shops to multi-location enterprises. The intuitive interface reduces training costs and increases user adoption, critical factors for successful SaaS businesses in the Spanish market.
