"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReactifySearchProvider = void 0;
const react_1 = __importDefault(require("react"));
// @ts-expect-error missing types
const GaGtag = __importStar(require("ga-gtag"));
const package_json_1 = __importDefault(require("../../../package.json"));
const hooks_1 = require("../../hooks");
const components_1 = require("../../components");
const utility_1 = require("../../utility");
const curation_1 = require("../../utility/curation");
const ReactifySearchProvider = (props) => {
    react_1.default.useEffect(() => {
        utility_1.debug.log("ReactifySearchProvider", "props", props);
        GaGtag.install("G-DV00Z0X5VP", {
            cookie_prefix: "_rs",
            user_properties: {
                shop: props.shopifyPermanentDomain,
                version: package_json_1.default.version,
            },
        });
    }, [props]);
    return react_1.default.createElement(ReactifySearchInner, Object.assign({}, props));
};
exports.ReactifySearchProvider = ReactifySearchProvider;
const ReactifySearchInner = (props) => {
    var _a, _b;
    const { config } = (0, hooks_1.useConfig)(props.shopifyPermanentDomain, (_a = props.preload) === null || _a === void 0 ? void 0 : _a.config);
    const theme = (_b = props.theme) !== null && _b !== void 0 ? _b : {
        typography: {
            fontFamily: "inherit",
            fontSize: "inherit",
        },
    };
    // search from url
    const searchTermFromURL = react_1.default.useMemo(() => {
        var _a;
        if (typeof window === "undefined") {
            return;
        }
        const urlParams = new URLSearchParams(window.location.search);
        return (_a = urlParams.get("q")) !== null && _a !== void 0 ? _a : undefined;
    }, [typeof window !== "undefined" && window.location.search]);
    // sort from url
    const searchSortFromURL = react_1.default.useMemo(() => {
        var _a, _b;
        if (typeof window === "undefined") {
            return (_a = props.query) === null || _a === void 0 ? void 0 : _a.sort;
        }
        const urlParams = new URLSearchParams(window.location.search);
        return (_b = urlParams.get("sort")) !== null && _b !== void 0 ? _b : undefined;
    }, [typeof window !== "undefined" && window.location.search]);
    // index from url
    const indexFromURL = react_1.default.useMemo(() => {
        var _a;
        if (typeof window === "undefined") {
            return;
        }
        const urlParams = new URLSearchParams(window.location.search);
        return (_a = urlParams.get("index")) !== null && _a !== void 0 ? _a : undefined;
    }, [typeof window !== "undefined" && window.location.search]);
    // search term
    const [searchTerm, setSearchTerm] = react_1.default.useState(searchTermFromURL !== null && searchTermFromURL !== void 0 ? searchTermFromURL : "");
    // search term redirect
    const searchRedirect = react_1.default.useMemo(() => {
        return config === null || config === void 0 ? void 0 : config.redirects.find((redirect) => redirect.query.trim().toLowerCase() === searchTerm.trim().toLowerCase());
    }, [config === null || config === void 0 ? void 0 : config.redirects, searchTerm]);
    // show instant-search
    const [showInstantSearchResults, setShowInstantSearchResults] = react_1.default.useState(false);
    // sort option
    const [sortOption, setSortOption] = react_1.default.useState(searchSortFromURL !== null && searchSortFromURL !== void 0 ? searchSortFromURL : "");
    // results
    const [results, setResults] = react_1.default.useState([]);
    // curation
    const curation = react_1.default.useMemo(() => {
        if (!config) {
            return undefined;
        }
        return (0, curation_1.getCuration)({
            provider: props,
            config: config,
            searchTerm: searchTerm,
        });
    }, [props, config, searchTerm]);
    // result stats
    const [resultStats, setResultStats] = react_1.default.useState();
    react_1.default.useEffect(() => {
        if (props.mode === "instant-search") {
            return;
        }
        if (searchTermFromURL && searchTerm !== searchTermFromURL) {
            setSearchTerm(searchTermFromURL);
        }
    }, [searchTermFromURL]);
    react_1.default.useEffect(() => {
        if (props.mode === "instant-search") {
            return;
        }
        if (searchSortFromURL && sortOption !== searchSortFromURL) {
            setSortOption(searchSortFromURL);
        }
    }, [searchSortFromURL]);
    const contextValue = react_1.default.useMemo(() => {
        var _a, _b, _c;
        if (!config) {
            return;
        }
        return {
            config: config,
            options: Object.assign(Object.assign({}, props), { clientId: (_a = props.clientId) !== null && _a !== void 0 ? _a : "theme", index: (_c = (_b = props.index) !== null && _b !== void 0 ? _b : indexFromURL) !== null && _c !== void 0 ? _c : config.index, filtersHandle: props.filtersHandle, credentials: props.credentials, theme: theme }),
            search: {
                searchTerm: searchTerm,
                setSearchTerm: setSearchTerm,
                showInstantSearchResults: showInstantSearchResults,
                setShowInstantSearchResults: setShowInstantSearchResults,
                searchRedirect: searchRedirect,
            },
            sortby: {
                sortOption: sortOption,
                setSortOption: setSortOption,
            },
            results: {
                results: results,
                setResults: setResults,
                resultStats: resultStats,
                setResultStats: setResultStats,
            },
            curation: curation,
        };
    }, [
        config,
        props,
        searchTerm,
        showInstantSearchResults,
        searchRedirect,
        sortOption,
        results,
        resultStats,
        curation,
    ]);
    utility_1.debug.hook("ReactifySearchProvider", "context", contextValue);
    if (!contextValue) {
        if (props.renderBooting) {
            return props.renderBooting();
        }
        return null;
    }
    return (react_1.default.createElement(hooks_1.ReactifySearchContext.Provider, { value: contextValue },
        react_1.default.createElement(components_1.UtilityAuthenticatedReactiveBase, null, props.children)));
};
//# sourceMappingURL=ReactifySearchProvider.js.map