"use client"

import { useCallback, useEffect } from "react"

import { useEnterDetailsStore } from "@/stores/enter-details"

export default function HistoryStateManager() {
  const setCurrentStep = useEnterDetailsStore((state) => state.setCurrentStep)
  const currentStep = useEnterDetailsStore((state) => state.currentStep)

  const handleBackButton = useCallback(
    (event: PopStateEvent) => {
      if (event.state.step) {
        setCurrentStep(event.state.step)
      }
    },
    [setCurrentStep]
  )

  useEffect(() => {
    window.addEventListener("popstate", handleBackButton)

    return () => {
      window.removeEventListener("popstate", handleBackButton)
    }
  }, [handleBackButton])

  useEffect(() => {
    if (!window.history.state.step) {
      window.history.replaceState(
        { step: currentStep },
        "",
        document.location.href
      )
    }
  }, [currentStep])

  return null
}
