# ProgressBar Component - Usage Guide

## Overview

The ProgressBar component is a visual progress indicator for translation jobs and batch operations. It supports multiple states, animated stripes, accessibility features, and both determinate and indeterminate modes.

## Features

- Animated progress bar (0-100%)
- Multiple states: `pending`, `in-progress`, `completed`, `failed`
- Label showing percentage or custom text
- Color coding by status
- Striped animation for active state
- Full accessibility (ARIA attributes)
- Dark mode support
- Responsive design
- Reduced motion support

## Installation

The component is automatically available when the admin panel is built:

```bash
npm run build
```

The compiled JavaScript and CSS will be enqueued in WordPress.

## Basic Usage

### Simple Progress Bar

```javascript
import ProgressBar from './components/ProgressBar';

const progress = new ProgressBar({
    container: '#progress-container',
    value: 0,
    max: 100,
    label: 'Translating posts...'
});

// Update progress
progress.setValue(50);
```

### Using CSS Selector

```javascript
const progress = new ProgressBar({
    container: '#my-progress',  // Can be a selector string
    value: 65,
    status: 'in-progress',
    animated: true
});
```

## API Reference

### Constructor Options

```javascript
new ProgressBar({
    container: HTMLElement|string,  // Required: DOM element or CSS selector
    value: number,                  // Current value (0-100), default: 0
    max: number,                    // Maximum value, default: 100
    label: string,                  // Optional label text
    status: string,                 // 'pending'|'in-progress'|'completed'|'failed'
    variant: string,                // 'default'|'success'|'warning'|'error'
    animated: boolean,              // Enable striped animation, default: false
    indeterminate: boolean,         // Indeterminate mode, default: false
    showLabel: boolean,             // Show label, default: true
    showPercentage: boolean,        // Show percentage text, default: true
    onComplete: function           // Callback when reaching 100%
})
```

### Methods

#### setValue(value, max?)
Set the current progress value.

```javascript
progress.setValue(75);              // Set to 75%
progress.setValue(50, 200);         // Set to 50 out of 200
```

#### setStatus(status)
Update the status (changes color automatically).

```javascript
progress.setStatus('in-progress');  // Blue, with stripes if animated
progress.setStatus('completed');    // Green
progress.setStatus('failed');       // Red
progress.setStatus('pending');      // Gray
```

#### setLabel(label)
Update the label text.

```javascript
progress.setLabel('Processing files...');
```

#### setVariant(variant)
Change the color variant.

```javascript
progress.setVariant('success');     // Green
progress.setVariant('error');       // Red
progress.setVariant('warning');     // Yellow
progress.setVariant('default');     // Blue
```

#### setIndeterminate(enabled)
Toggle indeterminate (loading) mode.

```javascript
progress.setIndeterminate(true);    // Show loading animation
progress.setIndeterminate(false);   // Show normal progress
```

#### increment(amount?)
Increment the progress value.

```javascript
progress.increment();               // +1
progress.increment(10);             // +10
```

#### reset()
Reset progress to zero.

```javascript
progress.reset();
```

#### complete()
Set progress to 100% and trigger completion.

```javascript
progress.complete();
```

#### destroy()
Remove the progress bar from DOM and clean up.

```javascript
progress.destroy();
```

#### getPercentage()
Get current percentage.

```javascript
const percent = progress.getPercentage();  // Returns 0-100
```

#### isCompleted()
Check if progress is complete.

```javascript
if (progress.isCompleted()) {
    console.log('Done!');
}
```

## Status-Based Styling

The component automatically applies color variants based on status:

| Status | Color | Use Case |
|--------|-------|----------|
| `pending` | Gray | Waiting to start |
| `in-progress` | Blue | Currently processing |
| `completed` | Green | Successfully finished |
| `failed` | Red | Error occurred |

## Examples

### Translation Job Progress

```javascript
const translationProgress = new ProgressBar({
    container: '#translation-progress',
    value: 0,
    max: 100,
    label: 'Translating content...',
    status: 'pending',
    animated: true,
    showPercentage: true,
    onComplete: () => {
        console.log('Translation complete!');
        showSuccessMessage();
    }
});

// Start translation
translationProgress.setStatus('in-progress');

// Update as translation progresses
translationProgress.setValue(25);
translationProgress.setValue(50);
translationProgress.setValue(75);

// Complete
translationProgress.setStatus('completed');
translationProgress.complete();
```

### Batch Processing with Error Handling

```javascript
async function processBatch(items) {
    const progress = new ProgressBar({
        container: '#batch-progress',
        value: 0,
        max: items.length,
        status: 'in-progress',
        animated: true,
        label: `Processing ${items.length} items...`
    });

    try {
        for (let i = 0; i < items.length; i++) {
            await processItem(items[i]);
            progress.increment();
            progress.setLabel(`Processing ${i + 1} of ${items.length}...`);
        }

        progress.setStatus('completed');
    } catch (error) {
        progress.setStatus('failed');
        progress.setLabel('Processing failed: ' + error.message);
    }
}
```

