/**
 * Non-side-effect class export for `<avatar-ui>` (+ co-located primitives).
 *
 * 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/avatar`
 * (which imports this file + calls `defineIfFree()`).
 *
 * @see ../../USAGE.md#registration--auto-vs-explicit
 */

/**
 * <avatar-ui src="photo.jpg" text="Alice Smith" size="md" shape="circle"></avatar-ui>
 *
 * Fallback chain: image → initials → empty.
 * If src fails to load, falls back to initials derived from text.
 *
 * <avatar-group-ui max="4" size="md">
 *   <avatar-ui text="Alice"></avatar-ui>
 *   <avatar-ui text="Bob"></avatar-ui>
 *   ...
 * </avatar-group-ui>
 *
 * Overlapping avatar stack with +N overflow counter.
 */

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

// ── Avatar ──────────────────────────────────────────────────

export class UIAvatar extends UIElement {
  static properties = {
    src:   { type: String,  default: '', reflect: true },
    text:  { type: String,  default: '', reflect: true },
    icon:  { type: String,  default: '', reflect: true },
    size:  { type: String,  default: 'md', reflect: true },
    shape: { type: String,  default: 'circle', reflect: true },
  };

  /** Display string (full name or initials derived from it). */
  get displayName() { return this.text; }

  static template = () => null;

  #imgEl = null;
  #initialsEl = null;
  #iconEl = null;

  connected() {
    this.setAttribute('role', 'img');
  }

  render() {
    if (!this.src && !this.displayName && !this.icon) return;

    if (this.src) {
      if (!this.#imgEl) {
        this.#imgEl = document.createElement('img');
        this.#imgEl.setAttribute('slot', 'img');
        this.#imgEl.onerror = () => {
          this.#imgEl.remove();
          this.#imgEl = null;
          this.#showInitials();
        };
      }
      this.#imgEl.src = this.src;
      this.#imgEl.alt = this.displayName || '';
      if (!this.#imgEl.parentElement) this.appendChild(this.#imgEl);

      // Remove initials when image is showing
      if (this.#initialsEl) {
        this.#initialsEl.remove();
        this.#initialsEl = null;
      }
    } else if (this.icon) {
      // Icon avatar (system events, non-person rep)
      if (this.#imgEl) { this.#imgEl.remove(); this.#imgEl = null; }
      if (this.#initialsEl) { this.#initialsEl.remove(); this.#initialsEl = null; }
      if (!this.#iconEl) {
        this.#iconEl = document.createElement('icon-ui');
        this.#iconEl.setAttribute('slot', 'icon');
        this.appendChild(this.#iconEl);
      }
      this.#iconEl.setAttribute('name', this.icon);
    } else {
      // No src / no icon — show initials
      if (this.#imgEl) { this.#imgEl.remove(); this.#imgEl = null; }
      if (this.#iconEl) { this.#iconEl.remove(); this.#iconEl = null; }
      this.#showInitials();
    }

    this.setAttribute('aria-label', this.displayName || this.icon || '');
  }

  #showInitials() {
    if (!this.displayName) return;
    const initials = this.displayName
      .split(/\s+/)
      .map(w => w[0])
      .join('')
      .slice(0, 2)
      .toUpperCase();

    if (!this.#initialsEl) {
      this.#initialsEl = document.createElement('span');
      this.#initialsEl.setAttribute('slot', 'initials');
      this.appendChild(this.#initialsEl);
    }
    this.#initialsEl.textContent = initials;
  }
}

export class UIAvatarGroup extends UIElement {
  static properties = {
    max:  { type: Number, default: 5, reflect: true },
    size: { type: String, default: '', reflect: true },
  };

  static template = () => null;

  connected() {
    this.setAttribute('role', 'group');
    if (!this.hasAttribute('aria-label')) {
      this.setAttribute('aria-label', 'Avatar group');
    }
  }

  render() {
    const avatars = [...this.querySelectorAll('avatar-ui')];
    const max = this.max;
    const overflow = avatars.length - max;

    // Propagate size
    if (this.size) {
      for (const av of avatars) av.setAttribute('size', this.size);
    }

    // Show/hide based on max
    avatars.forEach((av, i) => {
      av.style.display = i < max ? '' : 'none';
      av.style.zIndex = String(avatars.length - i);
    });

    // Overflow counter
    let counter = this.querySelector('[slot="overflow"]');
    if (overflow > 0) {
      if (!counter) {
        counter = document.createElement('span');
        counter.setAttribute('slot', 'overflow');
        this.appendChild(counter);
      }
      counter.textContent = `+${overflow}`;
      counter.setAttribute('aria-label', `${overflow} more`);
      counter.style.zIndex = '0';
    } else if (counter) {
      counter.remove();
    }
  }
}
