import { useEffect, useState } from 'react';
import { Annoyer, AnnoyerHandler } from './AnnoyerHandler';
import './Krassesoverlay.css';

const emojis = Array.from("🥐🥯🥞🍦🧁🍰🎂🍮🍭🍫🍬🍩🍪");


export const KrassesOverlay: React.FC = () => {

    const [annoyerHandler, ] = useState(() => new AnnoyerHandler(emojis, 2));
    const [x, setX] = useState(0);
    const update = () => setX(x+1);

    const handler = () => {
        annoyerHandler.tick();
        update();
    };

    useEffect(() => {
        const interval = setInterval(handler, 10);
        return () => clearInterval(interval);
    });

    const ref = (annoyer: Annoyer) => (element: HTMLImageElement) => {
        if (!element) return;
        const rect = element.getBoundingClientRect();
        const visible = rect.bottom >= 0 &&
            rect.right >= 0 &&
            rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.left <= (window.innerWidth || document.documentElement.clientWidth);
        annoyer.isVisible = visible;
    };

    return <div className="overlay">
        {Array.from(annoyerHandler.annoyers).map((annoyer, index) => (
            <span ref={ref(annoyer)} key={index} className="annoyer" style={
                {
                    fontSize: 40,
                    top: annoyer.y, left: annoyer.x,
                    transform: `rotate(${annoyer.angle}deg)`
                    }
            }>{annoyer.image}</span>
        ))}
    </div>;
}