import onFind from './dom/onFind'

/*
  Copies the progress stats label and inserts it after the percentage label.

  From:
  -------------------------
  | RPB || working info |
  | RPB ||progress stats|
  ------------------------

  To:
  ------------------------------
  |progress % (new)|
  |working info|
  |progress bar (visible in v5)|
  |progress stats|
  ------------------------------
*/
onFind('.DashboardWidget.p-workStreams .block', (workstream) => {
  const stats = workstream.querySelector('.progress .progress-stats-label')
  if (!stats) return
  const statsCopy = stats.cloneNode(true)
  if (statsCopy instanceof HTMLElement) {
    statsCopy.classList.add('v5-only')
    statsCopy.classList.remove('v4-contents-only')
    workstream.append(statsCopy)
  }

  // Also makes progress bar visible in v5
  const bar = workstream.querySelector('.progressBar')
  if (!bar) return
  bar.classList.remove('hidden')
  bar.removeAttribute('hidden')

  // Animate workstream when it's in view.
  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add('animated')
          observer.unobserve(entry.target)
        }
      })
    },
    {
      threshold: 0.5,
    },
  )

  observer.observe(workstream)
})
