import onFind from './dom/onFind'
import previousUntil from './dom/previousUntil'

// Mark the CIG empty if there aren't any rows in it.
const toggleEmpty = (group: Element) => {
  const rows = Array.from(
    group.querySelectorAll(
      ':scope > *.CIG-row, :scope > *[data-tab], :scope > .TemplateField, :scope > .RCIG > .RCIG-list > li',
    ),
  ).filter((row) => row.childNodes.length)

  group.classList.toggle('is-empty', !rows.length)
}

onFind('.CIG', toggleEmpty)

window.addEventListener('brightspot-content-state-change', ({ target }) => {
  if (!(target instanceof HTMLElement)) return
  for (const group of target.querySelectorAll('.CIG')) {
    toggleEmpty(group)
  }
})

// Move CIG-title to be more consistently placed.
onFind(['.CIG > h2', '.CIG-row > h2'], (heading: HTMLElement) => {
  const row = heading.parentNode
  if (!(row instanceof HTMLElement)) return
  const tab = row.dataset.tab

  if (tab) {
    row.parentNode?.insertBefore(heading, row)
    heading.dataset.tab = tab
  }

  heading.removeAttribute('style')
  heading.classList.add('CIG-title')
})

// Highlight the title of the cluster when one of its fields has an error.
onFind('.CIG-row > .Message.is-error', (message) => {
  let row: HTMLElement | null = null

  let r = message.closest('.CIG-row, .RCIG-item')
  while (r instanceof HTMLElement && r.parentNode instanceof HTMLElement) {
    r.classList.add('is-error')
    row = r
    r = r.parentNode.closest('.CIG-row, .RCIG-item')
  }

  if (!row) return
  const title = previousUntil(row, '.CIG-title')

  if (title instanceof HTMLElement && row.dataset.tab === title.dataset.tab) {
    title.classList.add('is-error')
  }
})

// Keeps guide icon active when popup open
// TODO: add same functionality for .CIG-guide
onFind('.CIG-help', (help) => {
  help.addEventListener('click', () => {
    const toolTip = document.querySelector('.CIG-row.is-openPopup')
    if (toolTip) toolTip.classList.remove('is-openPopup')
    help.closest('.CIG-row')?.classList.add('is-openPopup')
  })
})

// dynamic label on Duration and Period collection fields.
const updatePeriodLabel = (item: HTMLElement) => {
  const dataType = item.dataset.type
  const label = Array.from(
    item.querySelectorAll('input'),
    (i) => i.value || 0,
  ).join('-')

  const repeatableLabel = item.querySelector('.repeatableLabel')
  if (repeatableLabel) {
    repeatableLabel.innerHTML = `${dataType}: ${label}`
  }
}

onFind(
  '.CIG-row[data-type$="/duration"] > .RCIG li, .CIG-row[data-type$="/period"] > .RCIG li',
  (item: HTMLElement) =>
    item.addEventListener('change', () => updatePeriodLabel(item)),
)
