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

import { UIElement, signal, html } from '../../core/element.js';
import { getIcon } from '../../core/icons.js';

export class UIIcon extends UIElement {
  static properties = {
    name:   { type: String, default: '',        reflect: true },
    size:   { type: String, default: '',        reflect: true },
    label:  { type: String, default: '',        reflect: true },
    /** regular | thin | light | bold | fill | duotone */
    weight: { type: String, default: 'regular', reflect: true },
  };

  connected() {
    this.setAttribute('role', this.label ? 'img' : 'presentation');
    if (!this.label) this.setAttribute('aria-hidden', 'true');
  }

  render() {
    if (this.label) this.setAttribute('aria-label', this.label);
    const svg = getIcon(this.name, this.weight || 'regular');
    if (svg && this.innerHTML !== svg) this.innerHTML = svg;

    // Pixel / rem / em passthrough — `size="48"` → 48px,
    // `size="3.5rem"` → 3.5rem. Named-scale values (xs/sm/md/lg/xl/
    // 2xl/3xl/4xl/fill) are handled by `:scope[size="…"]` rules in
    // icon.css; we only set --icon-size inline for free-form values.
    if (this.size && this.#isFreeFormSize(this.size)) {
      this.style.setProperty('--icon-size', this.#normalizeSize(this.size));
    } else if (this.style.getPropertyValue('--icon-size')) {
      this.style.removeProperty('--icon-size');
    }
  }

  #isFreeFormSize(s) {
    return /^\d+(\.\d+)?(px|rem|em)?$/.test(s);
  }

  #normalizeSize(s) {
    return /^\d+(\.\d+)?$/.test(s) ? `${s}px` : s;
  }
}
