# EasyStream Design System & Accessibility Guide

## Overview

This guide covers the comprehensive design system, accessibility improvements, PWA enhancements, and responsive design updates for EasyStream v2.0.

## Table of Contents

1. [Design System](#design-system)
2. [Accessibility (WCAG 2.1 AA)](#accessibility)
3. [PWA Enhancements](#pwa-enhancements)
4. [Responsive Design](#responsive-design)
5. [Theme System](#theme-system)
6. [Implementation Guide](#implementation-guide)
7. [Testing Checklist](#testing-checklist)

---

## Design System

### New Files Created

- **[f_scripts/shared/design-system.css](f_scripts/shared/design-system.css)** - Complete design token system

### Design Tokens

#### Spacing System
```css
--space-xs: 4px;
--space-sm: 8px;
--space-md: 16px;
--space-lg: 24px;
--space-xl: 32px;
--space-2xl: 48px;
--space-3xl: 64px;
```

#### Typography Scale
```css
--font-size-xs: 0.75rem;    /* 12px */
--font-size-sm: 0.875rem;   /* 14px */
--font-size-md: 1rem;       /* 16px */
--font-size-lg: 1.125rem;   /* 18px */
--font-size-xl: 1.25rem;    /* 20px */
--font-size-2xl: 1.5rem;    /* 24px */
--font-size-3xl: 1.875rem;  /* 30px */
--font-size-4xl: 2.25rem;   /* 36px */
```

#### Color System

**Semantic Colors (Light Theme)**
- `--color-bg-primary`: #ffffff
- `--color-bg-secondary`: #f9fafb
- `--color-text-primary`: #111827
- `--color-text-secondary`: #4b5563

**Semantic Colors (Dark Theme)**
- `--color-bg-primary`: #121212
- `--color-bg-secondary`: #1c1c1c
- `--color-text-primary`: #f0f0f0
- `--color-text-secondary`: #d0d0d0

**Status Colors**
- Success: `--color-success` (#10b981)
- Warning: `--color-warning` (#f59e0b)
- Error: `--color-error` (#ef4444)
- Info: `--color-info` (#3b82f6)

#### Border Radius
```css
--border-radius-sm: 4px;
--border-radius-md: 8px;
--border-radius-lg: 12px;
--border-radius-xl: 16px;
--border-radius-full: 9999px;
```

#### Shadows
```css
--shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.1);
--shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1);
--shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.1);
--shadow-xl: 0 20px 25px rgba(0, 0, 0, 0.1);
```

#### Z-Index Scale
```css
--z-index-dropdown: 1000;
--z-index-sticky: 1020;
--z-index-fixed: 1030;
--z-index-modal-backdrop: 1040;
--z-index-modal: 1050;
--z-index-tooltip: 1070;
```

### Utility Classes

#### Spacing
- `.m-xs`, `.m-sm`, `.m-md`, `.m-lg`, `.m-xl` - Margin utilities
- `.p-xs`, `.p-sm`, `.p-md`, `.p-lg`, `.p-xl` - Padding utilities

#### Typography
- `.text-xs`, `.text-sm`, `.text-md`, `.text-lg`, `.text-xl` - Font sizes
- `.font-light`, `.font-normal`, `.font-medium`, `.font-bold` - Font weights

#### Layout
- `.rounded-sm`, `.rounded-md`, `.rounded-lg`, `.rounded-full` - Border radius
- `.shadow-sm`, `.shadow-md`, `.shadow-lg` - Box shadows

---

## Accessibility

### New Files Created

- **[f_scripts/shared/accessibility.css](f_scripts/shared/accessibility.css)** - WCAG 2.1 AA compliance styles

### Key Features

#### 1. Focus Indicators (WCAG 2.4.7)
✅ **Implementation:**
- All interactive elements have visible 3px focus rings
- Focus rings use high contrast color (`--focus-ring-color`)
- 2px offset for better visibility

```css
*:focus-visible {
  outline: 3px solid var(--focus-ring-color);
  outline-offset: 2px;
}
```

#### 2. Color Contrast (WCAG 1.4.3)
✅ **Implementation:**
- Minimum 4.5:1 contrast ratio for normal text
- Minimum 3:1 for large text (18pt+)
- All theme colors tested for compliance

#### 3. Touch Targets (WCAG 2.5.5)
✅ **Implementation:**
- Minimum 44x44px touch targets on mobile
- Adequate spacing between interactive elements

```css
button, a, .btn {
  min-height: 44px;
  min-width: 44px;
}
```

#### 4. Skip Links (WCAG 2.4.1)
✅ **Implementation:**
- Skip to main content link
- Visible on keyboard focus
- Hidden by default

```html
<a href="#main-content" class="skip-to-content">Skip to main content</a>
```

#### 5. Screen Reader Support
✅ **Implementation:**
- `.sr-only` class for screen reader only text
- Proper ARIA labels on all interactive elements
- Semantic HTML structure

#### 6. Keyboard Navigation (WCAG 2.1.1)
✅ **Implementation:**
- All functionality accessible via keyboard
- Logical tab order
- Focus management in modals

#### 7. Reduced Motion (WCAG 2.3.3)
✅ **Implementation:**
- Respects `prefers-reduced-motion` preference
- Disables animations for users who prefer reduced motion

```css
@media (prefers-reduced-motion: reduce) {
  * {
    animation-duration: 0.01ms !important;
    transition-duration: 0.01ms !important;
  }
}
```

#### 8. High Contrast Mode (WCAG 1.4.6)
✅ **Implementation:**
- Enhanced borders and focus rings in high contrast mode
- Supports `prefers-contrast: high`

#### 9. Form Accessibility
✅ **Implementation:**
- All inputs have associated labels
- Error messages linked with `aria-describedby`
- Required fields clearly marked

#### 10. Responsive Typography (WCAG 1.4.8)
✅ **Implementation:**
- Text can be resized up to 200%
- Line height of 1.5 for body text
- Optimal line length (max 80ch)

---

## PWA Enhancements

### Enhanced Service Worker

**File:** [sw.js](sw.js)

#### New Features

1. **Multiple Cache Strategies**
   - Network-first: HTML pages
   - Cache-first: Images, fonts
   - Stale-while-revalidate: CSS, JS

2. **Offline Support**
   - Custom offline page
   - Cached assets available offline
   - Graceful degradation

3. **Cache Management**
   - Automatic cache size limiting
   - Old cache cleanup on activation
   - Separate caches for different asset types

4. **Background Sync**
   - Sync watch history when back online
   - Queue failed requests

5. **Push Notifications**
   - Support for push notifications
   - Notification click handling

### Enhanced Manifest

**File:** [manifest.json](manifest.json)

#### New Features

1. **App Shortcuts**
   - Home, Trending, Subscriptions, Upload
   - Quick access from home screen

2. **Share Target**
   - Receive shared videos/images
   - Integration with OS share sheet

3. **Protocol Handler**
   - Handle `web+easystream://` URLs
   - Deep linking support

4. **Display Modes**
   - Window controls overlay
   - Standalone mode
   - Minimal UI fallback

5. **Screenshots & Metadata**
   - App store listing images
   - Enhanced discoverability

---

## Responsive Design

### New Files Created

- **[f_scripts/shared/responsive.css](f_scripts/shared/responsive.css)** - Mobile-first responsive system

### Breakpoint System

```css
--breakpoint-sm: 640px;   /* Tablet */
--breakpoint-md: 768px;   /* Desktop */
--breakpoint-lg: 1024px;  /* Large Desktop */
--breakpoint-xl: 1280px;  /* Extra Large */
--breakpoint-2xl: 1536px; /* 2X Large */
```

### Container System

```css
.container {
  width: 100%;
  max-width: var(--container-xl);
  margin: 0 auto;
  padding: 0 var(--space-md);
}
```

### Grid System

#### Auto-responsive Grid
```html
<div class="grid grid-auto">
  <!-- Auto-fits columns based on min 250px width -->
</div>
```

#### Responsive Grid Columns
```html
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4">
  <!-- 1 col mobile, 2 tablet, 3 desktop, 4 large -->
</div>
```

### Video Grid

Automatically responsive based on screen size:
- Mobile: 1 column
- Tablet: 2 columns
- Desktop: 3-4 columns
- Large: 5-6 columns

```html
<div class="video-grid">
  <!-- Video thumbnails auto-arrange -->
</div>
```

### Flexbox Utilities

```html
<div class="flex justify-between items-center gap-md">
  <!-- Flexible layouts -->
</div>
```

### Display Utilities

```html
<!-- Hide on mobile, show on desktop -->
<div class="xs:hidden md:block">...</div>

<!-- Show on mobile, hide on desktop -->
<div class="xs:block md:hidden">...</div>
```

### Touch Optimizations

- Larger touch targets on mobile (44x44px minimum)
- Increased spacing between interactive elements
- Touch-friendly navigation

### Safe Area Support

Automatically adjusts for iPhone X+ notches and safe areas:

```css
@supports (padding: env(safe-area-inset-left)) {
  .safe-area-padding {
    padding-left: env(safe-area-inset-left);
    padding-right: env(safe-area-inset-right);
  }
}
```

---

## Theme System

### New Files Created

- **[f_scripts/shared/theme-switcher.js](f_scripts/shared/theme-switcher.js)** - Advanced theme switching

### Features

#### 1. System Preference Detection
Automatically detects and respects user's OS dark/light mode preference:

```javascript
const themeSwitcher = new ThemeSwitcher({
  detectSystemPreference: true
});
```

#### 2. Smooth Transitions
Animated theme transitions with configurable duration:

```javascript
themeSwitcher.applyTheme('dark', 'blue', true); // With animation
```

#### 3. Multiple Color Themes
7 color options available:
- Blue (default)
- Red
- Cyan
- Green
- Orange
- Pink
- Purple

Each available in light and dark mode.

#### 4. Persistent Storage
Theme preferences saved to localStorage and restored on page load.

#### 5. Meta Theme Color
Automatically updates mobile browser theme color:

```html
<meta name="theme-color" content="#06a2cb">
```

#### 6. Event System
Listen for theme changes:

```javascript
document.addEventListener('easystream:theme-change', (e) => {
  console.log('Theme changed to:', e.detail.mode, e.detail.color);
});
```

### Usage

#### Basic Initialization

```javascript
// Auto-initializes on page load
window.themeSwitcher.toggleMode(); // Toggle light/dark
window.themeSwitcher.setColor('red'); // Change color
```

#### Creating Theme Picker UI

```javascript
const picker = ThemeSwitcher.createThemePicker();
document.getElementById('theme-container').appendChild(picker);
```

#### HTML Controls

```html
<!-- Theme toggle button -->
<button id="theme-toggle" aria-label="Toggle theme">
  <i class="icon-moon"></i>
</button>

<!-- Color picker buttons -->
<button data-color-theme="blue" aria-label="Blue theme">Blue</button>
<button data-color-theme="red" aria-label="Red theme">Red</button>
```

---

## Implementation Guide

### Step 1: Include New CSS Files

Add to your HTML `<head>` section:

```html
<!-- Design System -->
<link rel="stylesheet" href="/f_scripts/shared/design-system.css">

<!-- Accessibility -->
<link rel="stylesheet" href="/f_scripts/shared/accessibility.css">

<!-- Responsive Design -->
<link rel="stylesheet" href="/f_scripts/shared/responsive.css">

<!-- Existing Themes -->
<link rel="stylesheet" href="/f_scripts/shared/themes.css">
```

### Step 2: Include Theme Switcher

Add before closing `</body>` tag:

```html
<script src="/f_scripts/shared/theme-switcher.js"></script>
```

### Step 3: Add Skip Links

Add at the very beginning of `<body>`:

```html
<div class="skip-links">
  <a href="#main-content" class="skip-to-content">Skip to main content</a>
  <a href="#navigation" class="skip-to-content">Skip to navigation</a>
</div>
```

### Step 4: Update Service Worker Registration

The service worker is already registered in [index.js](index.js:1), but ensure you're using the latest version by clearing browser cache.

### Step 5: Add Main Content ID

Ensure your main content area has an ID for skip links:

```html
<main id="main-content" role="main">
  <!-- Your content -->
</main>
```

### Step 6: Use Utility Classes

Start using the new utility classes in your templates:

```html
<!-- Before -->
<div style="padding: 16px; margin-bottom: 24px;">
  <h2 style="font-size: 24px;">Title</h2>
</div>

<!-- After -->
<div class="p-md m-b-lg">
  <h2 class="text-2xl">Title</h2>
</div>
```

### Step 7: Use Responsive Grid

Update video grids to use the new responsive system:

```html
<!-- Before -->
<div class="thumbs-wrapper">
  <!-- Videos -->
</div>

<!-- After -->
<div class="video-grid">
  <!-- Videos auto-arrange responsively -->
</div>
```

---

## Testing Checklist

### Accessibility Testing

#### Keyboard Navigation
- [ ] All interactive elements focusable
- [ ] Focus indicators visible (3px outline)
- [ ] Tab order is logical
- [ ] No keyboard traps
- [ ] Skip links work
- [ ] Modal focus management works

#### Screen Reader Testing
- [ ] Test with NVDA (Windows)
- [ ] Test with JAWS (Windows)
- [ ] Test with VoiceOver (macOS/iOS)
- [ ] Test with TalkBack (Android)
- [ ] All images have alt text
- [ ] ARIA labels present
- [ ] Headings hierarchy correct

#### Color Contrast
- [ ] Use WebAIM Contrast Checker
- [ ] Test all theme combinations
- [ ] Test light mode: 4.5:1 minimum
- [ ] Test dark mode: 4.5:1 minimum
- [ ] Test focus indicators: 3:1 minimum

#### Touch Targets
- [ ] Minimum 44x44px on mobile
- [ ] Test on actual mobile device
- [ ] Adequate spacing between targets

#### Forms
- [ ] All inputs have labels
- [ ] Error messages associated
- [ ] Required fields marked
- [ ] Validation messages clear

### Responsive Testing

#### Breakpoints
- [ ] Mobile (320px - 639px)
- [ ] Tablet (640px - 767px)
- [ ] Desktop (768px - 1023px)
- [ ] Large (1024px - 1279px)
- [ ] XL (1280px+)

#### Devices
- [ ] iPhone SE (375px)
- [ ] iPhone 12 Pro (390px)
- [ ] iPad (768px)
- [ ] iPad Pro (1024px)
- [ ] Desktop (1920px)

#### Orientations
- [ ] Portrait mode
- [ ] Landscape mode
- [ ] Fullscreen video in landscape

#### Safe Areas
- [ ] iPhone X+ notch
- [ ] Bottom safe area
- [ ] Left/right safe areas

### PWA Testing

#### Installation
- [ ] Can install from Chrome (desktop)
- [ ] Can install from Edge (desktop)
- [ ] Can install from Safari (iOS)
- [ ] Can install from Chrome (Android)
- [ ] App shortcuts work
- [ ] Icon displays correctly

#### Offline Support
- [ ] Offline page displays
- [ ] Cached assets load
- [ ] Graceful degradation
- [ ] Back online detection

#### Service Worker
- [ ] SW installs correctly
- [ ] Cache strategies work
- [ ] Old caches cleaned up
- [ ] Background sync works

#### Notifications
- [ ] Push notifications work
- [ ] Notification click works
- [ ] Permissions requested properly

### Theme Testing

#### Theme Switching
- [ ] Light/dark toggle works
- [ ] Smooth transitions
- [ ] All 7 colors work
- [ ] Preferences persist
- [ ] System preference detection

#### Appearance
- [ ] Meta theme color updates
- [ ] Logo changes with theme
- [ ] All components themed
- [ ] Video player themed

### Performance Testing

#### Lighthouse Scores
- [ ] Performance: 90+
- [ ] Accessibility: 100
- [ ] Best Practices: 95+
- [ ] SEO: 95+
- [ ] PWA: Pass all checks

#### Core Web Vitals
- [ ] LCP < 2.5s
- [ ] FID < 100ms
- [ ] CLS < 0.1

#### Bundle Size
- [ ] design-system.css: ~15KB
- [ ] accessibility.css: ~8KB
- [ ] responsive.css: ~12KB
- [ ] theme-switcher.js: ~10KB

### Browser Testing

#### Desktop Browsers
- [ ] Chrome (latest)
- [ ] Firefox (latest)
- [ ] Safari (latest)
- [ ] Edge (latest)

#### Mobile Browsers
- [ ] Chrome Mobile
- [ ] Safari iOS
- [ ] Firefox Mobile
- [ ] Samsung Internet

### Reduced Motion Testing
- [ ] Enable "Reduce motion" in OS
- [ ] Animations disabled
- [ ] Transitions instant
- [ ] Scroll behavior auto

### High Contrast Testing
- [ ] Enable High Contrast Mode
- [ ] Borders enhanced
- [ ] Focus rings thicker
- [ ] Text readable

---

## Browser Support

### Minimum Supported Versions

- **Chrome/Edge:** Last 2 versions
- **Firefox:** Last 2 versions
- **Safari:** Last 2 versions
- **iOS Safari:** 12+
- **Chrome Android:** Last 2 versions

### Progressive Enhancement

Features that gracefully degrade:
- Service Worker (requires HTTPS)
- CSS Grid (fallback to Flexbox)
- CSS Custom Properties (fallback values)
- Container Queries (graceful degradation)

---

## Performance Considerations

### CSS Loading Strategy

1. Load critical design system first
2. Load accessibility styles inline
3. Defer non-critical styles
4. Use media queries to load responsive styles conditionally

### JavaScript Loading

- Theme switcher loads after DOMContentLoaded
- Service worker registers asynchronously
- No blocking scripts

### Image Optimization

- Use WebP with fallbacks
- Lazy load images below fold
- Responsive images with srcset
- Proper sizing to prevent CLS

---

## Maintenance

### Adding New Components

1. Use design tokens from design-system.css
2. Follow accessibility guidelines
3. Test responsiveness at all breakpoints
4. Ensure theme compatibility

### Updating Themes

1. Update CSS variables in themes.css
2. Test all color combinations
3. Verify contrast ratios
4. Update theme-switcher.js if adding new colors

### Service Worker Updates

1. Increment CACHE_VERSION in sw.js
2. Update PRECACHE array if needed
3. Test cache strategies
4. Clear old caches

---

## Resources

### Tools

- **Accessibility Testing:**
  - [WAVE Browser Extension](https://wave.webaim.org/extension/)
  - [axe DevTools](https://www.deque.com/axe/devtools/)
  - [Lighthouse](https://developers.google.com/web/tools/lighthouse)

- **Contrast Checking:**
  - [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/)
  - [Contrast Ratio Tool](https://contrast-ratio.com/)

- **Screen Readers:**
  - [NVDA (Free)](https://www.nvaccess.org/download/)
  - [VoiceOver (Built into macOS/iOS)](https://www.apple.com/accessibility/voiceover/)

- **PWA Testing:**
  - [PWA Builder](https://www.pwabuilder.com/)
  - [Lighthouse PWA Audit](https://web.dev/pwa-checklist/)

### Documentation

- [WCAG 2.1 Guidelines](https://www.w3.org/WAI/WCAG21/quickref/)
- [MDN Web Docs - Accessibility](https://developer.mozilla.org/en-US/docs/Web/Accessibility)
- [Web.dev - PWA](https://web.dev/progressive-web-apps/)
- [Can I Use](https://caniuse.com/) - Browser compatibility

---

## Support

For questions or issues:
1. Check the testing checklist
2. Review browser console for errors
3. Use browser DevTools for debugging
4. File issues on GitHub

---

## License

Same as EasyStream main project.
