import { computed, inject, type Signal } from '@angular/core';
import type {
DictionaryKeys,
DictionaryRegistryContent,
LocalesValues,
} from '@intlayer/types';
import { getIntlayer } from '../getIntlayer';
import type { DeepTransformContent } from '../plugins';
import { INTLAYER_TOKEN, type IntlayerProvider } from './installIntlayer';
/** guard utility - true only for objects generated by `renderIntlayerNode()` */
export const isUpdatableNode = (
val: unknown
): val is { __update: (n: unknown) => void } =>
!!val &&
typeof val === 'object' &&
typeof (val as any).__update === 'function';
/**
* Angular hook that picks one dictionary by its key and returns its reactive content.
*
* It utilizes Angular signals to provide deep reactivity, ensuring your components
* update automatically when the locale changes.
*
* @param key - The unique key of the dictionary to retrieve.
* @param locale - Optional locale to override the current context locale.
* @returns The transformed dictionary content.
*
* @example
* ```ts
* import { Component } from '@angular/core';
* import { useIntlayer } from 'angular-intlayer';
*
* @Component({
* standalone: true,
* selector: 'app-my-component',
* template: `<div>{{ content().myField.value }}</div>`,
* })
* export class MyComponent {
* content = useIntlayer('my-dictionary-key');
* }
* ```
*/
export const useIntlayer = <T extends DictionaryKeys, L extends LocalesValues>(
key: T,
locale?: LocalesValues
): Signal<DeepTransformContent<DictionaryRegistryContent<T>>> => {
const intlayer = inject<IntlayerProvider>(INTLAYER_TOKEN)!;
/** which locale should we use right now? */
const localeTarget = computed(() => locale ?? intlayer.locale());
/** a *stable* reactive dictionary object */
// @ts-ignore Type instantiation is excessively deep and possibly infinite
const content = computed(() => getIntlayer<T, L>(key, localeTarget() as L));
return content; // all consumers keep full reactivity
};