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

/**
 * <agent-suggestions-ui> — Row of follow-up suggestion chips.
 *
 * The agent proposes 2-4 next-step prompts; user picks one. The host listens
 * for `suggestion-select` and dispatches the associated prompt.
 *
 * JS API:
 *   el.suggestions = [
 *     { label: 'Add price comparison' },                    // label === prompt
 *     { label: 'Add quantity stepper', prompt: 'add a stepper' },
 *     { label: 'Variants picker',       prompt: 'add a variants picker', icon: 'tag' },
 *   ];
 *
 *   el.addEventListener('suggestion-select', (e) => {
 *     submit(e.detail.prompt);
 *   });
 *
 * Attributes:
 *   variant   — outline (default) | ghost | subtle
 *   size      — sm (default) | md
 *   disabled  — disable all chips
 *
 * Events:
 *   suggestion-select — detail: { label, prompt, index }
 */

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

function truncate(s, n) {
  if (typeof s !== 'string') return '';
  return s.length > n ? s.slice(0, n - 1) + '…' : s;
}

export class UIAgentSuggestions extends UIElement {
  static properties = {
    variant:  { type: String,  default: 'outline', reflect: true },
    size:     { type: String,  default: 'sm',      reflect: true },
    disabled: { type: Boolean, default: false,     reflect: true },
  };

  static template = () => null;

  #suggestions = [];

  get suggestions() { return this.#suggestions; }
  set suggestions(v) {
    this.#suggestions = Array.isArray(v) ? v.slice() : [];
    this.#render();
  }

  connected() {
    this.#render();
  }

  disconnected() {
    this.innerHTML = '';
  }

  #render() {
    this.innerHTML = '';
    for (let i = 0; i < this.#suggestions.length; i++) {
      const s = this.#suggestions[i];
      const label = typeof s === 'string' ? s : s.label || s.prompt || '';
      const prompt = typeof s === 'string' ? s : s.prompt || s.label || '';
      const icon = typeof s === 'object' ? s.icon : null;

      const chip = document.createElement('button-ui');
      chip.setAttribute('text', truncate(label, 42));
      chip.setAttribute('variant', this.variant);
      chip.setAttribute('size', this.size);
      if (icon) chip.setAttribute('icon', icon);
      if (this.disabled) chip.setAttribute('disabled', '');

      chip.addEventListener('press', () => {
        if (this.disabled) return;
        this.dispatchEvent(new CustomEvent('suggestion-select', {
          bubbles: true,
          detail: { label, prompt, index: i },
        }));
      });
      this.appendChild(chip);
    }
  }
}
