/**
 * @typedef {Object} RgbColor
 * @property {number} r
 * @property {number} g
 * @property {number} b
 */

/**
 * @description 解析 rgb 字符串
 * @param {string} colorString 形如 #1e90ff 或者 rgba(0, 206, 209, 1) 这样的字符串
 * @returns {RgbColor | undefined}
 */
export function parseColor(colorString) {
    // 检查是否是十六进制颜色
    if (colorString.startsWith('#')) {
        let hex = colorString.slice(1);
        if (hex.length === 3) {
            hex = hex.split('').map(c => c + c).join('');
        }
        const r = parseInt(hex.slice(0, 2), 16);
        const g = parseInt(hex.slice(2, 4), 16);
        const b = parseInt(hex.slice(4, 6), 16);
        return { r, g, b };
    }
    // 检查是否是 RGBA 颜色
    else if (colorString.startsWith('rgba')) {
        const matches = colorString.match(/rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d+(\.\d+)?)\)/);
        if (matches) {
            const r = parseInt(matches[1], 10);
            const g = parseInt(matches[2], 10);
            const b = parseInt(matches[3], 10);
            return { r, g, b };
        }
    }
    // 检查是否是 RGB 颜色
    else if (colorString.startsWith('rgb')) {
        const matches = colorString.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
        if (matches) {
            const r = parseInt(matches[1], 10);
            const g = parseInt(matches[2], 10);
            const b = parseInt(matches[3], 10);
            return { r, g, b };
        }
    }

    return undefined;
}

/**
 * @description 提升颜色的亮度
 * @param {RgbColor} rgb 
 * @param {number} percent 0 - 100 的数字，代表增强的亮度比例
 * @returns {RgbColor}
 */
export function increaseBrightness(rgb, percent) {
    // 确保 percent 在 0 到 100 之间
    percent = Math.max(0, Math.min(100, percent));

    // 计算每个颜色分量的增量
    const increment = (percent / 100) * 255;

    // 提升每个颜色分量的亮度
    const r = Math.min(255, Math.round(rgb.r + increment));
    const g = Math.min(255, Math.round(rgb.g + increment));
    const b = Math.min(255, Math.round(rgb.b + increment));

    return { r, g, b };
}


/**
 * @description gamma 修正
 * @param {number} c 颜色通道值，取值范围为 0 - 255
 */
function gammaCorrected(c) {
    c /= 255;
    return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
}

/**
 * @description 判断是否为亮色主题
 * @param {number} r 
 * @param {number} g 
 * @param {number} b 
 */
export function isLightColorTheme(r, g, b) {
    r = gammaCorrected(r);
    g = gammaCorrected(g);
    b = gammaCorrected(b);
    const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
    return luminance > 0.5;
}