# Badge Component

Status badges for translation states and language indicators with multiple variants and interactive features.

## Installation

```javascript
import Badge from './components/Badge.js';
```

## Basic Usage

```javascript
// Create a simple badge
const badge = new Badge({
    text: 'Translated',
    variant: 'success'
});

// Append to DOM
document.getElementById('container').appendChild(badge.getElement());
```

## API Reference

### Constructor Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `text` | `string` | `''` | Badge text content |
| `variant` | `string` | `'default'` | Badge color variant |
| `size` | `string` | `'medium'` | Badge size |
| `icon` | `string` | `null` | Dashicons class (e.g., 'dashicons-yes') |
| `pill` | `boolean` | `false` | Use fully rounded pill style |
| `dot` | `boolean` | `false` | Show colored dot indicator |
| `removable` | `boolean` | `false` | Show remove button (X) |
| `onRemove` | `Function` | `null` | Callback when remove button clicked |
| `tooltip` | `string` | `null` | Tooltip text on hover |

### Variants

| Variant | Color | Use Cases |
|---------|-------|-----------|
| `default` | Gray | Original content, neutral states |
| `primary` | Blue | Primary actions, featured items |
| `success` | Green | Translated, active, completed |
| `warning` | Yellow | Needs update, pending, caution |
| `danger` | Red | Failed, error, critical |
| `info` | Cyan | Draft, informational, tips |

### Sizes

| Size | Description |
|------|-------------|
| `small` | Compact badges for dense layouts |
| `medium` | Default size for most use cases |
| `large` | Prominent badges for emphasis |

## Examples

### Basic Variants

```javascript
// Default (gray)
const defaultBadge = new Badge({
    text: 'Original',
    variant: 'default'
});

// Primary (blue)
const primaryBadge = new Badge({
    text: 'Featured',
    variant: 'primary'
});

// Success (green)
const successBadge = new Badge({
    text: 'Translated',
    variant: 'success'
});

// Warning (yellow)
const warningBadge = new Badge({
    text: 'Pending',
    variant: 'warning'
});

// Danger (red)
const dangerBadge = new Badge({
    text: 'Failed',
    variant: 'danger'
});

// Info (cyan)
const infoBadge = new Badge({
    text: 'Draft',
    variant: 'info'
});
```

### Sizes

```javascript
// Small badge
const smallBadge = new Badge({
    text: 'New',
    variant: 'primary',
    size: 'small'
});

// Medium badge (default)
const mediumBadge = new Badge({
    text: 'Active',
    variant: 'success',
    size: 'medium'
});

// Large badge
const largeBadge = new Badge({
    text: 'Featured',
    variant: 'primary',
    size: 'large'
});
```

### With Icons

```javascript
// Badge with icon
const iconBadge = new Badge({
    text: 'Completed',
    variant: 'success',
    icon: 'dashicons-yes-alt'
});

// Icon-only badge
const iconOnlyBadge = new Badge({
    text: '',
    variant: 'info',
    icon: 'dashicons-info',
    tooltip: 'More information'
});
```

### Pill Style

```javascript
// Pill-shaped badge
const pillBadge = new Badge({
    text: 'Active',
    variant: 'success',
    pill: true
});
```

### With Dot Indicator

```javascript
// Badge with colored dot
const dotBadge = new Badge({
    text: 'Online',
    variant: 'success',
    dot: true
});

// Dot + icon
const dotIconBadge = new Badge({
    text: 'Processing',
    variant: 'warning',
    dot: true,
    icon: 'dashicons-clock'
});
```

### Removable Badges

```javascript
// Badge with remove button
const removableBadge = new Badge({
    text: 'Spanish',
    variant: 'primary',
    removable: true,
    onRemove: (badge) => {
        console.log('Badge removed:', badge.options.text);
        badge.destroy();
    }
});

// Tag-style removable badge
const tagBadge = new Badge({
    text: 'Translation',
    variant: 'default',
    pill: true,
    removable: true,
    onRemove: (badge) => {
        // Animate removal
        badge.getElement().style.opacity = '0';
        setTimeout(() => badge.destroy(), 150);
    }
});
```

### With Tooltips

```javascript
// Badge with tooltip
const tooltipBadge = new Badge({
    text: 'Translated',
    variant: 'success',
    icon: 'dashicons-yes-alt',
    tooltip: 'Translation completed on 2025-01-26'
});
```

### Status Helper Method

```javascript
// Use predefined status configurations
const translatedBadge = Badge.fromStatus('translated');
// → text: 'Translated', variant: 'success', icon: 'dashicons-yes-alt'

const pendingBadge = Badge.fromStatus('pending');
// → text: 'Pending', variant: 'warning', icon: 'dashicons-clock'

const failedBadge = Badge.fromStatus('failed');
// → text: 'Failed', variant: 'danger', icon: 'dashicons-dismiss'

// Override defaults
const customStatusBadge = Badge.fromStatus('translated', {
    size: 'large',
    pill: true
});
```

#### Available Status Presets

| Status | Text | Variant | Icon |
|--------|------|---------|------|
| `translated` | Translated | success | dashicons-yes-alt |
| `active` | Active | success | dashicons-yes |
| `needs_update` | Needs Update | warning | dashicons-update |
| `pending` | Pending | warning | dashicons-clock |
| `failed` | Failed | danger | dashicons-dismiss |
| `error` | Error | danger | dashicons-warning |
| `draft` | Draft | info | dashicons-edit |
| `original` | Original | default | none |

## Methods

### Instance Methods

#### `getElement()`
Returns the badge's DOM element.

```javascript
const badge = new Badge({ text: 'Test' });
const element = badge.getElement();
document.body.appendChild(element);
```

