/**
 * AvatarGroup - Stacks avatars with overlap and overflow indicator
 * @countermeasure/web-components/display/avatar
 */

import { type AvatarGroupConfig, type AvatarSize } from './types'
import { type Avatar } from './index'
import { resolveContainer } from '../../primitives/utils'

export class AvatarGroup {
  public readonly el: HTMLDivElement

  private readonly maxCount: number | undefined
  private readonly groupSize: AvatarSize
  private avatars: Avatar[] = []
  private overflowEl: HTMLSpanElement | null = null

  constructor(config: AvatarGroupConfig) {
    this.maxCount = config.max
    this.groupSize = config.size ?? 'md'

    this.el = document.createElement('div')
    this.el.className = this.buildClassName(config.className)
    this.el.setAttribute('role', 'group')
    this.el.setAttribute('aria-label', 'Avatar group')

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

  /** Add a single avatar to the group */
  add(avatar: Avatar): void {
    this.avatars.push(avatar)
    this.render()
  }

  /** Replace all avatars in the group */
  setAvatars(avatars: Avatar[]): void {
    this.avatars = [...avatars]
    this.render()
  }

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

  private buildClassName(extra?: string): string {
    const classes = ['cmm-avatar-group', `cmm-avatar-group--${this.groupSize}`]
    if (extra) {
      classes.push(extra)
    }
    return classes.join(' ')
  }

  private render(): void {
    // Clear current content
    this.el.innerHTML = ''
    this.overflowEl = null

    const total = this.avatars.length
    const limit = this.maxCount !== undefined && this.maxCount < total ? this.maxCount : total

    // Add visible avatars
    for (let i = 0; i < limit; i++) {
      const avatar = this.avatars[i]
      if (avatar !== undefined) {
        this.el.appendChild(avatar.el)
      }
    }

    // Add overflow indicator if needed
    const overflow = total - limit
    if (overflow > 0) {
      this.overflowEl = document.createElement('span')
      this.overflowEl.className = 'cmm-avatar-group__overflow'
      this.overflowEl.textContent = `+${String(overflow)}`
      this.overflowEl.setAttribute('aria-label', `${String(overflow)} more`)
      this.el.appendChild(this.overflowEl)
    }
  }
}
