# @erpsquad/common

A comprehensive React component library for ERP applications, built with Material-UI and TypeScript. This library provides 100+ reusable UI components, theming system, utilities, hooks, and optional Redux integration for building modern ERP applications.

## 🚀 Features

- **100+ UI Components**: Comprehensive set of form controls, data display, navigation, and layout components
- **Material-UI Integration**: Built on top of Material-UI with custom theming
- **TypeScript Support**: Full TypeScript definitions for all components and utilities
- **Flexible Redux Integration**: Optional Redux support - components work with or without Redux
- **Theme System**: Light/dark themes with RTL/LTR support and customizable colors
- **Internationalization**: Built-in i18n support with language switching
- **Tree Shaking**: Optimized for bundle size with proper tree shaking support
- **Accessibility**: WCAG compliant components with proper ARIA attributes
- **Modular Architecture**: Import only what you need to minimize bundle size
- **Peer Dependency Management**: Flexible dependency management for different project setups


### Development Environment
For local development, you can create a `.env` file in your project root with these variables. Make sure to add `.env` to your `.gitignore` file to keep sensitive information secure.

### Production Deployment
For production deployments, set these environment variables in your hosting environment's configuration panel.

## 📦 Installation

```bash
npm install @erpsquad/common
```

### Peer Dependencies

The library uses peer dependencies to avoid version conflicts and reduce bundle size. Install the dependencies you need based on your usage:

#### Required (Core functionality)

```bash
npm install react react-dom @mui/material @emotion/react @emotion/styled @mui/icons-material
```

#### Optional (Feature-specific)

For Redux integration:

```bash
npm install @reduxjs/toolkit react-redux
```

For date components:

```bash
npm install @mui/x-date-pickers date-fns
```

For data grid components:

```bash
npm install @mui/x-data-grid
```

For routing utilities:

```bash
npm install react-router-dom
```

For internationalization:

```bash
npm install react-i18next i18next
```

For utility functions:

```bash
npm install lodash axios
```

#### Complete Installation (All features)

```bash
# Install all peer dependencies for full functionality
npm install react react-dom @mui/material @emotion/react @emotion/styled @mui/icons-material @reduxjs/toolkit react-redux @mui/x-date-pickers @mui/x-data-grid date-fns react-router-dom react-i18next i18next lodash axios
```

## 🎯 Quick Start

### ⚠️ IMPORTANT: Import Styles

**Before using any components, you MUST import the CSS file in your main application file:**

```tsx
// main.tsx or App.tsx or index.tsx
import '@erpsquad/common/style.css'; // 👈 REQUIRED - Import this first!
```

Without this import, components will render but have **no styling**.

---

### Core Usage (Minimal dependencies)

The library provides core functionality without requiring all peer dependencies:

```tsx
import React from 'react';
// ⚠️ IMPORTANT: Import styles first (in your main file)
import '@erpsquad/common/style.css';

import {
	configureLibrary,
	getLibraryConfig,
	images,
	DEFAULT_LANG,
	type LibraryConfig
} from '@erpsquad/common';

// Configure library for your application
const config: LibraryConfig = {
	routes: {
		login: '/auth/login',
		dashboard: '/dashboard'
	},
	validation: {
		emailRequired: true,
		phoneRequired: false
	},
	dataTransforms: {
		dateFormat: 'dd/MM/yyyy'
	}
};

configureLibrary(config);

function App() {
	const currentConfig = getLibraryConfig();

	return (
		<div>
			<img src={images.logo} alt='Logo' />
			<p>Default language: {DEFAULT_LANG}</p>
			<p>Login route: {currentConfig.routes?.login}</p>
		</div>
	);
}

export default App;
```

### Available Core Exports

The following exports are available without peer dependencies:

```tsx
// Configuration system
import {
	configureLibrary,
	getLibraryConfig,
	getConfigFunction,
	type LibraryConfig
} from '@erpsquad/common';

// Static assets
import { default as images } from '@erpsquad/common';

// Constants
import { DEFAULT_LANG, LANGUAGES, S3_BUCKET_URL } from '@erpsquad/common';

// TypeScript types
import type {
	BaseComponentProps,
	ThemeConfig,
	SelectOption,
	TableColumn,
	User,
	Permission
} from '@erpsquad/common';
```

