"use client"
import { useEffect } from "react"

import { useRatesStore } from "@/stores/select-rate"

import styles from "./rooms.module.css"

export default function ScrollToList() {
  const { isSingleRoomAndHasSelection } = useRatesStore((state) => ({
    isSingleRoomAndHasSelection:
      state.booking.rooms.length === 1 && !!state.rateSummary.length,
  }))

  useEffect(() => {
    if (isSingleRoomAndHasSelection) {
      // Required to prevent the history.pushState on the first selection
      // to scroll user back to top
      requestAnimationFrame(() => {
        const SCROLL_OFFSET = 173 // summary on mobile is 163px

        const selectedRateCard: HTMLElement | null = document.querySelector(
          `.${styles.roomList} label:has(input[type=radio]:checked)`
        )

        if (selectedRateCard) {
          const elementPosition = selectedRateCard.getBoundingClientRect().top
          const windowHeight = window.innerHeight
          const offsetPosition =
            elementPosition +
            window.scrollY -
            (windowHeight - selectedRateCard.offsetHeight - SCROLL_OFFSET)

          window.scrollTo({
            top: offsetPosition,
            behavior: "instant",
          })
        }
      })
    }
  }, [isSingleRoomAndHasSelection])

  return null
}
