// ITS-Böhmer Mobile Navigation
// Loads on all pages; replaces inline mobile nav JS that previously lived in homeExperience.ts

;(function () {
  const hamburger = document.getElementById('navHamburger')
  const mobileNav = document.getElementById('mobileNav')
  const mediaQuery = window.matchMedia('(max-width: 900px)')
  const MOBILE_NAV_OPEN_EVENT = 'itsb:mobile-nav-open'
  const MOBILE_NAV_CLOSE_EVENT = 'itsb:mobile-nav-close'

  if (!hamburger || !mobileNav) return

  const ensureBackdrop = () => {
    let backdrop = document.querySelector<HTMLButtonElement>('[data-mobile-nav-backdrop]')
    if (backdrop) return backdrop

    backdrop = document.createElement('button')
    backdrop.type = 'button'
    backdrop.className = 'mobile-nav-backdrop'
    backdrop.dataset.mobileNavBackdrop = 'true'
    backdrop.setAttribute('aria-label', 'Navigation schließen')
    mobileNav.insertAdjacentElement('afterend', backdrop)
    backdrop.addEventListener('click', () => setNavOpen(false))
    return backdrop
  }

  const backdrop = ensureBackdrop()
  let returnFocusAfterClose = false

  const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)')

  hamburger.setAttribute('aria-controls', 'mobileNav')
  hamburger.setAttribute('aria-expanded', 'false')
  hamburger.innerHTML = '<span></span><span></span><span></span><i aria-hidden="true"></i>'

  const focusableSelector = 'a, button, [tabindex]:not([tabindex="-1"])'
  const focusableNodes = () => Array.from(mobileNav.querySelectorAll<HTMLElement>(focusableSelector))
    .filter((node) => !node.hasAttribute('hidden') && !node.closest<HTMLElement>('.mobile-submenu:not(.open)'))
  const firstFocusable = () => focusableNodes()[0] || null
  const lastFocusable = () => {
    const nodes = focusableNodes()
    return nodes[nodes.length - 1] || null
  }

  const setNavOpen = (open: boolean) => {
    const shouldOpen = open && mediaQuery.matches
    const chatWidget = document.querySelector<HTMLElement>('.chat-widget')
    if (shouldOpen && chatWidget) {
      chatWidget.dispatchEvent(new CustomEvent('chat:close'))
    }
    document.dispatchEvent(new CustomEvent(shouldOpen ? MOBILE_NAV_OPEN_EVENT : MOBILE_NAV_CLOSE_EVENT))
    document.documentElement.classList.toggle('mobile-nav-is-open', shouldOpen)
    if (shouldOpen) {
      returnFocusAfterClose = document.activeElement === hamburger || mobileNav.contains(document.activeElement)
      mobileNav.scrollTop = 0
      mobileNav.querySelectorAll<HTMLAnchorElement>(':scope > a').forEach((link, index) => {
        link.style.setProperty('--nav-i', String(index))
      })
    }
    if (shouldOpen && !mobileNav.dataset.ready) {
      mobileNav.dataset.ready = 'true'
      mobileNav.querySelectorAll<HTMLAnchorElement>('a').forEach((a) => {
        a.setAttribute('tabindex', '0')
      })
    }
    hamburger.classList.toggle('open', shouldOpen)
    mobileNav.classList.toggle('open', shouldOpen)
    backdrop.classList.toggle('open', shouldOpen)
    hamburger.setAttribute('aria-expanded', String(shouldOpen))
    hamburger.setAttribute(
      'aria-label',
      shouldOpen ? 'Navigation schließen' : 'Navigation öffnen',
    )
    // inert is ideal for modern browsers; aria-hidden/tabindex fallback keeps
    // older mobile WebViews from tabbing into the closed off-canvas menu.
    mobileNav.toggleAttribute('inert', !shouldOpen)
    mobileNav.setAttribute('aria-hidden', String(!shouldOpen))
    backdrop.toggleAttribute('hidden', !shouldOpen)
    backdrop.setAttribute('aria-hidden', String(!shouldOpen))
    mobileNav.querySelectorAll<HTMLAnchorElement>('a').forEach((a) => {
      const closedSubmenu = a.closest<HTMLElement>('.mobile-submenu:not(.open)')
      if (shouldOpen && !closedSubmenu) a.removeAttribute('tabindex')
      else a.setAttribute('tabindex', '-1')
    })
    // Trap scroll in mobile nav when open without losing the previous inline value.
    if (shouldOpen) {
      if (!document.body.dataset.navPreviousOverflow) {
        document.body.dataset.navPreviousOverflow = document.body.style.overflow || 'auto'
      }
      document.body.classList.add('mobile-nav-open')
      document.body.style.overflow = 'hidden'
    } else {
      const previousOverflow = document.body.dataset.navPreviousOverflow
      document.body.classList.remove('mobile-nav-open')
      document.body.style.overflow = previousOverflow === 'auto' ? '' : previousOverflow || ''
      delete document.body.dataset.navPreviousOverflow
      if (returnFocusAfterClose && mediaQuery.matches && document.contains(hamburger)) {
        hamburger.focus({ preventScroll: true })
      }
      returnFocusAfterClose = false
    }
  }

  mobileNav.setAttribute('tabindex', '-1')
  mobileNav.setAttribute('aria-hidden', 'true')
  mobileNav.toggleAttribute('inert', true)
  backdrop.hidden = true
  backdrop.setAttribute('aria-hidden', 'true')
  mobileNav.querySelectorAll<HTMLAnchorElement>('a').forEach((a) => a.setAttribute('tabindex', '-1'))

  hamburger.addEventListener('click', () => {
    setNavOpen(!mobileNav.classList.contains('open'))
    if (mobileNav.classList.contains('open')) {
      requestAnimationFrame(() => mobileNav.focus({ preventScroll: true }))
    }
  })

  mobileNav.addEventListener('click', (e) => {
    const target = e.target as HTMLElement
    if (target.closest('[data-chat-trigger]')) {
      setNavOpen(false)
    }
  })

  // Submenu toggle on mobile parent links
  mobileNav.querySelectorAll<HTMLAnchorElement>('.mobile-parent').forEach((link) => {
    const subId = link.dataset.submenu
    if (subId) {
      link.setAttribute('aria-controls', subId)
      link.setAttribute('aria-expanded', 'false')
    }

    link.addEventListener('click', (e) => {
      e.preventDefault()
      const subId = link.dataset.submenu
      if (!subId) return
      const sub = document.getElementById(subId)
      if (!sub) return
      const isOpen = sub.classList.toggle('open')
      link.classList.toggle('open', isOpen)
      link.setAttribute('aria-expanded', String(isOpen))
      sub.toggleAttribute('hidden', !isOpen)
      sub.setAttribute('aria-hidden', String(!isOpen))
      sub.querySelectorAll<HTMLAnchorElement>('a').forEach((a) => {
        if (isOpen && mobileNav.classList.contains('open')) a.removeAttribute('tabindex')
        else a.setAttribute('tabindex', '-1')
      })
      if (isOpen && !prefersReducedMotion.matches) {
        sub.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
      }
    })
  })

  mobileNav.querySelectorAll<HTMLElement>('.mobile-submenu').forEach((sub) => {
    sub.toggleAttribute('hidden', true)
    sub.setAttribute('aria-hidden', 'true')
    sub.querySelectorAll<HTMLAnchorElement>('a').forEach((a) => a.setAttribute('tabindex', '-1'))
  })

  // Submenu item clicks: stop propagation so they don't bubble to the
  // parent .mobile-parent anchor (which would retoggle the submenu).
  mobileNav.querySelectorAll<HTMLAnchorElement>('.mobile-submenu a').forEach((link) => {
    link.addEventListener('click', (e) => {
      e.stopPropagation()
      // Still close the nav after navigation
      returnFocusAfterClose = false
      setNavOpen(false)
    })
  })

  // Close on regular link click
  mobileNav.querySelectorAll('a').forEach((a) => {
    a.addEventListener('click', () => {
      if (!a.classList.contains('mobile-parent')) {
        returnFocusAfterClose = false
        setNavOpen(false)
      }
    })
  })

  // Close on outside click, viewport change, Escape key and browser back
  document.addEventListener('click', (e) => {
    const target = e.target as Node
    if (!mobileNav.classList.contains('open')) return
    if (mobileNav.contains(target) || hamburger.contains(target)) return
    returnFocusAfterClose = false
    setNavOpen(false)
  })

  const handleViewportChange = () => setNavOpen(false)
  mediaQuery.addEventListener('change', handleViewportChange)

  // Close on browser back button (mobile swipe-to-go-back)
  window.addEventListener('popstate', () => {
    if (mobileNav.classList.contains('open')) {
      setNavOpen(false)
    }
  })

  document.addEventListener('keydown', (e) => {
    if (!mobileNav.classList.contains('open')) return

    if (e.key === 'Escape') {
      setNavOpen(false)
      hamburger.focus()
      return
    }

    if (e.key === 'Tab') {
      const first = firstFocusable()
      const last = lastFocusable()
      if (!first || !last) return

      if (e.shiftKey && document.activeElement === first) {
        e.preventDefault()
        hamburger.focus()
      } else if (!e.shiftKey && document.activeElement === hamburger) {
        e.preventDefault()
        first.focus()
      } else if (!e.shiftKey && document.activeElement === last) {
        e.preventDefault()
        hamburger.focus()
      }
    }
  })
})()

