"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLogic = void 0;
const react_1 = require("react");
const ErrorService_1 = require("../../services/ErrorService");
const useMenu_1 = require("../../useMenu");
const useLogic = ({ getProducts, filter }) => {
    const [products, setProducts] = (0, react_1.useState)([]);
    const [isLoading, setIsLoading] = (0, react_1.useState)(false);
    const [isError, setIsError] = (0, react_1.useState)(false);
    const { open, anchorRef, handleOpenMenu, handleCloseMenu } = (0, useMenu_1.useMenu)();
    const filterProductList = (productList) => {
        const { hostname } = new URL(window.origin);
        return productList.filter((product) => new URL(product.url).hostname !== hostname);
    };
    const fetchProductsWithRetry = async () => {
        try {
            return await getProducts();
        }
        catch {
            // Retry запроса один раз при ошибке
            return await getProducts();
        }
    };
    const loadProducts = async () => {
        setIsLoading(true);
        setIsError(false);
        try {
            const productList = await fetchProductsWithRetry();
            const filteredProducts = filter
                ? filter(productList)
                : filterProductList(productList);
            setProducts(filteredProducts);
        }
        catch (error) {
            setIsError(true);
            ErrorService_1.ErrorService.getInstance().captureException(error, {
                place: 'ProductSwitcher',
            });
        }
        finally {
            setIsLoading(false);
        }
    };
    const openMenu = () => {
        handleOpenMenu();
        if (!products.length) {
            loadProducts().then();
        }
    };
    return {
        anchorRef,
        openMenu,
        closeMenu: handleCloseMenu,
        isLoading,
        isError,
        products,
        open,
    };
};
exports.useLogic = useLogic;
