import onFind from './dom/onFind'

/**
 * Adds runtime classes to Widget elements based on their crosslinker form descendants.
 * This replaces expensive :has() selectors for better performance.
 *
 * Performance considerations:
 * - onFind callbacks execute once per element (via unique data attributes)
 * - Classes added at page load and when new widgets are dynamically added
 * - No recalculation needed unlike :has() selectors which recalculate on every DOM mutation
 * - Single-pass approach reduces DOM traversals
 *
 * Original expensive selectors:
 * - .Widget:has(> form[action*='crosslinker/dictionaries'] .ActionBar)
 * - .Widget:has(form[action*='crosslinker/mappings'])
 *
 * New performant selectors:
 * - .Widget.has-crosslinker-dictionaries .ActionBar
 * - .Widget.has-crosslinker-mappings
 */

/**
 * Single-pass Widget classification for crosslinker forms.
 * More efficient than multiple onFind callbacks - one DOM traversal per Widget.
 */
onFind('.Widget', (widget: HTMLElement) => {
  // Check for dictionaries form (direct child with ActionBar)
  // Original selector: .Widget:has(> form[action*='crosslinker/dictionaries'] .ActionBar)
  const dictionariesForm = widget.querySelector<HTMLElement>(
    ':scope > form[action*="crosslinker/dictionaries"]',
  )

  if (dictionariesForm) {
    // Verify the form contains an ActionBar (matching original :has() logic)
    const hasActionBar = dictionariesForm.querySelector('.ActionBar')
    if (hasActionBar) {
      widget.classList.add('has-crosslinker-dictionaries')
    }
  }

  // Check for mappings form (any descendant)
  // Original selector: .Widget:has(form[action*='crosslinker/mappings'])
  if (widget.querySelector('form[action*="crosslinker/mappings"]')) {
    widget.classList.add('has-crosslinker-mappings')
  }
})
