import { IRegion, region } from "@uxland/regions";
import { LitElement, css, html, unsafeCSS } from "lit";
import { property, state } from "lit/decorators.js";
import { PrimariaRegionHost, shellApi } from "../../../../api/api";
import { ExitShell } from "../../../../features/exit/request";
import { GetUserInfo } from "../../../../features/get-user-info/request";
import styles from "./styles.css?inline";
import { template } from "./template";
import { IUserInfo } from "../../../../features/get-user-info/model";

export class PrimariaShellHeader extends PrimariaRegionHost(LitElement) {
  render() {
    return html`${template(this)}`;
  }

  static styles = css`
  ${unsafeCSS(styles)}
`;

  @region({ targetId: "header-region-container", name: shellApi.regionManager.regions.shell.header })
  headerRegion: IRegion | undefined;

  @region({ targetId: "header-actions-region-container", name: shellApi.regionManager.regions.shell.headerRightActions })
  headerRightActionsRegion: IRegion | undefined;

  @property({ type: Object })
  professional: IUserInfo;

  @state()
  menuOpened = false;

  toggleMenu() {
    this.menuOpened = !this.menuOpened;
  }

  logout() {
    shellApi.broker.send(new ExitShell());
  }

  connectedCallback() {
    super.connectedCallback();
    shellApi.broker.send(new GetUserInfo()).then((response: IUserInfo) => {
      this.professional = response;
    });
  }

  firstUpdated() {
    const container = this.renderRoot?.querySelector("#header-region-container");
    if (!container) return;

    let observer: MutationObserver;

    const updateDividers = () => {
      observer.disconnect();

      Array.from(container.querySelectorAll("header-divider")).forEach((div) => (div as HTMLElement).remove());

      const children = Array.from(container.children).filter((el) => (el as HTMLElement).tagName !== "HEADER-DIVIDER");

      for (let i = 1; i < children.length; i++) {
        const divider = document.createElement("header-divider");
        container.insertBefore(divider, children[i]);
      }

      observer.observe(container, { childList: true });
    };

    observer = new MutationObserver(updateDividers);
    observer.observe(container, { childList: true });
  }
}