### Full Usage (With peer dependencies)

After installing peer dependencies, you can use all components:

```tsx
import React from 'react';
// ⚠️ Import styles first!
import '@erpsquad/common/style.css';

// Note: Import from specific paths to avoid dependency issues
import { ERPUIProvider } from '@erpsquad/common/contexts';
import { Button, TextField } from '@erpsquad/common/components';

function App() {
	return (
		<ERPUIProvider>
			<div>
				<TextField label='Name' variant='outlined' />
				<Button variant='contained' color='primary'>
					Submit
				</Button>
			</div>
		</ERPUIProvider>
	);
}

export default App;
```

### With Custom Theme

```tsx
import React from 'react';
// ⚠️ Import styles first!
import '@erpsquad/common/style.css';

import { ERPUIProvider } from '@erpsquad/common/contexts';
import { Button } from '@erpsquad/common/components';
import { createLightTheme } from '@erpsquad/common/theme';

function App() {
	const { theme } = createLightTheme('#2196f3', 'ltr');

	return (
		<ERPUIProvider
			theme={theme}
			themeMode='dark'
			primaryColor='#2196f3'
			enableCssBaseline={true}>
			<Button variant='contained'>Dark Theme Button</Button>
		</ERPUIProvider>
	);
}
```

## 🎨 Theme System

The library includes a comprehensive theming system with support for light/dark modes, RTL/LTR direction, and custom colors.

### Theme Configuration

```tsx
import { ERPUIProvider } from '@erpsquad/common/contexts';

<ERPUIProvider
	themeMode='light' // 'light' | 'dark'
	primaryColor='#1976d2' // Any valid color
	direction='ltr' // 'ltr' | 'rtl'
	enableCssBaseline={true}>
	<App />
</ERPUIProvider>;
```

### Custom Theme Object

```tsx
import { createLightTheme, createDarkTheme } from '@erpsquad/common/theme';
import { ERPUIProvider } from '@erpsquad/common/contexts';

// Create custom theme
const { theme } = createLightTheme('#1976d2', 'ltr');

// Or create dark theme
const { darkTheme } = createDarkTheme('#1976d2', 'ltr');

<ERPUIProvider theme={theme}>
	<App />
</ERPUIProvider>;
```

### Available Colors

The library supports various color formats:

- Hex colors: `#1976d2`
- RGB: `rgb(25, 118, 210)`
- Color names: `blue`, `red`, `green`
- Material-UI color objects

## 🎨 Styles & SCSS

The library provides a comprehensive styling system with compiled CSS, SCSS variables, mixins, utility classes, and animations.

### Import Compiled CSS (Recommended)

Add this to your main application file:

```tsx
// main.tsx or App.tsx
import '@erpsquad/common/style.css';
```

This gives you:
- All component styles
- Utility classes for rapid development
- Responsive styles
- Animations

### Using Utility Classes

```tsx
<div className="d-flex justify-content-center align-items-center mb-2">
  <h1 className="h2 bold">Welcome</h1>
  <p className="s2 normal text-center">Description text</p>
</div>
```

Available utility classes:
- **Layout**: `d-flex`, `flex-direction-column`, `justify-content-center`, `align-items-center`
- **Spacing**: `mb-1`, `mt-2`, `p-0`, `pl-2` (padding/margin utilities)
- **Typography**: `h1`-`h5` (headings), `s1`-`s5` (body text), `bold`, `medium`, `normal`
- **Width/Height**: `w-100`, `w-50`, `h-100`, `vh-100`
- **Text Alignment**: `text-center`, `text-left`, `text-right`

### Using SCSS Variables (Advanced)

Import SCSS variables in your `.scss` files:

