import React, { useEffect, useRef, useState } from 'react';
import 'animate.css';

const Animate = ({ animation = 'animate__fadeIn', children, threshold = 0.1, className = '', style = {} }) => {
    const ref = useRef();
    const [visible, setVisible] = useState(false);

    useEffect(() => {
        const onScroll = () => {
            if (!ref.current) return;
            const rect = ref.current.getBoundingClientRect();
            const windowHeight = window.innerHeight || document.documentElement.clientHeight;
            const visibleRatio = (rect.bottom > 0 && rect.top < windowHeight) ? 1 : 0;

            if (visibleRatio >= threshold) {
                setVisible(true);
            }
        };

        window.addEventListener('scroll', onScroll);
        onScroll(); // dastlabki tekshiruv
        return () => window.removeEventListener('scroll', onScroll);
    }, [threshold]);

    return (
        <div
            ref={ref}
            className={`${className} ${visible ? `animate__animated ${animation}` : ''}`}
            style={{ ...style, opacity: visible ? 1 : 0 }}
        >
            {children}
        </div>
    );
};

export default Animate;
