/**
 * Non-side-effect class export for `<nav-item-ui>`.
 *
 * Importing this file gives you the class(es) without auto-registering the tag.
 * Useful for test isolation, subclassing with tag-name override, or selective
 * composition.
 *
 * The auto-register path stays at `@adia-ai/web-components/components/nav-item`
 * (which imports this file + calls `defineIfFree()`).
 *
 * @see ../../USAGE.md#registration--auto-vs-explicit
 */

/**
 * <nav-item-ui> — Single navigation link inside <nav-ui> (optionally
 * nested under <nav-group-ui>). Consolidates the prior
 * `app-nav-item-ui` + `section-nav-item-ui` per ADR-0015 § Nav consolidation.
 *
 * Supports icon, label, optional badge, selected/disabled state, and
 * keyboard activation (Enter/Space). Selection is managed by the parent
 * <nav-ui>; clicking or keyboard-activating an item calls nav.select(this)
 * and dispatches `nav-select` (bubbles, detail: { item, text, value }).
 */

import { UIElement } from '../../core/element.js';

export class UINavItem extends UIElement {
  static properties = {
    text:     { type: String,  default: '', reflect: true },
    icon:     { type: String,  default: '', reflect: true },
    value:    { type: String,  default: '', reflect: true },
    badge:    { type: String,  default: '', reflect: true },
    selected: { type: Boolean, default: false, reflect: true },
    disabled: { type: Boolean, default: false, reflect: true },
    variant:  { type: String,  default: '', reflect: true },
  };

  static template = () => null;

  #onClick = (e) => {
    if (this.disabled) { e.preventDefault(); return; }
    const parent = this.closest('nav-ui');
    parent?.select?.(this);
    this.dispatchEvent(new CustomEvent('nav-select', {
      bubbles: true,
      detail: { item: this, text: this.text, value: this.value },
    }));
  };

  #onKey = (e) => {
    if (this.disabled) return;
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault();
      this.#onClick(e);
    }
  };

  connected() {
    this.setAttribute('role', 'link');
    this.setAttribute('tabindex', this.disabled ? '-1' : '0');

    if (!this.querySelector('[slot="text"]')) {
      this.innerHTML = `
        <span slot="icon">${this.icon ? `<icon-ui name="${this.icon}"></icon-ui>` : ''}</span>
        <span slot="text">${this.text}</span>
        ${this.badge ? `<span slot="badge">${this.badge}</span>` : ''}
      `;
    }

    this.addEventListener('click', this.#onClick);
    this.addEventListener('keydown', this.#onKey);
  }

  render() {
    const textEl = this.querySelector('[slot="text"]');
    if (textEl) textEl.textContent = this.text;
    this.setAttribute('tabindex', this.disabled ? '-1' : '0');
    if (this.selected) this.setAttribute('aria-current', 'page');
    else this.removeAttribute('aria-current');
  }

  disconnected() {
    this.removeEventListener('click', this.#onClick);
    this.removeEventListener('keydown', this.#onKey);
  }
}