```scss
// your-component.scss
@import '@erpsquad/common/styles/variables';

.custom-component {
  background-color: $primary-600;
  color: $neutral-100;
  border: 1px solid $neutral-300;
}
```

Available color scales (100-1000):
- `$primary-*` (green), `$neutral-*` (gray), `$error-*` (red)
- `$blue-*`, `$magenta-*`, `$olive-*`, `$green-*`, `$lightGreen-*`

### Using SCSS Mixins (Advanced)

```scss
// your-component.scss
@import '@erpsquad/common/styles/mixins';

.responsive-layout {
  @include flex(center, space-between, row);
  
  @include media-md {
    flex-direction: column;
  }
}
```

Available mixins:
- `@include flex($align, $justify, $direction)` - Flexbox shorthand
- `@include transition($time, $motion)` - Transition shorthand
- `@include center` - Absolute center positioning
- Responsive breakpoints: `@include media-sm`, `@include media-md`, `@include media-l`, etc.

### Import All SCSS Features

```scss
// For complete access to variables, mixins, utilities, and animations
@import '@erpsquad/common/styles/all';
```

**📚 For detailed styles documentation, see:**
- [Complete Styles Documentation](./src/styles/README.md)
- [Styles Usage Guide](./STYLES_USAGE.md)
- [Migration Guide](./STYLES_MIGRATION.md)

## 📁 Modular Import System

The library uses a modular import system to prevent dependency issues. Import from specific paths based on your needs:

```tsx
// Core functionality (no peer dependencies required)
import { configureLibrary, images } from '@erpsquad/common';

// Components (requires React, MUI peer dependencies)
import { Button, TextField } from '@erpsquad/common/components';

// Hooks (requires React peer dependencies)
import { useAuth, useLanguage } from '@erpsquad/common/hooks';

// Contexts (requires React peer dependencies)
import { ERPUIProvider, AuthProvider } from '@erpsquad/common/contexts';

// Theme utilities (requires MUI peer dependencies)
import { createLightTheme, createDarkTheme } from '@erpsquad/common/theme';

// Utility functions (may require specific peer dependencies)
import { formatDate, validateEmail } from '@erpsquad/common/utils';

// Redux integration (requires Redux peer dependencies)
import { createLibraryStore, slices } from '@erpsquad/common/redux';

// API clients (requires axios peer dependency)
import { AccountingAPI, InventoryAPI } from '@erpsquad/common/api-client';

// Styles (CSS bundle - recommended)
import '@erpsquad/common/style.css';

// Styles (SCSS imports for advanced usage)
// Import in .scss files only:
// @import '@erpsquad/common/styles/variables';
// @import '@erpsquad/common/styles/mixins';
// @import '@erpsquad/common/styles/all';
```

## 🔌 API Clients

The library includes pre-configured API clients for different ERP modules:

```tsx
import {
	AccountingAPI,
	InventoryAPI,
	ManufacturingAPI,
	PurchaseAPI,
	SalesAPI,
	RentalAPI,
	RbacAPI,
	DriveAPI,
	SystemFeatureAPI
} from '@erpsquad/common/api-client';

// Configure base API client
const baseConfig = {
	baseURL: 'https://api.example.com',
	timeout: 10000,
	headers: {
		'Content-Type': 'application/json'
	}
};

// Use specific API clients
const accountingClient = new AccountingAPI(baseConfig);
const inventoryClient = new InventoryAPI(baseConfig);

// Example usage
const users = await accountingClient.getUsers();
const products = await inventoryClient.getProducts();
```

## 🔧 Components

### Form Controls

```tsx
import {
  TextField,
  Select,
  DatePicker,
  Checkbox,
  Radio,
  ToggleSwitch,
  Button
} from '@erpsquad/common/components';

// Text input
<TextField
  label="Email"
  type="email"
  variant="outlined"
  required
/>

// Select dropdown
<Select
  label="Country"
  options={countries}
  value={selectedCountry}
  onChange={handleCountryChange}
/>

// Date picker (requires @mui/x-date-pickers)
<DatePicker
  label="Birth Date"
  value={birthDate}
  onChange={setBirthDate}
/>
```

