/**
 * Spinner - Loading indicator component
 * @countermeasure/web-components/primitives/spinner
 */

import { resolveContainer } from '../utils'

export type SpinnerSize = 'sm' | 'md' | 'lg'

export interface SpinnerConfig {
  container?: HTMLElement | string
  size?: SpinnerSize
  className?: string
}

export class Spinner {
  public readonly el: HTMLSpanElement

  private currentSize: SpinnerSize

  constructor(config: SpinnerConfig) {
    this.currentSize = config.size ?? 'md'

    // Create the spinner wrapper
    this.el = document.createElement('span')
    this.el.className = `cmm-spinner cmm-spinner--${this.currentSize}`
    this.el.setAttribute('role', 'status')

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

    // Create the spinning circle
    const circle = document.createElement('span')
    circle.className = 'cmm-spinner__circle'
    circle.setAttribute('aria-hidden', 'true')
    this.el.appendChild(circle)

    // Create screen reader text
    const srText = document.createElement('span')
    srText.className = 'sr-only'
    srText.textContent = 'Loading...'
    this.el.appendChild(srText)

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

  /** Change the spinner size */
  setSize(size: SpinnerSize): void {
    this.el.classList.remove(`cmm-spinner--${this.currentSize}`)
    this.currentSize = size
    this.el.classList.add(`cmm-spinner--${this.currentSize}`)
  }

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