import React, { useState, useEffect, useRef } from 'react';

const LazyImage: React.FC<React.ImgHTMLAttributes<any>> = ({ src, ...props }) => {
    const [imageSrc, setImageSrc] = useState<string>();
    const [hasBeenLoaded, setHasBeenLoaded] = useState(false);
    const imgRef = useRef(null);

    useEffect(() => {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting && !hasBeenLoaded) {
                    setImageSrc(src);
                    setHasBeenLoaded(true);
                    observer.unobserve(imgRef.current as any);
                }
            });
        });

        observer.observe(imgRef.current as any);

        return () => {
            if (imgRef.current) {
                observer.unobserve(imgRef.current);
            }
        };
    }, [src, hasBeenLoaded]);

    return <img {...props} ref={imgRef} src={imageSrc || require('../../public/avatar.png')} />;
};

export default React.memo(LazyImage);