### Data Display

```tsx
import {
  MaterialTable,
  Grid,
  CardWrapper,
  Avatar,
  Chip
} from '@erpsquad/common/components';

// Data table (requires @mui/x-data-grid)
<MaterialTable
  columns={columns}
  data={data}
  title="Users"
  options={{
    search: true,
    pagination: true,
    sorting: true
  }}
/>

// Grid layout
<Grid container spacing={2}>
  <Grid item xs={12} md={6}>
    <CardWrapper>Content</CardWrapper>
  </Grid>
</Grid>
```

### Navigation

```tsx
import {
  Sidebar,
  BreadCrumb,
  Pagination,
  Tabs
} from '@erpsquad/common/components';

// Sidebar navigation
<Sidebar
  items={navigationItems}
  collapsed={isCollapsed}
  onItemClick={handleNavigation}
/>

// Breadcrumb (requires react-router-dom for navigation)
<BreadCrumb
  items={[
    { label: 'Home', href: '/' },
    { label: 'Users', href: '/users' },
    { label: 'Profile' }
  ]}
/>
```

### Feedback

```tsx
import {
  CustomSnackbar,
  Toast,
  Loader,
  Alert,
  Modal
} from '@erpsquad/common/components';

// Loading indicator
<Loader size="large" text="Loading data..." />

// Alert message
<Alert severity="success" onClose={handleClose}>
  Operation completed successfully!
</Alert>

// Snackbar notification
<CustomSnackbar
  open={isOpen}
  message="Operation completed successfully!"
  severity="success"
  onClose={handleClose}
/>

// Modal dialog
<Modal
  open={isOpen}
  onClose={handleClose}
  title="Confirm Action"
  actions={[
    { label: 'Cancel', onClick: handleClose },
    { label: 'Confirm', onClick: handleConfirm, variant: 'contained' }
  ]}
>
  Are you sure you want to proceed?
</Modal>
```

## 🔄 Redux Integration

The library provides flexible Redux integration that works with or without Redux. Requires `@reduxjs/toolkit` and `react-redux` peer dependencies.

### With Redux (Recommended for complex applications)

```tsx
import { ERPUIProvider } from '@erpsquad/common/contexts';
import {
	createLibraryStore,
	createConfiguredApiClient
} from '@erpsquad/common/redux';
import { ShareModal } from '@erpsquad/common/components';

// Configure API client
const apiClient = createConfiguredApiClient(baseApiClient, () => ({
	authorization: `Bearer ${getAuthToken()}`
}));

// Create store with library slices
const store = createLibraryStore(
	{
		// Your app reducers
		app: appReducer,
		user: userReducer
	},
	apiClient
);

function App() {
	return (
		<ERPUIProvider useRedux={true} reduxStore={store} apiClient={apiClient}>
			<ShareModal useRedux={true} />
		</ERPUIProvider>
	);
}
```

### Without Redux (Simpler applications)

```tsx
import { ERPUIProvider } from '@erpsquad/common/contexts';
import { ShareModal } from '@erpsquad/common/components';

function App() {
	const [users, setUsers] = useState([]);
	const [loading, setLoading] = useState(false);

	const fetchUsers = async () => {
		setLoading(true);
		try {
			const response = await api.getUsers();
			setUsers(response.data);
		} finally {
			setLoading(false);
		}
	};

	return (
		<ERPUIProvider useRedux={false}>
			<ShareModal
				useRedux={false}
				users={users}
				loading={loading}
				onFetchUsersAndDepartments={fetchUsers}
			/>
		</ERPUIProvider>
	);
}
```

### Available Redux Slices

- **shareSlice**: User and department data for sharing functionality
- **headerSlice**: Language data and current language selection
- **reportsTitleBarSlice**: Company data for reports filtering
- **inventoryReportsTitleBarSlice**: Inventory-related data for reports

## 🪝 Hooks

### Custom Hooks

