class LisioShadowRootController {
  private static _current: LisioShadowRootController;

  private _addedStyles = new Set<string>(); // stocke les styles déjà ajoutés
  private _root: ShadowRoot;
  private _styleElement: HTMLStyleElement = document.createElement("style");
  private _wrapper: HTMLElement;

  private constructor() {
    const rootEnv: HTMLElement = document.createElement("lisio-root");
    rootEnv.role = "complementary";
    rootEnv.id = `lisio-shadow-env`;
    this._root = rootEnv.attachShadow({ mode: "open", delegatesFocus: true });

    // Crée la div wrapper
    this._wrapper = document.createElement("div");
    this._wrapper.className = "lisio-wrapper";

    this._root.append(this._styleElement, this._wrapper);
    document.body.prepend(rootEnv);
    LisioShadowRootController._current = this;
  }

  public static get current() {
    if (!this._current) {
      this._current = new LisioShadowRootController();
    } else if (!document.getElementById("lisio-shadow-env")) {
      // DOM a été détruit par Turbo, on reconstruit
      this._current = new LisioShadowRootController();
    }
    return this._current;
  }

  public get root() {
    return this._root;
  }

  // public addStyles(styles: string) {
  //   this._styleElement.textContent += styles;
  // }
  public addStyles(styles: string) {
    if (!this._addedStyles.has(styles)) {
      this._styleElement.textContent += styles;
      this._addedStyles.add(styles);
    }
  }

  public appendElement(element: HTMLElement, styles: string) {
    this.addStyles(styles);
    this._wrapper.append(element);
    // this._root.append(element);
  }

  public removeElement(element: HTMLElement, styles: string) {
    this._wrapper.removeChild(element);
    // this._root.removeChild(element);
    this.removeStyles(styles);
  }

  public removeStyles(styles: string) {
    if (this._styleElement.textContent != undefined) {
      this._styleElement.textContent = this._styleElement.textContent?.replace(
        styles,
        "",
      );
      this._addedStyles.delete(styles);
    }
  }
}

export default LisioShadowRootController;
