

export const IS_DEV = window.location.hostname === 'localhost' && window.location.port !== '8888';

// Цвета бренда из index.css
const brandColors = {
    // Основные цвета
    'red': '#ff0000',
    'green': '#00ff00',
    'blue': '#0000ff',
    'yellow': '#ffff00',
    'purple': '#800080',
    'orange': '#ffa500',
    'pink': '#ffc0cb',
    'brown': '#a52a2a',
    // Дополнительные цвета
    'cyan': '#00ffff',
    'magenta': '#ff00ff',
    'lime': '#00ff00',
    'teal': '#008080',
    'indigo': '#4b0082',
    'violet': '#8a2be2',
    'coral': '#ff7f50',
    'salmon': '#fa8072',
    'gold': '#ffd700',
    'silver': '#c0c0c0',
    'gray': '#808080',
    'black': '#000000',
    'white': '#ffffff',
} as const;

type BrandColorName = keyof typeof brandColors;

/**
 * Преобразует hex цвет в RGB
 */
function hexToRgb(hex: string): [number, number, number] {
    // Убираем # если есть
    hex = hex.replace('#', '');

    // Если короткий формат (3 символа), расширяем
    if (hex.length === 3) {
        hex = hex.split('').map(char => char + char).join('');
    }

    const r = parseInt(hex.substring(0, 2), 16);
    const g = parseInt(hex.substring(2, 4), 16);
    const b = parseInt(hex.substring(4, 6), 16);

    return [r, g, b];
}

/**
 * Вычисляет евклидово расстояние между двумя цветами в RGB пространстве
 */
function colorDistance(color1: [number, number, number], color2: [number, number, number]): number {
    const [r1, g1, b1] = color1;
    const [r2, g2, b2] = color2;

    return Math.sqrt(
        Math.pow(r2 - r1, 2) +
        Math.pow(g2 - g1, 2) +
        Math.pow(b2 - b1, 2)
    );
}

/**
 * Находит самый близкий цвет из палитры бренда и возвращает класс вида k-color-brand-red
 */
export function getClosestBrandColorClass(hexColor?: string): string {

    if (!hexColor) {
        return '';
    }

    try {
        const inputRgb = hexToRgb(hexColor);

        let closestColor: BrandColorName | null = null;
        let minDistance = Infinity;

        for (const [colorName, colorHex] of Object.entries(brandColors)) {
            const brandRgb = hexToRgb(colorHex);
            const distance = colorDistance(inputRgb, brandRgb);

            if (distance < minDistance) {
                minDistance = distance;
                closestColor = colorName as BrandColorName;
            }
        }

        return closestColor ? `k-color-brand-${closestColor}` : 'k-color-brand-red';
    } catch (error) {
        // В случае ошибки возвращаем дефолтный цвет
        return 'k-color-brand-red';
    }
}


export const VIEW_MODE: "default" | "menubar" = "default";

export const getDomains = () => {

    if (IS_DEV) {
        return ['http://localhost:8888'];
    }

    if ((window as any)?.apiUrl) {

        let url = new URL((window as any)?.apiUrl)
        return [url.origin];

    }



    return [
        window.location.origin
    ];

}

export const getEndpoint = () => {

    if (IS_DEV) {

        let path = location.pathname.split('?')[0]

        return path;
    }

    if ((window as any)?.apiUrl) {

        let url = new URL((window as any)?.apiUrl)
        return url.pathname;


    }

    let path = location.pathname.split('?')[0]
    return path;


}

export const getFullURL = () => {

    if (IS_DEV) {

        let path = location.pathname.split('?')[0]

        return `http://localhost:8888${path}`;
    }



    if ((window as any)?.apiUrl) {
        return (window as any).apiUrl;
    }

    let fullURL = window.location.href;

    //Remove all after #
    fullURL = fullURL.split('#')[0];

    //Remove all after ?
    fullURL = fullURL.split('?')[0];

    return fullURL;


}