/**
 * ButtonGroup - Groups buttons into a connected visual unit
 * @countermeasure/web-components/primitives/button
 */

import { type ButtonGroupConfig } from './types'
import { type Button } from './index'
import { resolveContainer } from '../utils'

export class ButtonGroup {
  public readonly el: HTMLDivElement

  constructor(config: ButtonGroupConfig) {
    const orientation = config.orientation ?? 'horizontal'

    this.el = document.createElement('div')
    this.el.className = `cmm-btn-group cmm-btn-group--${orientation}`
    this.el.setAttribute('role', 'group')

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

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

  /** Add a button to the group */
  add(button: Button): void {
    this.el.appendChild(button.el)
  }

  /** Remove a button from the group */
  remove(button: Button): void {
    if (this.el.contains(button.el)) {
      this.el.removeChild(button.el)
    }
  }

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