import { forceUpdate } from "@stencil/core";
import { getLocale } from "./i18n";
const cleanupHandlers = new WeakMap();
const wrappedDisconnect = new WeakSet();
const registerCleanup = (target, cleanup) => {
    var _a;
    let handlers = cleanupHandlers.get(target);
    if (handlers === undefined) {
        handlers = new Set();
        cleanupHandlers.set(target, handlers);
    }
    handlers.add(cleanup);
    if (wrappedDisconnect.has(target)) {
        return;
    }
    const originalDisconnected = (_a = target.disconnectedCallback) === null || _a === void 0 ? void 0 : _a.bind(target);
    target.disconnectedCallback = () => {
        const currentHandlers = cleanupHandlers.get(target);
        if (currentHandlers !== undefined) {
            currentHandlers.forEach((handler) => {
                handler();
            });
            currentHandlers.clear();
        }
        if (originalDisconnected !== undefined) {
            originalDisconnected();
        }
    };
    wrappedDisconnect.add(target);
};
export const watchStoreLocale = (target, store, onLocaleChange, options) => {
    let activeLocale;
    // Trigger optional callback and force rerender on locale changes.
    const applyLocale = (inputLocale) => {
        const locale = getLocale(inputLocale);
        const previousLocale = activeLocale;
        activeLocale = locale;
        if (onLocaleChange !== undefined) {
            onLocaleChange(locale);
        }
        if (!(options === null || options === void 0 ? void 0 : options.skipForceUpdate) &&
            previousLocale !== undefined &&
            previousLocale !== locale) {
            forceUpdate(target);
        }
    };
    applyLocale(store.state.locale);
    const unsubscribe = store.onChange("locale", applyLocale);
    let disposed = false;
    const cleanup = () => {
        if (disposed)
            return;
        disposed = true;
        unsubscribe();
    };
    registerCleanup(target, cleanup);
    return cleanup;
};
//# sourceMappingURL=locale-state.js.map
