import { type Action, ActionType, type InitState, type State, } from "@/types/components/form/bookingwidget" import type { Locations } from "@/types/trpc/routers/hotel/locations" export const localStorageKey = "searchHistory" export const sessionStorageKey = "searchData" export function init(initState: InitState): State { const locations = [] if (initState.initialValue) { const location = initState.defaultLocations.find( (loc) => loc.name.toLowerCase() === initState.initialValue!.toLowerCase() ) if (location) { locations.push(location) } } return { defaultLocations: initState.defaultLocations, locations, search: locations.length ? locations[0].name : "", searchData: locations.length ? locations[0] : undefined, searchHistory: null, } } export function reducer(state: State, action: Action) { const type = action.type switch (type) { case ActionType.CLEAR_HISTORY_LOCATIONS: { return { ...state, locations: [], search: "", searchHistory: null, } } case ActionType.CLEAR_SEARCH_LOCATIONS: return { ...state, locations: [], search: "", } case ActionType.SEARCH_LOCATIONS: { const matchesMap = new Map() const search = action.payload.search.toLowerCase() state.defaultLocations.forEach((location) => { const locationName = location.name.toLowerCase() const keyWords = location.keyWords?.flatMap((l) => l.toLowerCase().split(" ") ) if (locationName.includes(search.trim())) { matchesMap.set(location.name, location) } if (keyWords?.find((keyWord) => keyWord.startsWith(search.trim()))) { matchesMap.set(location.name, location) } }) const matches: Locations = [] matchesMap.forEach((value) => { matches.push(value) }) return { ...state, locations: matches, search: action.payload.search, } } case ActionType.SELECT_ITEM: { return { ...state, searchData: action.payload.location, searchHistory: action.payload.searchHistory, } } case ActionType.SET_STORAGE_DATA: { return { ...state, searchData: action.payload.searchData ? action.payload.searchData : state.searchData, searchHistory: action.payload.searchHistory ? action.payload.searchHistory : state.searchHistory, } } default: const unhandledActionType: never = type console.info(`Unhandled type: ${unhandledActionType}`) return state } }