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

/**
 * <segment-ui value="tab1" text="Tab 1" icon="list"></segment-ui>
 * Child of segmented-ui. Represents one option.
 *
 * `icon=` stamps a leading <icon-ui name="…"> child on render.
 * Mirrors the button-ui pattern.
 */

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

export class UISegment extends UIElement {
  static properties = {
    value:    { type: String, default: '', reflect: true },
    text:     { type: String, default: '', reflect: true },
    icon:     { type: String, default: '', reflect: true },
    disabled: { type: Boolean, default: false, reflect: true },
    selected: { type: Boolean, default: false, reflect: true },
  };

  static template = () => null;

  connected() {
    this.setAttribute('role', 'radio');
    if (!this.getAttribute('tabindex')) this.setAttribute('tabindex', '-1');
  }

  render() {
    if (this.text) this.setAttribute('aria-label', this.text);
    this.setAttribute('aria-checked', this.selected ? 'true' : 'false');
    if (this.disabled) this.setAttribute('aria-disabled', 'true');
    else this.removeAttribute('aria-disabled');

    // Stamp/refresh leading icon-ui child when [icon] is set.
    // Mirrors button-ui's pattern (button.js:29) — author code never
    // hand-rolls an icon-ui inside a segment.
    if (this.icon) {
      const existing = this.querySelector(':scope > icon-ui');
      if (!existing || existing.getAttribute('name') !== this.icon) {
        existing?.remove();
        const iconEl = document.createElement('icon-ui');
        iconEl.setAttribute('name', this.icon);
        iconEl.setAttribute('aria-hidden', 'true');
        this.prepend(iconEl);
      }
    } else {
      this.querySelector(':scope > icon-ui')?.remove();
    }
  }
}
