# DBIS UI Component Library

## Overview

A comprehensive, framework-agnostic UI component library specification for DBIS, SCB, and FI employee systems. This library provides reusable components, design tokens, and role-based visibility integration for building consistent, accessible, and permission-aware user interfaces.

## Architecture

The component library is organized into four main sections:

1. **Design System** - Foundation tokens, themes, typography, spacing, and breakpoints
2. **Core Components** - Reusable UI components (buttons, inputs, tables, modals, etc.)
3. **Layout Components** - Layout and grid system components
4. **Permission Components** - RBAC-aware wrappers for role-based visibility

## Design System

### Design Tokens

Located in `design-system/design-tokens.json`, provides:
- **Colors**: Primary, secondary, success, warning, error, neutral, and participant-specific colors
- **Typography**: Font families, sizes, weights, line heights, letter spacing
- **Spacing**: Consistent spacing scale (0-64)
- **Shadows**: Elevation system for depth
- **Borders**: Width, radius, and style definitions
- **Z-Index**: Layering system for overlays and modals
- **Transitions**: Duration and easing functions

### Theme Configuration

The `theme-config.ts` provides:
- Light and dark theme support
- Participant-specific themes (DBIS, SCB, FI)
- CSS variable generation for easy theming
- System theme detection

### Typography System

The `typography.ts` defines:
- Font families (sans, mono, serif)
- Typography scales (xs to 6xl)
- Font weights (light to extrabold)
- Helper functions for CSS generation

### Spacing System

The `spacing.ts` provides:
- Consistent spacing scale
- Layout grid configuration (12-column)
- Helper functions for padding/margin

### Breakpoints

The `breakpoints.ts` defines:
- Responsive breakpoints (sm, md, lg, xl, 2xl)
- Device type detection
- Media query helpers
- Responsive value resolution

## Core Components

### Button

Multi-variant button component with role-based action checking.

**Variants**: primary, secondary, tertiary, danger, ghost, link  
**Sizes**: xs, sm, md, lg, xl  
**States**: default, loading, disabled, success, error

**Features**:
- Icon support (left/right positioning)
- Loading states with spinner
- Permission-based visibility
- Full accessibility support

**Usage**:
```typescript
<Button
  label="Create Settlement"
  variant="primary"
  size="md"
  requiredAction="create"
  requiredModule="settlement"
  onClick={handleCreate}
/>
```

### Input

Flexible input component supporting multiple types and validation states.

**Types**: text, number, email, password, search, tel, url, date, datetime-local, time, currency  
**Sizes**: sm, md, lg  
**States**: default, error, success, warning, disabled

**Features**:
- Currency input with locale support
- Left/right icon support
- Clear button
- Validation rules
- Helper text and error messages

**Usage**:
```typescript
<Input
  name="amount"
  label="Amount"
  type="currency"
  currency="USD"
  value={amount}
  onChange={setAmount}
  required
  state={errors.amount ? 'error' : 'default'}
  errorMessage={errors.amount}
/>
```

### Table/DataGrid

Advanced data table with sorting, filtering, pagination, and role-based column visibility.

**Variants**: default, striped, bordered, hoverable  
**Sizes**: sm, md, lg

**Features**:
- Sortable columns
- Filterable columns
- Global search
- Pagination
- Row selection
- Expandable rows
- Role-based column visibility
- Row and bulk actions with permission checking

**Usage**:
```typescript
<Table
  data={settlements}
  columns={columns}
  sortable
  filterable
  paginated
  pagination={{
    page: 1,
    pageSize: 20,
    total: 100
  }}
  rowActions={[
    {
      label: "View",
      action: "view",
      module: "settlement",
      onClick: (row) => viewSettlement(row.id)
    }
  ]}
/>
```

### Modal/Dialog

Modal component for confirmations, forms, and information display.

**Variants**: default, confirmation, form, information, warning, error  
**Sizes**: xs, sm, md, lg, xl, full

