"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ALLOWED_REGISTRATION_TOKEN = exports.TOKEN_ACCESS_SYNC_EVENT = exports.TOKEN_ACCESS_STORAGE_KEY = void 0;
exports.isAllowedRegistrationToken = isAllowedRegistrationToken;
exports.getRegisteredAccessToken = getRegisteredAccessToken;
exports.hasRegisteredAccessTokenAccess = hasRegisteredAccessTokenAccess;
exports.setRegisteredAccessToken = setRegisteredAccessToken;
exports.useTokenAccess = useTokenAccess;
var react_1 = require("react");
exports.TOKEN_ACCESS_STORAGE_KEY = 'work-app.token-access.registered-token';
exports.TOKEN_ACCESS_SYNC_EVENT = 'work-app:token-access-changed';
exports.ALLOWED_REGISTRATION_TOKEN = ((_a = import.meta.env.VITE_ALLOWED_REGISTRATION_TOKEN) === null || _a === void 0 ? void 0 : _a.trim()) || 'usr_7f3a9c2d8e1b4a6f';
function normalizeToken(value) {
    var _a;
    return (_a = value === null || value === void 0 ? void 0 : value.trim()) !== null && _a !== void 0 ? _a : '';
}
function isAllowedRegistrationToken(token) {
    return normalizeToken(token) === exports.ALLOWED_REGISTRATION_TOKEN;
}
function getRegisteredAccessToken() {
    if (typeof window === 'undefined') {
        return '';
    }
    return normalizeToken(window.localStorage.getItem(exports.TOKEN_ACCESS_STORAGE_KEY));
}
function hasRegisteredAccessTokenAccess() {
    return isAllowedRegistrationToken(getRegisteredAccessToken());
}
function setRegisteredAccessToken(token) {
    if (typeof window === 'undefined') {
        return;
    }
    var normalizedToken = normalizeToken(token);
    if (normalizedToken) {
        window.localStorage.setItem(exports.TOKEN_ACCESS_STORAGE_KEY, normalizedToken);
    }
    else {
        window.localStorage.removeItem(exports.TOKEN_ACCESS_STORAGE_KEY);
    }
    window.dispatchEvent(new CustomEvent(exports.TOKEN_ACCESS_SYNC_EVENT));
}
function useTokenAccess() {
    var _a = (0, react_1.useState)(function () { return getRegisteredAccessToken(); }), registeredToken = _a[0], setRegisteredToken = _a[1];
    (0, react_1.useEffect)(function () {
        if (typeof window === 'undefined') {
            return undefined;
        }
        var syncRegisteredToken = function () {
            setRegisteredToken(getRegisteredAccessToken());
        };
        window.addEventListener('storage', syncRegisteredToken);
        window.addEventListener(exports.TOKEN_ACCESS_SYNC_EVENT, syncRegisteredToken);
        return function () {
            window.removeEventListener('storage', syncRegisteredToken);
            window.removeEventListener(exports.TOKEN_ACCESS_SYNC_EVENT, syncRegisteredToken);
        };
    }, []);
    return {
        registeredToken: registeredToken,
        hasAccess: isAllowedRegistrationToken(registeredToken),
    };
}
