import { useEffect } from 'react'

let lockDepth = 0
const saved = {
  appMainScrollTop: 0,
  bodyScrollTop: 0,
  appMainOverflow: '',
  appMainTouchAction: '',
}

function queryAppMain() {
  return document.querySelector('.app-main')
}

function applyLock() {
  document.documentElement.classList.add('modal-scroll-locked')

  const appMain = queryAppMain()
  if (appMain) {
    saved.appMainScrollTop = appMain.scrollTop
    saved.appMainOverflow = appMain.style.overflow
    saved.appMainTouchAction = appMain.style.touchAction
    appMain.style.overflow = 'hidden'
    appMain.style.touchAction = 'none'
  }

  saved.bodyScrollTop = window.scrollY || document.documentElement.scrollTop || 0
  document.body.style.overflow = 'hidden'
  document.body.style.overscrollBehavior = 'none'
}

function releaseLock() {
  document.documentElement.classList.remove('modal-scroll-locked')

  const appMain = queryAppMain()
  if (appMain) {
    appMain.style.overflow = saved.appMainOverflow
    appMain.style.touchAction = saved.appMainTouchAction
    appMain.scrollTop = saved.appMainScrollTop
  }

  document.body.style.overflow = ''
  document.body.style.overscrollBehavior = ''
  if (saved.bodyScrollTop) {
    window.scrollTo(0, saved.bodyScrollTop)
  }
}

/** Hintergrund-Scroll sperren (.app-main + body), verschachtelte Modals via Zähler. */
export function useModalScrollLock(active) {
  useEffect(() => {
    if (!active) return undefined
    lockDepth += 1
    if (lockDepth === 1) applyLock()
    return () => {
      lockDepth = Math.max(0, lockDepth - 1)
      if (lockDepth === 0) releaseLock()
    }
  }, [active])
}