**Features**:
- Multiple variants for different use cases
- Form submission support
- Loading states
- Accessibility (ARIA labels, keyboard navigation)
- Overlay click and escape key handling

**Usage**:
```typescript
<Modal
  isOpen={isOpen}
  onClose={handleClose}
  variant="confirmation"
  title="Confirm Action"
  content="Are you sure you want to proceed?"
  confirmLabel="Confirm"
  cancelLabel="Cancel"
  onConfirm={handleConfirm}
/>
```

### Navigation

Comprehensive navigation components: Navbar, Sidebar, Tabs, and Breadcrumbs.

**Features**:
- Role-based item visibility
- Badge/notification support
- User menu integration
- Search functionality
- Collapsible sidebar
- Active state management

**Usage**:
```typescript
<Navbar
  items={navItems}
  logo="/logo.svg"
  userMenu={{
    user: { name: "John Doe", role: "MSC_Officer" },
    menuItems: userMenuItems
  }}
  showSearch
  onSearch={handleSearch}
/>

<Sidebar
  items={sidebarItems}
  collapsed={isCollapsed}
  onToggle={toggleSidebar}
/>
```

### Status Indicators

Badges, Tags, Alerts, and Toasts for status communication.

**Badge Variants**: default, primary, success, warning, error, info  
**Alert Variants**: info, success, warning, error

**Features**:
- Multiple variants for different contexts
- Closable alerts and toasts
- Action buttons
- Toast positioning and duration control

**Usage**:
```typescript
<Badge label="New" variant="success" />
<Alert
  variant="warning"
  title="Attention Required"
  message="Please review the settlement before proceeding"
  closable
/>
```

### Charts

Chart components compatible with Chart.js, D3, and other charting libraries.

**Types**: line, bar, pie, area, scatter, radar, donut

**Features**:
- Multiple chart types
- Light/dark theme support
- Interactive tooltips
- Click and hover events
- Export functionality
- Responsive design

**Usage**:
```typescript
<LineChart
  data={{
    labels: ['Jan', 'Feb', 'Mar', 'Apr'],
    datasets: [{
      label: 'Settlements',
      data: [100, 150, 200, 180],
      borderColor: '#2196F3'
    }]
  }}
  title="Monthly Settlements"
  showLegend
  responsive
/>
```

### Timeline

Timeline component for process steps and activity tracking.

**Variants**: default, compact, detailed  
**Orientations**: vertical, horizontal

**Features**:
- Multiple status types (pending, active, completed, error, skipped)
- Nested timelines
- Item actions
- Click handlers

**Usage**:
```typescript
<Timeline
  items={[
    {
      id: '1',
      title: 'Settlement Initiated',
      status: 'completed',
      timestamp: new Date()
    },
    {
      id: '2',
      title: 'Validation',
      status: 'active'
    }
  ]}
  variant="detailed"
/>
```

## Layout Components

### Container

Flexible container component with size variants.

**Sizes**: sm, md, lg, xl, full, fluid

**Usage**:
```typescript
<Container size="lg" padding>
  <Content />
</Container>
```

### Grid

12-column grid system with responsive breakpoints.

**Usage**:
```typescript
<Grid columns={12} gap={4}>
  <GridItem colSpan={8}>
    <MainContent />
  </GridItem>
  <GridItem colSpan={4}>
    <Sidebar />
  </GridItem>
</Grid>
```

## Permission Components

### PermissionGate

Wrapper component that checks RBAC permissions before rendering children.

**Features**:
- Action and module permission checking
- Screen-level access checking
- Fallback component support
- Loading state handling

**Usage**:
```typescript
<PermissionGate
  action="create"
  module="settlement"
  employeeId={employeeId}
  fallback={<Alert variant="warning" message="You don't have permission" />}
>
  <CreateSettlementForm />
</PermissionGate>
```

### ScreenVisibility

Wrapper for screen-level visibility based on RBAC.

**Usage**:
```typescript
<ScreenVisibility
  screen="settlement"
  employeeId={employeeId}
  fallback={<AccessDeniedScreen />}
>
  <SettlementDashboard />
</ScreenVisibility>
```

