/**
 * Skeleton - Loading placeholder component
 * @countermeasure/web-components/primitives/skeleton
 */

import { resolveContainer } from '../utils'

export type SkeletonVariant = 'text' | 'circular' | 'rectangular'

export interface SkeletonConfig {
  container?: HTMLElement | string
  variant?: SkeletonVariant
  width?: string
  height?: string
  className?: string
}

export class Skeleton {
  public readonly el: HTMLDivElement

  constructor(config: SkeletonConfig) {
    const variant = config.variant ?? 'text'

    // Create the skeleton element
    this.el = document.createElement('div')
    this.el.className = `cmm-skeleton cmm-skeleton--${variant}`
    this.el.setAttribute('aria-hidden', 'true')

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

    if (config.width !== undefined) {
      this.el.style.width = config.width
    }

    if (config.height !== undefined) {
      this.el.style.height = config.height
    }

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

  /** Update the skeleton dimensions */
  setSize(width: string, height: string): void {
    this.el.style.width = width
    this.el.style.height = height
  }

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