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

const cache = {};

export function detectOptimalBackground(blob,
                                        darkBackground = '#333333',
                                        lightBackground = '#f0f0f0',
                                        defaultBackground = 'transparent',
                                        tolerance = 55,
                                        minPixels = 10) {
    return new Promise((resolve) => {
        const imgUrl = URL.createObjectURL(blob);
        const img = new Image();
        img.crossOrigin = "anonymous";
        img.onload = () => {
            const canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0);

            const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
            const pixels = imageData.data;
            let lightBorderCount = 0;
            let darkBorderCount = 0;

            const isTransparent = (i) => pixels[i + 3] === 0;
            const isLightColor = (i) => {
                const r = pixels[i];
                const g = pixels[i + 1];
                const b = pixels[i + 2];
                const a = pixels[i + 3];
                return r > 255 - tolerance && g > 255 - tolerance && b > 255 - tolerance && a > 128;
            };
            const isDarkColor = (i) => {
                const r = pixels[i];
                const g = pixels[i + 1];
                const b = pixels[i + 2];
                const a = pixels[i + 3];
                return r < tolerance && g < tolerance && b < tolerance && a > 128;
            };

            // Parcourir une ligne/colonne sur 3
            for (let y = 0; y < canvas.height; y += Math.max(canvas.height / 500, 1)) {
                for (let x = 0; x < canvas.width; x += Math.max(canvas.width / 500, 1)) {
                    const i = Math.round(y * canvas.width + x) * 4;
                    if (isTransparent(i)) {
                        const neighbors = [
                            i - 4, i + 4, // Haut/Bas
                            i - 4 * canvas.width, i + 4 * canvas.width, // Gauche/Droite
                        ];
                        for (const neighbor of neighbors) {
                            if (neighbor >= 0 && neighbor < pixels.length) {
                                if (isLightColor(neighbor)) lightBorderCount++;
                                if (isDarkColor(neighbor)) darkBorderCount++;
                            }
                        }
                    }
                }
            }

            URL.revokeObjectURL(imgUrl);
            if (lightBorderCount > darkBorderCount && lightBorderCount >= minPixels) {
                resolve(darkBackground); // Fond sombre
            } else if (darkBorderCount > lightBorderCount && darkBorderCount >= minPixels) {
                resolve(lightBackground); // Fond clair
            } else {
                resolve(defaultBackground); // Fond transparent
            }
        };
        img.onerror = () => {
            URL.revokeObjectURL(imgUrl);
            resolve(defaultBackground); // En cas d'erreur
        };
        img.src = imgUrl;
    });
}

export function SmartLogoBackground({
                                        src,
                                        darkBackground = '#333333',
                                        lightBackground = '#f0f0f0',
                                        defaultBackground = 'transparent',
                                        tolerance = 55,
                                        minPixels = 10, // Seuil minimal de pixels détectés pour appliquer un fond
                                        alt = 'Logo',
                                        style = {},
                                        imgClassName = '',
                                    }) {
    const canvasRef = useRef(null);
    const [background, setBackground] = useState(defaultBackground);
    const [load, setLoad] = useState(false)

    useEffect(() => {
        if (!load) return;

        const fetchAndDetect = async () => {
            if (cache[src]) {
                setBackground(cache[src]);
                return;
            }

            try {
                const response = await fetch(src);
                const blob = await response.blob();
                const detectedBackground = await detectOptimalBackground(blob, darkBackground, lightBackground, defaultBackground, tolerance, minPixels);
                cache[src] = detectedBackground;
                setBackground(detectedBackground);
            } catch (error) {
                console.error("Erreur de détection du fond:", error);
                cache[src] = defaultBackground;
                setBackground(defaultBackground);
            }
        };

        fetchAndDetect();
    }, [src, darkBackground, lightBackground, defaultBackground, tolerance, minPixels, load]);

    return <>
        <img className={imgClassName} src={src} alt={alt} style={{...style, filter: `drop-shadow(0 0 1rem ${background})`}}
             onError={e => {
                 e.target.style.opacity = "0"
                 setLoad(false)
             }}
             onLoad={e => {
                 e.target.style.opacity = "1"
                 setLoad(true)
             }}/>
        <canvas ref={canvasRef} style={{display: 'none'}}/>
    </>
}

export const SmartLogoBackgroundMemo = memo(SmartLogoBackground);
