import { regionView } from "@uxland/regions";
import { LitElement, PropertyValues, css, html, unsafeCSS } from "lit";
import { property, state } from "lit/decorators.js";
import { shellApi } from "../../../api/api";
import { BROKER_EVENTS } from "../../../api/broker/broker-events";
import { PrimariaNavItemConfig } from "../typings";
import styles from "./styles.css?inline";
import { template } from "./template";
import { BrokerDisposableHandler } from "@uxland/harmonix";

export class PrimariaNavItem extends regionView(LitElement) {
  static styles = css`
    ${unsafeCSS(styles)}
  `;

  constructor(config: PrimariaNavItemConfig) {
    super();
    this.config = config;
  }

  private subscriptions: BrokerDisposableHandler[] = [];

  connectedCallback(): void {
    super.connectedCallback();
    this._subscribeEvents();
  }

  disconnectedCallback(): void {
    this._unsubscribeEvents();
  }

  firstUpdated(_changedProps: PropertyValues<PrimariaNavItem>) {
    super.firstUpdated(_changedProps);
    this.observeHostResize();
  }

  observeHostResize() {
    const parentElement = this.parentElement;
    const observer = new ResizeObserver((entries) => {
      for (const entry of entries) {
        const width = entry.target.clientWidth; // Obtenemos el ancho del host
        this.showText = width > 100; // Mostrar texto si el ancho del host es mayor que 150px
      }
    });

    observer.observe(parentElement as HTMLElement);
  }

  _subscribeEvents() {
    const subscription = shellApi.broker.subscribe(BROKER_EVENTS.shell.mainViewChanged, (payload: { viewId: string }) => {
      this.isActive = payload.viewId === this.view?.id;
    });
    this.subscriptions.push(subscription);
  }

  _unsubscribeEvents() {
    this.subscriptions.forEach((s) => s.dispose());
  }

  render() {
    return html`${template(this)}`;
  }

  @property({ type: Number }) containerWidth = 0;
  @state() showText = false;
  @state() isActive = false;

  @property({ type: Object }) config: PrimariaNavItemConfig;
}
