import { create } from "zustand"

interface HotelsMapState {
  activeHotel: string | null
  hoveredHotel: string | null
  hoverTimeout: number | null
  activate: (hotel: string | null) => void
  deactivate: () => void
  engage: (hotel: string | null) => void
  disengage: () => void
  disengageAfterDelay: () => void
}

export const useHotelsMapStore = create<HotelsMapState>((set, get) => ({
  activeHotel: null,
  hoveredHotel: null,
  hoverTimeout: null,
  activate: (hotel) => set({ activeHotel: hotel }),
  deactivate: () => set({ activeHotel: null }),
  engage: (hotel) => {
    const state = get()

    if (state.hoverTimeout) {
      window.clearTimeout(state.hoverTimeout)
    }

    if (hotel && state.activeHotel) {
      set({ activeHotel: null })
    }

    set({ hoveredHotel: hotel })
  },
  disengage: () => {
    set({ hoveredHotel: null })
  },
  disengageAfterDelay: () => {
    const timeoutId = window.setTimeout(() => {
      set({ hoveredHotel: null, activeHotel: null, hoverTimeout: null })
    }, 3000)

    set({ hoverTimeout: timeoutId })
  },
}))
