'use client';
import { useSyncExternalStore } from 'react';
const INITIAL_STATE = {
    pageIndex: 0,
    referrer: '',
    pageEvent: undefined,
    isFirstPage: true,
    isLastPage: true,
    pageHistory: [],
    pageHistoryLength: 0,
};
export const pageTrackerStore = {
    state: {
        ...INITIAL_STATE,
    },
    listeners: new Set(),
    getState() {
        return this.state;
    },
    getImmutablePageHistory() {
        return this.state.pageHistory.slice();
    },
    setState: (newState) => {
        pageTrackerStore.state = {
            ...pageTrackerStore.state,
            ...newState,
        };
        requestAnimationFrame(() => {
            pageTrackerStore.listeners.forEach((listener) => listener());
        });
    },
    subscribe: (listener) => {
        pageTrackerStore.listeners.add(listener);
        return () => pageTrackerStore.listeners.delete(listener);
    },
};
/**
 * get PageTrackerStore in any function.
 **/
export const getPageTrackerStore = () => {
    return pageTrackerStore.getState();
};
const shallow = (a, b) => {
    if (Object.is(a, b))
        return true;
    if (!a || !b)
        return false;
    const aKeys = Object.keys(a);
    const bKeys = Object.keys(b);
    if (aKeys.length !== bKeys.length)
        return false;
    for (const k of aKeys) {
        if (!Object.is(a[k], b[k]))
            return false;
    }
    return true;
};
export const usePageTrackerStore = (selector) => {
    let lastSelected = selector(pageTrackerStore.getState());
    return useSyncExternalStore(pageTrackerStore.subscribe, () => {
        const selected = selector(pageTrackerStore.getState());
        if (!shallow(lastSelected, selected)) {
            lastSelected = selected;
        }
        return lastSelected;
    }, () => selector(pageTrackerStore.getState()));
};
//# sourceMappingURL=page-tracker-store.js.map