## Role-Based Visibility

All components support role-based visibility through:

1. **Component Props**: `visibleForRoles`, `hiddenForRoles`, `requiredAction`, `requiredModule`
2. **Permission Wrappers**: `PermissionGate` and `ScreenVisibility` components
3. **RBAC Integration**: Automatic integration with the permission schema

Components automatically check permissions and hide/show based on:
- Employee role
- Participant type (DBIS, SCB, FI)
- Required actions
- Required modules
- Screen access

## Accessibility

All components follow WCAG 2.1 AA standards:

- **Keyboard Navigation**: Full keyboard support
- **ARIA Labels**: Proper labeling for screen readers
- **Focus Management**: Visible focus indicators
- **Color Contrast**: Meets WCAG contrast requirements
- **Semantic HTML**: Proper HTML structure

## Framework Implementation

This library is framework-agnostic. To implement in your framework:

### React

```typescript
// Example Button component
import { ButtonProps } from './button.component';

export const Button: React.FC<ButtonProps> = ({ label, onClick, ...props }) => {
  // Implementation
};
```

### Vue

```typescript
// Example Button component
import { ButtonProps } from './button.component';

export default defineComponent({
  props: {
    ...ButtonProps
  },
  setup(props, { emit }) {
    // Implementation
  }
});
```

### Angular

```typescript
// Example Button component
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { ButtonProps } from './button.component';

@Component({
  selector: 'app-button',
  template: `...`
})
export class ButtonComponent implements ButtonProps {
  // Implementation
}
```

## Design Tokens Usage

### CSS Variables

The theme system generates CSS variables that can be used in styles:

```css
.button {
  background-color: var(--theme-participant-primary);
  color: var(--theme-text-inverse);
  padding: var(--spacing-4);
}
```

### JavaScript/TypeScript

```typescript
import { spacingScale } from './design-system/spacing';
import { typographyConfig } from './design-system/typography';

const padding = spacingScale['4']; // '1rem'
const fontSize = typographyConfig.scales.base.fontSize; // '1rem'
```

## Responsive Design

All components support responsive design through:

1. **Breakpoints**: Use `BreakpointService` for responsive logic
2. **Grid System**: Responsive column spans
3. **Spacing**: Responsive spacing utilities
4. **Typography**: Responsive font sizes

## Best Practices

1. **Use Design Tokens**: Always use design tokens instead of hardcoded values
2. **Check Permissions**: Use `PermissionGate` for action-based visibility
3. **Accessibility First**: Ensure all components are accessible
4. **Consistent Styling**: Use theme variables for consistent theming
5. **Responsive Design**: Test components at all breakpoints
6. **Error Handling**: Provide proper error states and messages
7. **Loading States**: Show loading indicators for async operations

## Component Catalog

### Core Components
- ✅ Button
- ✅ Input
- ✅ Table/DataGrid
- ✅ Modal/Dialog
- ✅ Navigation (Navbar, Sidebar, Tabs, Breadcrumbs)
- ✅ Status Indicators (Badge, Tag, Alert, Toast)
- ✅ Charts
- ✅ Timeline

### Layout Components
- ✅ Container
- ✅ Grid

### Permission Components
- ✅ PermissionGate
- ✅ ScreenVisibility

## Integration with Permission Schema

The component library fully integrates with the RBAC permission schema:

- Components automatically check permissions
- Role-based column visibility in tables
- Action-based button visibility
- Screen-level access control
- Participant-specific theming

## Future Enhancements

- Additional chart types
- Form builder component
- Rich text editor
- Date/Time picker components
- File upload component
- Drag and drop support
- Virtual scrolling for large lists
- Component animations
- Storybook documentation

## Support

For questions or issues, refer to:
- Permission Schema: `src/core/operations/permissions/README.md`
- Design Tokens: `src/ui/components/design-system/`
- Component Specifications: `src/ui/components/core/`

