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

/**
 * <search-ui placeholder="Search..."></search-ui>
 * <search-ui debounce="500"></search-ui>
 *
 * Search input with magnifying-glass icon, clear button, and debounce.
 * Composes input-ui internally — no raw <input> stamping.
 * Fires debounced 'search' event. Clear button resets and fires immediately.
 */

import { UIFormElement } from '../../core/form.js';

export class UISearch extends UIFormElement {
  static properties = {
    ...UIFormElement.properties,
    placeholder: { type: String, default: 'Search...', reflect: true },
    debounce:    { type: Number, default: 300, reflect: true },
  };

  static template = () => null;

  #inputEl = null;
  #suffixEl = null;
  #timer = null;

  connected() {
    super.connected();
    this.setAttribute('role', 'search');

    if (!this.querySelector('input-ui')) {
      const size = this.getAttribute('size');
      this.innerHTML = `<input-ui
        type="search"
        prefix="magnifying-glass"
        suffix="x-circle"
        placeholder="${this.placeholder}"
        ${this.disabled ? 'disabled' : ''}
        ${size ? `size="${size}"` : ''}
      ></input-ui>`;
    }

    this.#inputEl = this.querySelector('input-ui');
    if (this.#inputEl) {
      this.#inputEl.addEventListener('input', this.#onInput);
      this.#inputEl.addEventListener('keydown', this.#onKeydown);
      this.#suffixEl = this.#inputEl.querySelector('[slot="suffix"]');
      if (this.#suffixEl) {
        this.#suffixEl.style.cursor = 'pointer';
        this.#suffixEl.addEventListener('click', this.#onClear);
      }
    }
  }

  render() {
    if (!this.#inputEl) return;

    this.#inputEl.setAttribute('placeholder', this.placeholder);
    if (this.disabled) this.#inputEl.setAttribute('disabled', '');
    else this.#inputEl.removeAttribute('disabled');

    // Reflect value for CSS (clear button visibility)
    this.setAttribute('value', this.value || '');
  }

  #onInput = () => {
    this.value = this.#inputEl.value;
    this.syncValue(this.value);
    this.dispatchEvent(new CustomEvent('input', { bubbles: true, detail: { value: this.value } }));
    this.dispatchEvent(new CustomEvent('change', { bubbles: true, detail: { value: this.value } }));

    clearTimeout(this.#timer);
    this.#timer = setTimeout(() => {
      this.dispatchEvent(new CustomEvent('search', {
        bubbles: true,
        detail: { value: this.value },
      }));
    }, this.debounce || 300);
  };

  #onKeydown = (e) => {
    if (e.key === 'Enter') {
      clearTimeout(this.#timer);
      this.dispatchEvent(new CustomEvent('search', {
        bubbles: true,
        detail: { value: this.value },
      }));
    }
    if (e.key === 'Escape') {
      this.#onClear();
    }
  };

  #onClear = () => {
    clearTimeout(this.#timer);
    this.value = '';
    if (this.#inputEl) this.#inputEl.value = '';
    this.syncValue('');
    this.setAttribute('value', '');
    this.dispatchEvent(new CustomEvent('input', { bubbles: true, detail: { value: this.value } }));
    this.dispatchEvent(new CustomEvent('change', { bubbles: true, detail: { value: this.value } }));
    this.dispatchEvent(new CustomEvent('search', {
      bubbles: true,
      detail: { value: '' },
    }));
    this.#inputEl?.focus();
  };

  focus() { this.#inputEl?.focus(); }

  clear() { this.#onClear(); }

  disconnected() {
    super.disconnected();
    clearTimeout(this.#timer);
    this.#timer = null;
    if (this.#inputEl) {
      this.#inputEl.removeEventListener('input', this.#onInput);
      this.#inputEl.removeEventListener('keydown', this.#onKeydown);
    }
    if (this.#suffixEl) {
      this.#suffixEl.removeEventListener('click', this.#onClear);
    }
    this.#inputEl = null;
    this.#suffixEl = null;
  }
}