```tsx
import {
	useAuth,
	useLanguage,
	usePermissions,
	usePages,
	useDeepMemo,
	useReduxIntegration
} from '@erpsquad/common/hooks';

// Authentication hook
const { user, isAuthenticated, login, logout } = useAuth();

// Language hook (requires react-i18next)
const { currentLanguage, changeLanguage, t } = useLanguage();

// Permissions hook
const { hasPermission, checkPermission } = usePermissions();

// Deep memoization hook
const memoizedValue = useDeepMemo(() => expensiveCalculation(data), [data]);
```

### Redux Integration Hook

```tsx
import { useReduxIntegration } from '@erpsquad/common/hooks';

const MyComponent = ({ useRedux, ...props }) => {
	const { data, loading, error, actions } = useReduxIntegration({
		useRedux,
		sliceName: 'share',
		fallbackData: props.users,
		fallbackLoading: props.loading,
		fallbackActions: {
			fetchData: props.onFetchUsers
		}
	});

	// Component logic using unified interface
};
```

## 🛠️ Utilities

### Common Utilities

```tsx
import {
	formatDate,
	formatFileSize,
	formatText,
	deformatText,
	colorUtils
} from '@erpsquad/common/utils';

// Date formatting (requires date-fns)
const formattedDate = formatDate(new Date(), 'dd/MM/yyyy');

// File size formatting
const fileSize = formatFileSize(1024000); // "1.02 MB"

// Text formatting
const formatted = formatText('hello world', 'title'); // "Hello World"

// Color utilities
const hexColor = colorUtils.rgbToHex(255, 0, 0); // "#ff0000"
```

## 🌐 Internationalization

Requires `react-i18next` and `i18next` peer dependencies.

### Language Provider

```tsx
import { ERPUIProvider } from '@erpsquad/common/contexts';

<ERPUIProvider
	enableLanguage={true}
	// Other props
>
	<App />
</ERPUIProvider>;
```

### Using Translations

```tsx
import { useLanguage } from '@erpsquad/common/hooks';

const MyComponent = () => {
	const { t, currentLanguage, changeLanguage } = useLanguage();

	return (
		<div>
			<p>{t('common.welcome')}</p>
			<button onClick={() => changeLanguage('es')}>Switch to Spanish</button>
		</div>
	);
};
```

## 🧪 Testing

The library includes comprehensive testing utilities:

```tsx
import { render, screen } from '@testing-library/react';
import { ERPUIProvider } from '@erpsquad/common/contexts';
import { Button } from '@erpsquad/common/components';

test('renders button correctly', () => {
	render(
		<ERPUIProvider>
			<Button>Click me</Button>
		</ERPUIProvider>
	);

	expect(screen.getByRole('button')).toBeInTheDocument();
});
```

## 📚 API Reference

### ERPUIProvider Props

| Prop             | Type                | Default     | Description              |
| ---------------- | ------------------- | ----------- | ------------------------ |
| `useRedux`       | `boolean`           | `false`     | Enable Redux integration |
| `reduxStore`     | `Store`             | `undefined` | Custom Redux store       |
| `apiClient`      | `ApiClientConfig`   | `undefined` | API client configuration |
| `themeMode`      | `'light' \| 'dark'` | `'light'`   | Theme mode               |
| `primaryColor`   | `string`            | `undefined` | Primary theme color      |
| `direction`      | `'ltr' \| 'rtl'`    | `'ltr'`     | Text direction           |
| `enableAuth`     | `boolean`           | `true`      | Enable auth context      |
| `enableLanguage` | `boolean`           | `true`      | Enable language context  |
| `enableRouter`   | `boolean`           | `false`     | Enable router provider   |
| `enableSnackbar` | `boolean`           | `true`      | Enable snackbar provider |

### Component Props

All components extend their respective Material-UI component props with additional ERP-specific functionality. Refer to individual component documentation for detailed prop information.

## 🔧 Development

### Building the Library

```bash
# Production build
npm run build

# Build with analysis
npm run build:analyze

# Build with validation
npm run build:validate

# Clean build artifacts
npm run clean
```

### Running Tests

