import {Meta} from '@storybook/addon-docs/blocks'

<Meta title='@dxtmisha/en/functional-basic/Classes/Translate - Translation and Text Management'/>

# Translate Class

A static wrapper for a default instance of the `TranslateInstance` class. It manages translations and localized text at a global level, providing tools for retrieving, caching, and displaying content with template support and automatic locale detection.

## Relationship with TranslateInstance

The `Translate` class acts as a global, pre-configured interface for `TranslateInstance`. All static methods call the corresponding methods on an internal instance (`Translate.getItem()`).

While `Translate` is suitable for most application-wide translation needs, you can create independent translation environments using `TranslateInstance`.

## Key Features

- **Batch Loading** — Intelligently groups translation requests, sending them as a single pack 160ms after being queued.
- **Flexible Templates** — Supports parameter replacement in text using both indices (`[0]`) and named keys (`{key}`).
- **Sync and Async Access** — Methods for instant text retrieval from cache (`getSync`) or guaranteed server loading (`get`).
- **Smart Cache** — Stores translations scoped to the current locale and supports fallbacks (Location > Language > Global).

## Initialization

The class is static and does not require instantiation. Configuration applies to the global translation instance.

```javascript
import { Translate } from '@dxtmisha/functional-basic'

// Configure API URL for the global instance
Translate.setUrl('/api/v1/translate')

// Preload necessary texts
await Translate.add(['welcome', 'auth.login'])
```

## Methods

### Configuration

- `setConfig(config: TranslateConfig): Translate` — Sets the complete configuration for the translation instance.
- `setUrl(url: string): Translate` — Changes the API endpoint for fetching translations.
- `setPropsName(name: string): Translate` — Changes the property name used in the API request/response.
- `setReadApi(value: boolean): Translate` — Enables or disables fetching translations from the API.

### Translation Retrieval

- `async get(name: string, replacement?: any): Promise<string>` — Asynchronously retrieves text. If not in cache and not on localhost, it attempts to load it from the server.
- `getSync(name: string, first?: boolean, replacement?: any): string` — Returns text from the cache. If `first` is `true`, returns a space ` ` if the text is missing.
- `async getList<T>(names: T): Promise<TranslateList<T>>` — Retrieves a group of translations (asynchronous).
- `getListSync<T>(names: T, first?: boolean): TranslateList<T>` — Retrieves a group of translations from the cache (synchronous).

### Batch Update

- `async add(names: string | string[]): Promise<void>` — Adds multiple codes to the queue for batch loading.
- `addSync(data: Record<string, string>): void` — Directly adds translations to the cache.
- `async addNormalOrSync(data: Record<string, string>): Promise<void>` — Adds translations directly on localhost, otherwise queues them for loading.
- `addSyncByLocation(data: Record<string, Record<string, string>>): void` — Adds translations for specific locations/locales.
- `addSyncByFile(data: TranslateDataFile): void` — Adds translations from a file definition.

### Static vs Instance

- **Usage**: Use `Translate` for global access anywhere in the app. Use `TranslateInstance` for localized, independent instances.
- **State**: `Translate` state is shared across the entire application. `TranslateInstance` provides isolated state for specific components or modules.
- **Creation**: `Translate` does not require instantiation (static wrapper). `TranslateInstance` is created via `new TranslateInstance()`.

## Standalone Instances

If you need to manage a separate set of translations (e.g., for a specific sub-application or a specialized widget), use `TranslateInstance` instead of the global `Translate` class.

```javascript
import { TranslateInstance, TranslateFile } from '@dxtmisha/functional-basic'

// 1. Create a specialized set of translation files
const widgetFiles = new TranslateFile({
  'en-US': () => import('./locales/widget.en-US.json')
})

// 2. Initialize a standalone translation instance
const widgetTranslate = new TranslateInstance(
  '/api/widget/translate', 
  'list', 
  widgetFiles
)

// 3. Use independently
const label = await widgetTranslate.get('widget.welcome')
```

## Types

### `TranslateCode`
A string (code name) or an array of strings. Arrays are used for template replacement:
- `string` — e.g., `'welcome'`
- `string[]` — e.g., `['welcome', 'Guest']`

### `TranslateList`
A record where keys are translation codes and values are the resulting translated strings.

## Examples

### Working with Templates
```javascript
// In database: "Hello, [0]! You have {count} notifications."
const text = await Translate.get('user.notifications', ['John', { count: 5 }])
// Result: "Hello, John! You have 5 notifications."
```

### Batch List Retrieval
```javascript
const labels = await Translate.getList([
  'home.title',
  ['home.welcome', 'Guest'], 
  'home.footer'
])
```
