/**
 * 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.css';
import NileElement from '../internal/nile-element';

/**
 * Nile side-bar-group-item component.
 *
 * @tag nile-side-bar-group-item
 *
 * @slot icon - Slot for the item icon
 * @slot text - Slot for the item text
 * @slot trigger - Slot for chevron/trigger icons
 * @slot content - Slot for dropdown/popover content
 *
 * @csspart base - Wrapper for the group item
 * @csspart link - The clickable row (div or anchor)
 * @csspart content - Content container (for dropdown/popover)
 */
@customElement('nile-side-bar-group-item')
export class NileSideBarGroupItem extends NileElement {

  @property({ type: String }) link: string | null = null;

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

  @property({ type: String, reflect: true })
  type: 'default' | 'dropdown' | 'popover' = 'default';

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

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


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

  private toggleExpand() {
    if ((this.type === 'dropdown' || this.type === 'popover') && !this.disabled) {
      this.expanded = !this.expanded;
    }
  }

  connectedCallback() {
    super.connectedCallback();
    if (this.link && window.location.pathname === this.link) {
      this.active = true;
    }
  }

  private handleSelect(e: Event) {
    e.preventDefault();
    if (this.disabled) {
      e.stopImmediatePropagation();
      return;
    }

    if (!this.link) {
      e.preventDefault();
    }
    const parent = this.closest('nile-side-bar');
    if (parent) {
      parent.querySelectorAll<NileSideBarGroupItem>('nile-side-bar-group-item[active]')
        .forEach(item => {
          if (item !== this) {
            item.active = false;
            item.expanded = false; 
          }
        });
    }
  
    this.active = true;
  
    if ((this.type === 'dropdown' || this.type === 'popover') && !this.disabled) {
      this.expanded = true;
    }
    this.dispatchEvent(
      new CustomEvent('nile-click', {
        bubbles: true,
        composed: true,
        detail: {
          href: this.link,
          text: this.textContent?.trim() || '',
          type: this.type,
        },
      })
    );
  }

  public render(): TemplateResult {
    const interactive = this.type === 'dropdown' || this.type === 'popover';

    return html`
      <div
        part="base"
        class="group-item ${this.disabled ? 'disabled' : ''}"
        role="listitem"
        ?data-expanded=${this.expanded}
        aria-disabled=${this.disabled ? 'true' : 'false'}
      >
        ${this.link
          ? html`
              <a
                part="link"
                class="item-link"
                href=${this.link}
                @click=${this.handleSelect}
                tabindex=${this.disabled ? '-1' : '0'}
              >
                <slot name="icon"></slot>
                <slot name="text"></slot>
                <slot name="trigger"></slot>
              </a>
            `
          : html`
              <div
                part="link"
                class="item-link"
                @click=${(e: Event) => {
                  this.handleSelect(e);
                  if (interactive && !this.disabled) this.toggleExpand();
                }}
                tabindex=${this.disabled ? '-1' : '0'}
              >
                <slot name="icon" part="icon"></slot>
                <slot name="text" part="text"></slot>
                <slot name="trigger" part="trigger"></slot>
              </div>
            `}
      </div>

      ${interactive
        ? html`
            <div
              part="content"
              class="item-content"
              role=${this.type === 'dropdown' ? 'menu' : 'dialog'}
              ?hidden=${!this.expanded}
            >
              <slot name="content"></slot>
            </div>
          `
        : null}
    `;
  }
}

export default NileSideBarGroupItem;

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