
const ProductInfo = (props) => {
    const {
        config, barcode, setBarcode, baskets, setBaskets, productSelected, 
        setReloadPage, reloadPage, scrollToFirstPage, member, content, 
        isMobile = false, userInfo, showCart = false, setShowCart 
    } = props;

    const [loading, setLoading] = useState(false);
    const [product, setProduct] = useState();
    const history = useHistory();
    const custCode = baskets?.basket?.cust_code || '';
    const [fromPage] = useState('cart');

    // 1. Logic cập nhật Basket (Dùng useCallback để tránh re-render thừa)
    const updateBasket = useCallback((itemCode, qty, productInfo, item_code_ref, line_type = 'S') => {
        const timestamp = Date.now();
        const basket_date = new Date().toISOString();

        setBaskets(prevBaskets => {
            const currentBaskets = prevBaskets || { 
                items: [], 
                basket: { basket_id: timestamp, basket_date, cust_code: member?.shopper_id } 
            };

            const existingItemIndex = currentBaskets.items.findIndex(
                item => item.item_code === itemCode && item.line_type === line_type
            );

            if (existingItemIndex !== -1) {
                const updatedItems = [...currentBaskets.items];
                // Giữ nguyên logic: nếu reload=true thì không tăng thêm qty
                const finalQty = currentBaskets?.basket?.reload === true ? 0 : qty;
                updatedItems[existingItemIndex].qty += finalQty;
                return { ...currentBaskets, items: updatedItems };
            }

            return {
                ...currentBaskets,
                items: [...currentBaskets.items, { item_code: itemCode, qty, product_info: productInfo, item_code_ref, line_type }]
            };
        });
    }, [member, setBaskets]);

    // 2. Logic Fetch Product (Dùng useCallback)
    const fetchProductByBarcode = useCallback(async () => {
        try {
            setLoading(true);
            const url = `/api/get-mdc-product-info`;
            
            let [strQty, strBarcode] = barcode.includes("*") ? barcode.split('*') : ['1', barcode];
            strBarcode = (strBarcode || barcode).split('_')[0].replace(/[\n\r]+/g, '').trim();
            const qty = parseInt(strQty) || 1;

            const dataRequest = {
                barcode: strBarcode,
                cust_code: baskets?.basket?.cust_code || member?.shopper_id
            };

            const resultObj = await commonApi.APIPOSTByURL(url, dataRequest, config);

            if (resultObj?.status === 200) {
                const dataTmp = resultObj?.data;
                if (dataTmp?.product?.item_code) {
                    setProduct(dataTmp);
                    updateBasket(dataTmp.product.item_code, qty, dataTmp, dataTmp.product.item_code_ref);
                    
                    const slug = dataTmp.product.slug;
                    history.push(`/products/${slug}`);

                    if (reloadPage === '1') {
                        // eslint-disable-next-line no-undef
                        currentProductInfo = null; // Cẩn thận với biến global này
                        window.location.href = window.location.origin;
                        window.location.reload();
                    }
                } else {
                    alert('Item not found !!');
                }
            }
        } catch (e) {
            console.error("ERROR get-product-info:", e);
        } finally {
            setLoading(false);
        }
    }, [barcode, baskets, config, history, member, reloadPage, updateBasket]);

    // 3. Quản lý Effects
    useEffect(() => {
        if (barcode) {
            fetchProductByBarcode();
            setBarcode('');
        } else if (typeof currentProductInfo !== 'undefined' && currentProductInfo) {
            setProduct(currentProductInfo);
        }
    }, [barcode, custCode, fetchProductByBarcode, setBarcode]);

    useEffect(() => {
        if (productSelected) setProduct(productSelected);
    }, [productSelected]);

    useEffect(() => {
        if (baskets?.items?.length === 0 && showCart === true) {
            setProduct(null);
        }
    }, [baskets?.items, showCart]);

    useEffect(() => {
        const titleLink = document.getElementById("title_company");
        const title = config?.lang === 'vi' 
            ? content?.product?.Short_Description_VI 
            : content?.product?.Short_Description_EN;

        if (titleLink) {
            titleLink.textContent = title || content?.product?.description || '';
        }
        setProduct(content);
    }, [content, config, content?.product]);

    return (
        <>
            <LoadingComponent loading={loading} message="Wait" />
            {product && (
                <ProductDetail 
                    productInfo={product} setBaskets={setBaskets} config={config} 
                    userInfo={userInfo} scrollToFirstPage={scrollToFirstPage} 
                    member={member} isMobile={isMobile} fromPage={fromPage} 
                    showCart={showCart} 
                />
            )}
        </>
    );
};
