@use "sass:math";

@function hex-alpha($color, $opacity: 1) {
    // Handle cases where color might be passed in parentheses (as a list)
    @if type-of($color) == 'list' {
        $color: nth($color, 1);
    }

    // Handle CSS variables (e.g., --edbi-primary-color or var(--edbi-primary-color))
    @if type-of($color) == 'string' {
        @if str-slice($color, 1, 2) == '--' {
            @return color-mix(in srgb, var(#{$color}), transparent math.percentage(1 - $opacity));
        } @else if str-slice($color, 1, 4) == 'var(' {
            @return color-mix(in srgb, #{$color}, transparent math.percentage(1 - $opacity));
        }
    }

    // Ensure opacity is between 0 and 1
    $opacity: math.clamp(0, $opacity, 1);

    // If it's a real Sass color, use built-in rgba (which Sass can render as hex or rgba)
    @if type-of($color) == 'color' {
        @return rgba($color, $opacity);
    }

    // Manual hex conversion fallback for strings that are hex values
    $alpha-dec: round($opacity * 255);
    $alpha-hex: str-slice("0123456789ABCDEF", math.floor(math.div($alpha-dec, 16)) + 1, math.floor(math.div($alpha-dec, 16)) + 1)
                + str-slice("0123456789ABCDEF", ($alpha-dec % 16) + 1, ($alpha-dec % 16) + 1);

    @return unquote("#{$color}#{$alpha-hex}");
}
