@use "sass:color";
@use "sass:math";
@use "sass:list";

@function rgb-to-hsl($color) {
  // Replace / with math.div() for all divisions
  $r: math.div(color.channel($color, "red", $space: rgb), 255);
  $g: math.div(color.channel($color, "green", $space: rgb), 255);
  $b: math.div(color.channel($color, "blue", $space: rgb), 255);

  $max: max($r, $g, $b);
  $min: min($r, $g, $b);
  $h: 0;
  $s: 0;
  $l: math.div($max + $min, 2);

  @if $max != $min {
    $d: $max - $min;
    $s: if($l > 0.5, math.div($d, 2 - $max - $min), math.div($d, $max + $min));

    @if $max == $r {
      $h: ((math.div($g - $b, $d) + if($g < $b, 6, 0)) * 60);
    } @else if $max == $g {
      $h: ((math.div($b - $r, $d) + 2) * 60);
    } @else {
      $h: ((math.div($r - $g, $d) + 4) * 60);
    }
  }

  @return ($h, $s * 100%, $l * 100%);
}

@function color-by-background($bg-color, $text-color, $inverted-text-color) {
  $bg-hsl: rgb-to-hsl($bg-color);
  $bg-lightness: list.nth($bg-hsl, 3); // Extract lightness component

  @if $bg-lightness > 50% {
    @return $text-color;
  } @else {
    @return $inverted-text-color;
  }
}