### Indeterminate Loading

```javascript
const loader = new ProgressBar({
    container: '#loader',
    indeterminate: true,
    label: 'Loading...',
    showPercentage: false
});

// When data arrives
fetchData().then(() => {
    loader.setIndeterminate(false);
    loader.setValue(0);
    // Start actual progress tracking
});
```

### File Upload Progress

```javascript
const uploadProgress = new ProgressBar({
    container: '#upload-progress',
    value: 0,
    max: 100,
    status: 'in-progress',
    animated: true,
    showPercentage: true
});

const xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', (e) => {
    if (e.lengthComputable) {
        const percent = (e.loaded / e.total) * 100;
        uploadProgress.setValue(percent);
    }
});

xhr.addEventListener('load', () => {
    uploadProgress.setStatus('completed');
    uploadProgress.complete();
});

xhr.addEventListener('error', () => {
    uploadProgress.setStatus('failed');
    uploadProgress.setLabel('Upload failed');
});
```

### Multiple Progress Bars

```javascript
const jobs = [
    { id: 1, title: 'Post Translation' },
    { id: 2, title: 'Page Translation' },
    { id: 3, title: 'Menu Translation' }
];

const progressBars = jobs.map(job => {
    const container = document.createElement('div');
    document.getElementById('jobs-container').appendChild(container);

    return new ProgressBar({
        container: container,
        value: 0,
        label: job.title,
        status: 'pending',
        animated: true
    });
});

// Update individual jobs
progressBars[0].setStatus('in-progress');
progressBars[0].setValue(50);
```

### With Custom Completion Handler

```javascript
const progress = new ProgressBar({
    container: '#custom-progress',
    value: 0,
    status: 'in-progress',
    animated: true,
    onComplete: () => {
        // Custom completion logic
        showConfetti();
        playSound('success.mp3');
        setTimeout(() => {
            progress.destroy();
            showResultsPage();
        }, 2000);
    }
});
```

## Styling Customization

### CSS Variables

You can customize colors by overriding SCSS variables:

```scss
// In your custom SCSS file
$progress-default-bar: #your-color;
$progress-success-bar: #your-color;
$progress-warning-bar: #your-color;
$progress-error-bar: #your-color;
```

### Size Variants

Add size modifier classes in your HTML:

```javascript
// Small progress bar
progress.element.classList.add('mpz-progress-bar--small');

// Large progress bar
progress.element.classList.add('mpz-progress-bar--large');
```

## Accessibility

The component includes full accessibility support:

- `role="progressbar"` for screen readers
- `aria-valuemin`, `aria-valuemax`, `aria-valuenow` for current value
- `aria-valuetext` for human-readable status
- `aria-label` for context
- Respects `prefers-reduced-motion` for animations
- High contrast mode support

## Browser Support

- Modern browsers (Chrome, Firefox, Safari, Edge)
- IE11+ (with polyfills)
- Mobile browsers (iOS Safari, Chrome Mobile)

## Performance Considerations

- Uses `requestAnimationFrame` for smooth updates
- GPU-accelerated animations with `transform: translateZ(0)`
- Efficient DOM updates (only changes necessary elements)
- Automatic cleanup with `destroy()` method

## Troubleshooting

### Progress bar not showing
Ensure the container element exists before creating the ProgressBar:

```javascript
// Wait for DOM ready
document.addEventListener('DOMContentLoaded', () => {
    const progress = new ProgressBar({
        container: '#my-progress'
    });
});
```

### Animations not working
Check that animations are not disabled by user preferences or CSS:

```css
/* Make sure this isn't overriding animations */
@media (prefers-reduced-motion: reduce) {
    /* Animations are intentionally disabled */
}
```

### Percentage not updating
Ensure you're calling `setValue()` with valid numbers:

```javascript
// Wrong
progress.setValue('50');  // String, not number

// Correct
progress.setValue(50);    // Number
```

## Related Components

- **Badge**: For status indicators
- **Spinner**: For simple loading states
- **StatusFeedback**: For operation results

## WordPress Integration

```php
// Enqueue in WordPress
wp_enqueue_script(
    'mpz-progress-bar',
    plugins_url('admin/dist/js/main.js', __FILE__),
    ['wp-i18n'],
    '1.0.0',
    true
);

wp_enqueue_style(
    'mpz-progress-bar',
    plugins_url('admin/dist/css/main.css', __FILE__),
    [],
    '1.0.0'
);
```

## Support

For issues or questions, refer to:
- Component source: `admin/src/components/ProgressBar.js`
- Styles: `admin/src/styles/components/_progress-bar.scss`
- Build system: `admin/README.md`
