import { useState } from 'react';
import { ErrorService } from '../../services/ErrorService';
import { useMenu } from '../../useMenu';
export const useLogic = ({ getProducts, filter }) => {
    const [products, setProducts] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [isError, setIsError] = useState(false);
    const { open, anchorRef, handleOpenMenu, handleCloseMenu } = 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.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,
    };
};
