import type { ReactiveController, ReactiveControllerHost } from "lit";
import { locale, type TranslationKey } from "./locale.js";

export class LocaleController implements ReactiveController {
  private _host: ReactiveControllerHost;
  private _unsub?: () => void;

  constructor(host: ReactiveControllerHost) {
    this._host = host;
    host.addController(this);
  }

  hostConnected() {
    this._unsub = locale.subscribe(() => this._host.requestUpdate());
    locale.init().then(() => this._host.requestUpdate());
  }

  hostDisconnected() {
    this._unsub?.();
  }

  t(key: TranslationKey): string {
    return locale.t(key);
  }

  get current() {
    return locale.current;
  }
}
