/**
 * DetailHeader component - title, subtitle, status badge, action buttons
 * @countermeasure/web-components/components/detail-header
 */

export interface DetailHeaderAction {
  label: string
  onClick: () => void
  variant?: 'default' | 'ghost' | 'destructive'
  disabled?: boolean
}

import { escapeHtml } from '../../utils/sanitize'

export interface DetailHeaderConfig {
  container: HTMLElement | string
  title: string
  subtitle?: string
  status?: {
    label: string
    variant?: 'success' | 'error' | 'warning' | 'info' | 'default'
    dot?: boolean
  }
  actions?: DetailHeaderAction[]
  breadcrumbs?: { label: string; href?: string }[]
}

function resolveContainer(container: HTMLElement | string): HTMLElement {
  if (typeof container === 'string') {
    const el = document.querySelector(container)
    if (!el) {
      throw new Error(`DetailHeader: container not found for selector "${container}"`)
    }
    return el as HTMLElement
  }
  return container
}

function isSafeHref(href: string): boolean {
  if (
    href.startsWith('/') ||
    href.startsWith('./') ||
    href.startsWith('../') ||
    href.startsWith('?') ||
    href.startsWith('#')
  ) {
    return !href.startsWith('//')
  }

  try {
    const parsed = new URL(href)
    return parsed.protocol === 'http:' || parsed.protocol === 'https:'
  } catch {
    return false
  }
}

export class DetailHeader {
  private readonly containerEl: HTMLElement
  private readonly rootEl: HTMLElement
  private readonly titleEl: HTMLElement
  private readonly subtitleEl: HTMLElement
  private readonly statusEl: HTMLElement
  private readonly actionsEl: HTMLElement
  private readonly breadcrumbEl: HTMLElement | null
  private destroyed = false

  constructor(config: DetailHeaderConfig) {
    this.containerEl = resolveContainer(config.container)

    this.rootEl = document.createElement('div')
    this.rootEl.className = 'cmm-detail-header'

    // Breadcrumb (optional)
    if (config.breadcrumbs && config.breadcrumbs.length > 0) {
      this.breadcrumbEl = document.createElement('nav')
      this.breadcrumbEl.className = 'cmm-detail-header__breadcrumb'
      this.renderBreadcrumbs(config.breadcrumbs)
      this.containerEl.appendChild(this.breadcrumbEl)
    } else {
      this.breadcrumbEl = null
    }

    // Main header row
    const left = document.createElement('div')
    left.className = 'cmm-detail-header__left'

    this.titleEl = document.createElement('h2')
    this.titleEl.className = 'cmm-detail-header__title'
    this.titleEl.textContent = config.title
    left.appendChild(this.titleEl)

    this.subtitleEl = document.createElement('div')
    this.subtitleEl.className = 'cmm-detail-header__subtitle'
    if (config.subtitle) this.subtitleEl.textContent = config.subtitle
    left.appendChild(this.subtitleEl)

    this.rootEl.appendChild(left)

    // Right side: actions + status
    const right = document.createElement('div')
    right.className = 'cmm-detail-header__right'

    this.actionsEl = document.createElement('div')
    this.actionsEl.className = 'cmm-detail-header__actions'
    if (config.actions) this.renderActions(config.actions)
    right.appendChild(this.actionsEl)

    this.statusEl = document.createElement('span')
    this.statusEl.className = 'cmm-detail-header__status'
    if (config.status) this.renderStatus(config.status)
    right.appendChild(this.statusEl)

    this.rootEl.appendChild(right)
    this.containerEl.appendChild(this.rootEl)
  }

  setTitle(title: string): void {
    this.titleEl.textContent = title
  }

  setSubtitle(subtitle: string): void {
    this.subtitleEl.textContent = subtitle
  }

  setStatus(status: DetailHeaderConfig['status']): void {
    if (status) {
      this.renderStatus(status)
    } else {
      this.statusEl.innerHTML = ''
    }
  }

  setActions(actions: DetailHeaderAction[]): void {
    this.renderActions(actions)
  }

  destroy(): void {
    if (this.destroyed) return
    this.destroyed = true
    if (this.breadcrumbEl?.parentNode) this.breadcrumbEl.parentNode.removeChild(this.breadcrumbEl)
    if (this.rootEl.parentNode) this.rootEl.parentNode.removeChild(this.rootEl)
  }

  private renderBreadcrumbs(items: { label: string; href?: string }[]): void {
    if (!this.breadcrumbEl) return
    const fragment = document.createDocumentFragment()

    for (const [index, item] of items.entries()) {
      const isLast = index === items.length - 1
      if (isLast) {
        const current = document.createElement('span')
        current.className = 'cmm-detail-header__breadcrumb-current'
        current.textContent = item.label
        fragment.appendChild(current)
      } else if (item.href && isSafeHref(item.href)) {
        const link = document.createElement('a')
        link.className = 'cmm-detail-header__breadcrumb-link'
        link.textContent = item.label
        link.setAttribute('href', item.href)
        fragment.appendChild(link)
      } else {
        const label = document.createElement('span')
        label.textContent = item.label
        fragment.appendChild(label)
      }

      if (!isLast) {
        const sep = document.createElement('span')
        sep.className = 'cmm-detail-header__breadcrumb-sep'
        sep.textContent = '/'
        fragment.appendChild(sep)
      }
    }

    this.breadcrumbEl.replaceChildren(fragment)
  }

  private renderStatus(status: NonNullable<DetailHeaderConfig['status']>): void {
    const variant = status.variant ?? 'default'
    const dot =
      status.dot !== false
        ? `<span class="cmm-detail-header__status-dot cmm-detail-header__status-dot--${variant}"></span>`
        : ''
    this.statusEl.className = `cmm-detail-header__status cmm-detail-header__status--${variant}`
    this.statusEl.innerHTML = `${dot}${escapeHtml(status.label)}`
  }

  private renderActions(actions: DetailHeaderAction[]): void {
    this.actionsEl.innerHTML = ''
    for (const action of actions) {
      const btn = document.createElement('button')
      const variant = action.variant ?? 'ghost'
      btn.className = `cmm-detail-header__action-btn cmm-detail-header__action-btn--${variant}`
      btn.textContent = action.label
      if (action.disabled) btn.disabled = true
      btn.addEventListener('click', action.onClick)
      this.actionsEl.appendChild(btn)
    }
  }
}
