/**
 * AspectRatio - Container that maintains a specific aspect ratio
 * @countermeasure/web-components/display/aspect-ratio
 */

import { resolveContainer } from '../../primitives/utils'

export interface AspectRatioConfig {
  container?: HTMLElement | string
  ratio?: number
  className?: string
}

export class AspectRatio {
  public readonly el: HTMLDivElement

  private readonly contentEl: HTMLDivElement

  constructor(config: AspectRatioConfig) {
    const ratio = config.ratio ?? 1

    // Create root element
    this.el = document.createElement('div')
    this.el.className = 'cmm-aspect-ratio'
    this.el.style.setProperty('--cmm-aspect-ratio', String(ratio))

    if (config.className) {
      this.el.classList.add(config.className)
    }

    // Content container
    this.contentEl = document.createElement('div')
    this.contentEl.className = 'cmm-aspect-ratio__content'
    this.el.appendChild(this.contentEl)

    // Mount if container provided
    if (config.container !== undefined) {
      const parent = resolveContainer(config.container)
      parent.appendChild(this.el)
    }
  }

  /** Returns the content div for mounting children */
  getContent(): HTMLDivElement {
    return this.contentEl
  }

  /** Update the aspect ratio */
  setRatio(ratio: number): void {
    this.el.style.setProperty('--cmm-aspect-ratio', String(ratio))
  }

  /** Remove from the DOM */
  destroy(): void {
    this.el.remove()
  }
}
