"use strict";
'use client';
Object.defineProperty(exports, "__esModule", { value: true });
exports.usePageTrackerStore = exports.getPageTrackerStore = exports.pageTrackerStore = void 0;
const react_1 = require("react");
const INITIAL_STATE = {
    pageIndex: 0,
    referrer: '',
    pageEvent: undefined,
    isFirstPage: true,
    isLastPage: true,
    pageHistory: [],
    pageHistoryLength: 0,
};
exports.pageTrackerStore = {
    state: {
        ...INITIAL_STATE,
    },
    listeners: new Set(),
    getState() {
        return this.state;
    },
    getImmutablePageHistory() {
        return this.state.pageHistory.slice();
    },
    setState: (newState) => {
        exports.pageTrackerStore.state = {
            ...exports.pageTrackerStore.state,
            ...newState,
        };
        requestAnimationFrame(() => {
            exports.pageTrackerStore.listeners.forEach((listener) => listener());
        });
    },
    subscribe: (listener) => {
        exports.pageTrackerStore.listeners.add(listener);
        return () => exports.pageTrackerStore.listeners.delete(listener);
    },
};
/**
 * get PageTrackerStore in any function.
 **/
const getPageTrackerStore = () => {
    return exports.pageTrackerStore.getState();
};
exports.getPageTrackerStore = getPageTrackerStore;
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;
};
const usePageTrackerStore = (selector) => {
    let lastSelected = selector(exports.pageTrackerStore.getState());
    return (0, react_1.useSyncExternalStore)(exports.pageTrackerStore.subscribe, () => {
        const selected = selector(exports.pageTrackerStore.getState());
        if (!shallow(lastSelected, selected)) {
            lastSelected = selected;
        }
        return lastSelected;
    }, () => selector(exports.pageTrackerStore.getState()));
};
exports.usePageTrackerStore = usePageTrackerStore;
//# sourceMappingURL=page-tracker-store.js.map