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

/**
 * <embed-ui src="https://example.com" height="400" aspect="16/9"></embed-ui>
 *
 * Responsive sandboxed iframe wrapper.
 *
 * Properties:
 *   src    — iframe URL
 *   height — iframe height (default '400')
 *   width  — iframe width (default '100%')
 *   aspect — optional CSS aspect-ratio (e.g. '16/9')
 */

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

export class UIEmbed extends UIElement {
  static properties = {
    src:    { type: String,  default: '', reflect: true },
    height: { type: String,  default: '400', reflect: true },
    width:  { type: String,  default: '100%', reflect: true },
    aspect: { type: String,  default: '', reflect: true },
  };

  static template = () => null;

  #iframe = null;

  connected() {
    if (!this.#iframe) {
      this.#iframe = document.createElement('iframe');
      this.#iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin');
      this.#iframe.setAttribute('loading', 'lazy');
      this.#iframe.setAttribute('allowfullscreen', '');
      this.appendChild(this.#iframe);
    }
  }

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

    if (this.src) this.#iframe.src = this.src;

    if (this.aspect) {
      this.style.aspectRatio = this.aspect;
      this.#iframe.style.width = '100%';
      this.#iframe.style.height = '100%';
      this.style.width = this.width;
      this.style.height = '';
    } else {
      this.style.aspectRatio = '';
      this.#iframe.style.width = '100%';
      this.#iframe.style.height = this.height.match(/^\d+$/) ? `${this.height}px` : this.height;
      this.style.width = this.width;
      this.style.height = '';
    }
  }

  disconnected() {
    this.#iframe = null;
  }
}
