/**
 * AppShell - Lightweight layout composition for app chrome.
 */

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

export interface AppShellConfig {
  container?: HTMLElement | string
  sidebar?: HTMLElement
  header?: HTMLElement
  content?: HTMLElement
  metrics?: HTMLElement
  className?: string
}

export class AppShell {
  public readonly el: HTMLElement
  public readonly mainEl: HTMLElement
  public readonly contentEl: HTMLElement

  constructor(config: AppShellConfig = {}) {
    this.el = document.createElement('div')
    this.el.className = ['cmm-app-shell', config.className].filter(Boolean).join(' ')

    if (config.sidebar !== undefined) {
      const sidebarSlot = document.createElement('aside')
      sidebarSlot.className = 'cmm-app-shell__sidebar'
      sidebarSlot.appendChild(config.sidebar)
      this.el.appendChild(sidebarSlot)
    }

    this.mainEl = document.createElement('div')
    this.mainEl.className = 'cmm-app-shell__main'

    if (config.header !== undefined) {
      this.mainEl.appendChild(config.header)
    }

    this.contentEl = document.createElement('main')
    this.contentEl.className = 'cmm-app-shell__content'

    if (config.metrics !== undefined) {
      const metrics = document.createElement('div')
      metrics.className = 'cmm-app-shell__metric-strip'
      metrics.appendChild(config.metrics)
      this.contentEl.appendChild(metrics)
    }

    if (config.content !== undefined) {
      this.contentEl.appendChild(config.content)
    }

    this.mainEl.appendChild(this.contentEl)
    this.el.appendChild(this.mainEl)

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

export function createAppShell(config: AppShellConfig = {}): HTMLElement {
  return new AppShell(config).el
}
