/**
 * PageHeader - Canonical CounterMeasure page title block.
 */

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

export type PageHeaderMetadata = string | HTMLElement

export interface PageHeaderConfig {
  container?: HTMLElement | string
  eyebrow?: string
  title: string
  lede?: string
  metadata?: PageHeaderMetadata[]
  actions?: HTMLElement[]
  tight?: boolean
  className?: string
}

export class PageHeader {
  public readonly el: HTMLElement

  constructor(config: PageHeaderConfig) {
    this.el = document.createElement('header')
    this.el.className = this.buildClassName(config)

    const top = document.createElement('div')
    top.className = 'cmm-page-header__top'

    const copy = document.createElement('div')
    copy.className = 'cmm-page-header__copy'

    if (config.eyebrow !== undefined) {
      const eyebrow = document.createElement('div')
      eyebrow.className = 'cmm-page-header__eyebrow'
      eyebrow.textContent = config.eyebrow
      copy.appendChild(eyebrow)
    }

    const title = document.createElement('h1')
    title.className = `cmm-page-header__title${config.tight === true ? ' cmm-page-header__title--tight' : ''}`
    title.textContent = config.title
    copy.appendChild(title)

    if (config.lede !== undefined) {
      const lede = document.createElement('p')
      lede.className = 'cmm-page-header__lede'
      lede.textContent = config.lede
      copy.appendChild(lede)
    }

    top.appendChild(copy)

    if (config.actions !== undefined && config.actions.length > 0) {
      const actions = document.createElement('div')
      actions.className = 'cmm-page-header__actions'
      for (const action of config.actions) {
        actions.appendChild(action)
      }
      top.appendChild(actions)
    }

    this.el.appendChild(top)

    if (config.metadata !== undefined && config.metadata.length > 0) {
      this.el.appendChild(this.createMetadata(config.metadata))
    }

    if (config.container !== undefined) {
      resolveContainer(config.container).appendChild(this.el)
    }
  }

  private createMetadata(items: PageHeaderMetadata[]): HTMLElement {
    const metadata = document.createElement('div')
    metadata.className = 'cmm-page-header__metadata'

    for (const item of items) {
      const node = document.createElement('span')
      node.className = 'cmm-page-header__metadata-item'
      if (typeof item === 'string') {
        node.textContent = item
      } else {
        node.appendChild(item)
      }
      metadata.appendChild(node)
    }

    return metadata
  }

  private buildClassName(config: PageHeaderConfig): string {
    return ['cmm-page-header', config.className].filter(Boolean).join(' ')
  }
}

export function createPageHeader(config: PageHeaderConfig): HTMLElement {
  return new PageHeader(config).el
}
