"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useConfig = void 0;
const react_1 = __importDefault(require("react"));
const utility_1 = require("../utility");
const useConfig = (shopifyPermanentDomain, preloadedConfig) => {
    // synchronously returns cached and non-expired config from session storage
    const cachedConfig = react_1.default.useMemo(() => {
        var _a, _b;
        if (typeof window === "undefined") {
            return;
        }
        const sessionConfig = JSON.parse((_a = window.sessionStorage.getItem("reactify-search:config")) !== null && _a !== void 0 ? _a : "null");
        if (sessionConfig) {
            if (((_b = sessionConfig.config.cache) === null || _b === void 0 ? void 0 : _b.enabled) === false) {
                return;
            }
            return sessionConfig.config;
        }
        return;
    }, []);
    const [config, setConfig] = react_1.default.useState(cachedConfig);
    react_1.default.useEffect(() => {
        (() => __awaiter(void 0, void 0, void 0, function* () {
            const searchParams = new URLSearchParams();
            searchParams.set("shop", shopifyPermanentDomain);
            let json;
            try {
                json = yield fetch(`https://config.usereactify.com/?${searchParams.toString()}`).then((response) => response.json());
            }
            catch (error) {
                json = yield fetch(`https://config.usereactify.com/?${searchParams.toString()}`).then((response) => response.json());
            }
            setConfig(json.body);
            window.sessionStorage.setItem("reactify-search:config", JSON.stringify({
                config: json.body,
            }));
        }))();
    }, [shopifyPermanentDomain]);
    utility_1.debug.hook("useConfig", "config", config);
    return {
        config: config !== null && config !== void 0 ? config : preloadedConfig,
    };
};
exports.useConfig = useConfig;
//# sourceMappingURL=useConfig.js.map