/**
 * Copyright Aquera Inc 2023
 *
 * This source code is licensed under the BSD-3-Clause license found in the
 * LICENSE file in the root directory of this source tree.
 */

import { html, CSSResultArray, TemplateResult } from 'lit';
import { customElement, property } from 'lit/decorators.js';
import { styles } from './nile-side-bar-group-item-icon.css';
import NileElement from '../internal/nile-element';
import type { NileSideBar } from '../nile-side-bar/nile-side-bar';

/**
 * Nile side-bar-group-item-icon component.
 *
 * @tag nile-side-bar-group-item-icon
 *
 * @attr icon - The name of the icon to render inside <nile-icon>
 * @attr tooltip - Tooltip text shown when sidebar is collapsed
 *
 * @slot - Optional slot to override the icon completely
 */
@customElement('nile-side-bar-group-item-icon')
export class NileSideBarGroupItemIcon extends NileElement {
  /**
   * Name of the icon (passed to <nile-icon name="">)
   */
  @property({ type: String, reflect: true })
  icon: string = '';

  /**
   * Tooltip text (auto-synced from sibling text if available)
   */
  @property({ type: String })
  tooltip: string = '';

  @property({ type: String })
  method: string = 'fill';

  @property({ type: String })
  size: string = '14';

  @property ({type: Boolean, attribute: true, reflect: true}) enableVisibilityEffect: boolean = false;

  @property ({type: Number, attribute: true, reflect: true}) duration: number = 200;

  private sidebar: NileSideBar | null = null;

  public static get styles(): CSSResultArray {
    return [styles];
  }

  connectedCallback(): void {
	if (!this.hasAttribute('slot')) {
		this.setAttribute('slot', 'icon');
	  }
	  
    super.connectedCallback();
    this.sidebar = this.closest('nile-side-bar') as NileSideBar | null;
    if (this.sidebar) {
      const observer = new MutationObserver(() => this.requestUpdate());
      observer.observe(this.sidebar, { attributes: true, attributeFilter: ['collapsed'] });
      (this as any)._observer = observer;
    }
  }

  disconnectedCallback(): void {
    super.disconnectedCallback();
    (this as any)._observer?.disconnect();
  }

  private getSiblingText(): string {
    const parent = this.parentElement;
    const textEl = parent?.querySelector('nile-side-bar-group-item-text');
    return textEl?.textContent?.trim() ?? '';
  }

  public render(): TemplateResult {
    const isCollapsed = !!this.sidebar?.collapsed;
    const text = this.tooltip || this.getSiblingText();

    if (isCollapsed && text) {
      return html`

          <slot>
          <nile-lite-tooltip hoist distance="18" content=${text} placement="right" enableVisibilityEffect=${this.enableVisibilityEffect} duration=${this.duration}>
            ${this.icon ? html`<nile-icon size=${this.size}  color="var(--nile-colors-dark-900,var(--ng-colors-fg-quaternary-400))" name=${this.icon} method=${this.method}></nile-icon>` : null}
            </nile-lite-tooltip>
          </slot>

      `;
    }

    return html`
      <slot>
        ${this.icon ? html`<nile-icon size=${this.size} color="var(--nile-colors-dark-900,var(--ng-colors-fg-quaternary-400))" size="14" name=${this.icon} method=${this.method}></nile-icon>` : null}
      </slot>
    `;
  }
}

export default NileSideBarGroupItemIcon;

declare global {
  interface HTMLElementTagNameMap {
    'nile-side-bar-group-item-icon': NileSideBarGroupItemIcon;
  }
}