#### `setText(text)`
Updates the badge text.

```javascript
badge.setText('Updated');
```

#### `setVariant(variant)`
Changes the badge variant.

```javascript
badge.setVariant('success');
```

#### `setSize(size)`
Changes the badge size.

```javascript
badge.setSize('large');
```

#### `setTooltip(tooltip)`
Updates or removes the tooltip.

```javascript
badge.setTooltip('New tooltip text');
badge.setTooltip(null); // Remove tooltip
```

#### `destroy()`
Removes the badge from DOM and cleans up event listeners.

```javascript
badge.destroy();
```

### Static Methods

#### `Badge.fromStatus(status, options = {})`
Creates a badge using predefined status configurations.

```javascript
const badge = Badge.fromStatus('translated', { size: 'large' });
```

## Common Use Cases

### Translation Status Indicators

```javascript
const statuses = {
    translated: Badge.fromStatus('translated'),
    pending: Badge.fromStatus('pending'),
    failed: Badge.fromStatus('failed'),
    needs_update: Badge.fromStatus('needs_update')
};

// Render based on translation state
function renderStatus(translationStatus) {
    return statuses[translationStatus] || Badge.fromStatus('original');
}
```

### Language Tags

```javascript
const languages = ['English', 'Spanish', 'French', 'German'];

const languageTags = languages.map(lang => new Badge({
    text: lang,
    variant: 'primary',
    pill: true,
    removable: true,
    onRemove: (badge) => {
        console.log(`Removing language: ${badge.options.text}`);
        badge.destroy();
    }
}));
```

### Count Badges

```javascript
const countBadge = new Badge({
    text: '42',
    variant: 'primary',
    pill: true,
    size: 'small'
});
```

### Feature Tags

```javascript
const featureTags = [
    { text: 'New', variant: 'success' },
    { text: 'Beta', variant: 'warning' },
    { text: 'Deprecated', variant: 'danger' }
].map(tag => new Badge({ ...tag, size: 'small', pill: true }));
```

### Status with Real-time Updates

```javascript
const statusBadge = new Badge({
    text: 'Connecting...',
    variant: 'warning',
    dot: true
});

// Update when connected
function onConnect() {
    statusBadge.setText('Connected');
    statusBadge.setVariant('success');
}

// Update when disconnected
function onDisconnect() {
    statusBadge.setText('Disconnected');
    statusBadge.setVariant('danger');
}
```

## Styling

The badge component is styled using SCSS in `/admin/src/styles/components/_badge.scss`.

### CSS Variables Support

The component uses SCSS variables that can be customized:

```scss
// Color variants
$primary-color: #0073aa;
$success-color: #00a32a;
$warning-color: #f0b849;
$error-color: #d63638;
$info-color: #2271b1;

// Sizes
$badge-font-size-small: 11px;
$badge-font-size-medium: 12px;
$badge-font-size-large: 13px;
```

### Custom Styling

Add custom classes to badge elements:

```javascript
const badge = new Badge({ text: 'Custom' });
badge.getElement().classList.add('my-custom-class');
```

## Accessibility

The Badge component follows accessibility best practices:

- **ARIA Attributes**: Uses `role="status"` and `aria-label` for screen readers
- **Keyboard Navigation**: Remove button is keyboard accessible
- **Focus Indicators**: Clear focus outlines for interactive elements
- **Color Contrast**: Meets WCAG 2.1 AA standards
- **Tooltips**: Properly labeled for assistive technology
- **Reduced Motion**: Respects `prefers-reduced-motion` setting

## Dark Mode Support

The Badge component automatically adapts to dark mode:

- Responds to `prefers-color-scheme: dark` media query
- Supports WordPress admin color schemes (midnight, ectoplasm)
- Adjusted colors maintain readability in dark environments

## Browser Support

- Chrome/Edge: Last 2 versions
- Firefox: Last 2 versions
- Safari: Last 2 versions
- Modern browsers with ES6 support

## Performance Considerations

- Lightweight: Minimal DOM structure
- Efficient event listeners with proper cleanup
- CSS transitions for smooth animations
- No external dependencies

## Migration from Old API

If migrating from the old API that used `error` variant:

```javascript
// Old (still works, but deprecated)
const badge = new Badge({ variant: 'error' });

// New (recommended)
const badge = new Badge({ variant: 'danger' });
```

The `error` variant is automatically mapped to `danger` for backwards compatibility.

## Best Practices

1. **Use semantic variants**: Match variant to meaning (success for completed, danger for errors)
2. **Consistent sizing**: Use same size within a context for visual harmony
3. **Icon usage**: Include icons for common statuses to improve scannability
4. **Tooltip for context**: Add tooltips to provide additional information
5. **Proper cleanup**: Always call `destroy()` when removing badges to prevent memory leaks
6. **Status helper**: Use `fromStatus()` for translation statuses to ensure consistency

## Troubleshooting

### Badge not appearing
Ensure the element is appended to the DOM:
```javascript
const badge = new Badge({ text: 'Test' });
document.getElementById('container').appendChild(badge.getElement());
```

### Icon not showing
Verify dashicons are loaded and class name is correct:
```javascript
// Correct
icon: 'dashicons-yes'

// Incorrect (missing prefix)
icon: 'yes'
```

### Remove callback not firing
Ensure both `removable` and `onRemove` are set:
```javascript
const badge = new Badge({
    text: 'Remove me',
    removable: true,
    onRemove: (badge) => {
        console.log('Removed!');
        badge.destroy();
    }
});
```

### Dark mode not working
Check that parent element has proper color scheme setup and SCSS is compiled correctly.
