<template>
  <div
    class="grid h-full grid-rows-[_1rem_1fr_1rem_auto_auto_] sm:grid-rows-[_auto_1rem_1fr_1rem_auto_] pt-safe sm:pb-safe overflow-hidden touch-none"
  >
    <!-- Shadow Top -->
    <div
      class="row-start-1 row-span-1 col-start-1 sm:row-start-2 relative w-full h-[1rem] bg-gradient-to-b from-black/30 sm:from-black/10 to-transparent dark:from-white/10 pointer-events-none transition-opacity duration-300"
      :class="{ 'opacity-0': !showTopShadow, 'opacity-100': showTopShadow }"
    />

    <!-- Content Section -->
    <div
      class="row-start-1 row-span-3 col-start-1 sm:row-start-2 overflow-hidden overflow-y-auto px-4 overscroll-contain touch-manipulation"
      ref="contentScrollContainer"
      @scroll="handleScroll"
    >
      <div class="sm:max-w-prose grid grid-cols-1 mx-auto my-5 w-full">
        <slot name="default" v-bind:scrollToBottom />
      </div>
    </div>

    <!-- Shadow Bottom -->
    <div
      class="row-start-3 row-span-1 col-start-1 sm:row-start-4 relative w-full h-[1rem] bg-gradient-to-t from-black/10 to-transparent dark:from-white/10 pointer-events-none transition-opacity duration-300"
      :class="{ 'opacity-0': !showBottomShadow, 'opacity-100': showBottomShadow }"
    />

    <!-- Footer Section -->
    <div class="row-start-4 row-span-1 col-start-1 sm:row-start-5">
      <slot name="footer">
        <footer
          v-if="!slots.footer"
          class="bg-gray-100 dark:bg-gray-800 text-center py-1.5 border-t dark:border-gray-700 text-xs sm:text-base text-gray-700 dark:text-gray-300 sm:order-last"
        >
          <span class="text-nowrap">Сделайте НаСвязи удобнее.</span>
          <span> </span>
          <span class="text-nowrap">
            Будем рады
            <RouterLink
              to="/donate"
              class="underline underline-offset-2 text-primary-600 dark:text-primary-400"
            >
              вашей поддержке
            </RouterLink>
          </span>
        </footer>
      </slot>
    </div>

    <TabBar class="row-start-5 row-span-1 col-start-1 sm:row-start-1" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useTemplateRef } from 'vue'

const slots = defineSlots<{
  default?: (slotBindings: { scrollToBottom: typeof scrollToBottom }) => void
  footer?: () => void
}>()

const contentScrollContainerRef = useTemplateRef('contentScrollContainer')

const showTopShadow = ref(false)
const showBottomShadow = ref(false)

const scrollToBottom = () => {
  if (contentScrollContainerRef.value) {
    contentScrollContainerRef.value.scrollTop = contentScrollContainerRef.value.scrollHeight
  }
}

const handleScroll = () => {
  const el = contentScrollContainerRef.value
  if (!el) return

  const hasScrollTop = el.scrollTop > 0
  const hasScrollBottom = el.scrollTop + el.clientHeight < el.scrollHeight

  showTopShadow.value = hasScrollTop
  showBottomShadow.value = hasScrollBottom
}

// Устанавливаем корректную высоту при загрузке и изменении размера окна
const onresize = () => {
  document.documentElement.style.setProperty(
    '--visual-viewport-offset-top',
    `${visualViewport!.offsetTop!}px`,
  )
  document.documentElement.style.setProperty(
    '--visual-viewport-height',
    `${visualViewport!.height}px`,
  )
  if (document.activeElement) {
    if ('scrollIntoViewIfNeeded' in document.activeElement) {
      ;(document.activeElement.scrollIntoViewIfNeeded as (options?: ScrollIntoViewOptions) => void)(
        {
          block: 'center',
        },
      )
    } else {
      document.activeElement.scrollIntoView({ block: 'center' })
    }
  }
}

// if ('virtualKeyboard' in navigator) {
//   // Tell the browser you are taking care of virtual keyboard occlusions yourself.
//   navigator.virtualKeyboard.overlaysContent = true;
//   navigator.virtualKeyboard.addEventListener('geometrychange', (event) => {
//     const { x, y, width, height } = event.target.boundingRect;
//     if (height > 0) console.log('keyboard is shown');
//     else console.log('keyboard is hidden');
//   });
// }

function preventScroll(e: TouchEvent) {
  if (
    contentScrollContainerRef.value &&
    contentScrollContainerRef.value.scrollHeight <= contentScrollContainerRef.value.clientHeight
  ) {
    e.preventDefault()
  }
}

const layoutPageHead = useHead({
  htmlAttrs: { class: 'overflow-hidden overscroll-none touch-none fix-layout-scrolling' },
  bodyAttrs: { class: 'overflow-hidden overscroll-none touch-none' },
})

onMounted(() => {
  // visualViewport?.addEventListener('resize', onresize, { passive: true })
  contentScrollContainerRef.value!.addEventListener('touchmove', preventScroll, { passive: false })

  // Инициализируем отображение теней
  handleScroll()
})

onBeforeUnmount(() => {
  layoutPageHead?.dispose()
  visualViewport?.removeEventListener('resize', onresize)
  document.documentElement.style.removeProperty('--visual-viewport-offset-top')
  document.documentElement.style.removeProperty('--visual-viewport-height')
  contentScrollContainerRef.value!.removeEventListener('touchmove', preventScroll)
})
</script>

<style scoped>
::v-global(html.fix-layout-scrolling) {
  --visual-viewport-height: 100dvh;
  --visual-viewport-offset-top: 0px;
  position: fixed;
  width: 100dvw;
  height: var(--visual-viewport-height);
  top: var(--visual-viewport-offset-top);
  bottom: 0;
}
</style>