```bash
# Run all tests
npm test

# Run tests in CI mode
npm run test:ci

# Type checking
npm run type-check

# Linting
npm run lint
npm run lint:fix
```

### Package Validation

```bash
# Validate package structure
npm run validate:package

# Check bundle size limits
npm run size-check

# Full validation (lint + type-check + test + build)
npm run validate
```

## 📈 Bundle Analysis

```bash
# Analyze bundle size and composition
npm run build:analyze

# Check size limits against configuration
npm run size-check

# Validate package contents before publishing
npm run validate:package
```

## 🚨 Troubleshooting

### Common Issues

#### ⚠️ Components Have No Styling

**Problem**: Components render but have no styling / look unstyled.

**Solution**: You MUST import the CSS file in your application:

```tsx
// In your main file (main.tsx, App.tsx, or index.tsx)
import '@erpsquad/common/style.css'; // 👈 Add this!

// Then import components
import { Button } from '@erpsquad/common/components';
```

**Why**: Component styles are bundled separately for optimal tree-shaking and loading performance. The CSS file must be explicitly imported once in your application entry point.

#### Import Errors

```bash
# Error: Cannot resolve '@erpsquad/common/components'
# Solution: Install required peer dependencies
npm install @mui/material @emotion/react @emotion/styled

# Error: Module not found
# Solution: Use correct import paths
import { Button } from '@erpsquad/common/components'; // ✅ Correct
import { Button } from '@erpsquad/common'; // ❌ Incorrect for components
```

#### Peer Dependency Warnings

```bash
# Warning: peer dependency not installed
# Solution: Install the specific peer dependency
npm install react-redux @reduxjs/toolkit

# Or install all peer dependencies
npm install react react-dom @mui/material @emotion/react @emotion/styled @mui/icons-material
```

#### TypeScript Errors

```bash
# Error: Cannot find type definitions
# Solution: Ensure TypeScript types are properly imported
import type { LibraryConfig } from '@erpsquad/common';

# Error: Module has no exported member
# Solution: Check if the export requires peer dependencies
import { useAuth } from '@erpsquad/common/hooks'; // Requires React
```

#### Build Issues

```bash
# Error: Module not found during build
# Solution: Check if all peer dependencies are installed
# and properly configured in your build tool

# For Vite projects, add to vite.config.ts:
export default defineConfig({
  optimizeDeps: {
    include: ['@erpsquad/common']
  }
});

# For Webpack projects, ensure proper externals configuration
```

### Getting Help

- Check the [troubleshooting guide](./TROUBLESHOOTING.md)
- Review [migration documentation](./MIGRATION.md)
- Search [existing issues](https://github.com/erpforce/common/issues)
- Create a [new issue](https://github.com/erpforce/common/issues/new)

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/new-component`
3. Make your changes and add tests
4. Run tests: `npm test`
5. Run linting: `npm run lint`
6. Commit your changes: `git commit -m 'Add new component'`
7. Push to the branch: `git push origin feature/new-component`
8. Submit a pull request

### Development Guidelines

- Follow TypeScript best practices
- Write comprehensive tests for new components
- Update documentation for API changes
- Ensure accessibility compliance
- Maintain backward compatibility

## 📄 License

MIT License - see the [LICENSE](LICENSE) file for details.

## 🆘 Support

- **Documentation**: [Library Docs](https://github.com/erpforce/erpforce-common-hub-fe/tree/dev#readme)
- **Issues**: [GitHub Issues](https://github.com/erpforce/erpforce-common-hub-fe/issues)
- **NPM Package**: [@erpsquad/common](https://www.npmjs.com/package/@erpsquad/common)
- **Changelog**: [CHANGELOG.md](./CHANGELOG.md)
- **Migration Guide**: [MIGRATION.md](./MIGRATION.md)
- **Troubleshooting**: [TROUBLESHOOTING.md](./TROUBLESHOOTING.md)

## 📋 Changelog

See [CHANGELOG.md](CHANGELOG.md) for a detailed list of changes and version history.
