import ColorThief from "colorthief/dist/color-thief.mjs";
import { useEffect, useState } from "react";

import { hasEnoughContrast } from "./checkContrast";

const rgbToHex = (rgbColor: [number, number, number]) => {
	// biome-ignore format:
	return `#${rgbColor.map(x => {
    const hex = x.toString(16);
    // biome-ignore format: 
    return hex.length === 1 ? `0${hex}` : hex
  }).join('')}`
};

export const useColor = (imgUrl: string) => {
	const [color, setColor] = useState<string>();

	useEffect(() => {
		// Get the layer color from the CSS variable
		const rootStyles = getComputedStyle(
			document.getElementsByClassName("bn-swap-wrap")?.[0],
		);
		const layerColor = rootStyles
			.getPropertyValue("--bn-bgLayer2")
			?.split(" ")
			.map((item) => Number(item)) as [number, number, number];

		if (!layerColor) {
			console.error("Invalid layer color value:", layerColor);
			return;
		}

		if (imgUrl) {
			const img = new Image();
			img.crossOrigin = "Anonymous"; // This is important for cross-origin images
			img.src = imgUrl;

			img.onload = () => {
				const colorthief = new ColorThief();
				const dominantColor = colorthief.getColor(img);

				if (hasEnoughContrast(dominantColor, layerColor)) {
					setColor(rgbToHex(dominantColor));
				} else {
					const colors = colorthief.getPalette(img);
					for (const color of colors) {
						if (hasEnoughContrast(color, layerColor as [number, number, number])) {
							setColor(rgbToHex(color));
							break;
						}
					}
				}
			};

			img.onerror = (err) => {
				const layerColor = rootStyles
					.getPropertyValue("--bn-themePrimary")
					?.split(" ")
					.map((item) => Number(item)) as [number, number, number];

				setColor(rgbToHex(layerColor));
			};
		}
	}, [imgUrl]);

	return color;
};
