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

/**
 * <check-ui> — Checkbox. The host IS the control.
 * Pure CSS checkmark via border trick on [slot="box"]::after. No SVG.
 */

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

export class UICheck extends UIFormElement {
  static labelDeprecated = false;  // §170 (v0.5.4): label is first-class per check.yaml
  static properties = {
    ...UIFormElement.properties,
    checked:       { type: Boolean, default: false, reflect: true },
    indeterminate: { type: Boolean, default: false, reflect: true },
    label:         { type: String,  default: '', reflect: true },
  };

  static template = () => html`<span slot="box"></span>`;

  connected() {
    super.connected();
    this.setAttribute('role', 'checkbox');
    this.setAttribute('tabindex', '0');
    this.addEventListener('click', this.#toggle);
    this.addEventListener('keydown', this.#onKey);
  }

  render() {
    if (this.indeterminate) {
      this.setAttribute('aria-checked', 'mixed');
    } else {
      this.setAttribute('aria-checked', String(this.checked));
    }
    if (this.disabled) this.setAttribute('aria-disabled', 'true');
    else this.removeAttribute('aria-disabled');
    if (this.label) this.setAttribute('aria-label', this.label);
    this.syncValue(this.checked ? (this.value || 'on') : '');
  }

  #toggle = () => {
    if (this.disabled) return;
    this.checked = !this.checked;
    this.indeterminate = false;
    this.dispatchEvent(new CustomEvent('change', { bubbles: true, detail: { value: this.value, checked: this.checked } }));
  };

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

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