<script lang="ts">
  import { getColorModeContext } from "../../stores/color-mode";
  import { useConditionContext } from "../../stores/condition-context.svelte";
  import type { IconProps } from "../../types/components/icon";
  import {
    css,
    mapBorder,
    mapBorderRadius,
    mapColor,
    mapFillBounds,
    mapShadow,
    mapSize,
    mapSpacing,
  } from "../../utils/base-utils";
  import { resolveOverrideProperties } from "../../utils/style-utils";

  const props: IconProps = $props();
  const buildConditionContext = useConditionContext({ state: true });
  const {
    base_url,
    formats,
    size,
    margin,
    padding,
    color,
    icon_background: background,
    visible,
  } = $derived.by(() => {
    return {
      ...props,
      ...resolveOverrideProperties(buildConditionContext(), props.overrides),
    };
  });

  const getColorMode = getColorModeContext();
  const colorMode = $derived(getColorMode());

  const container = $derived(
    css({
      width: mapSize(size.width),
      height: mapSize(size.height),
      ...mapFillBounds(size),
      margin: mapSpacing(margin),
      padding: mapSpacing(padding),
      "background-color": mapColor(colorMode, background?.color),
      ...mapBorder(colorMode, background?.border),
      "border-radius": mapBorderRadius(background?.shape),
      "box-shadow": mapShadow(colorMode, background?.shadow),
      flex: "0 0 auto",
    }),
  );

  const isVisible = $derived(visible !== false);

  const webpUrl = $derived(`${base_url}/${formats.webp}`);
  const icon = $derived(
    css({
      width: "100%",
      height: "100%",
      position: "relative",
      "z-index": 1,
      overflow: "hidden",
      "background-color": mapColor(colorMode, color),
      "mask-image": `url(${webpUrl})`,
      "-webkit-mask-image": `url(${webpUrl})`,
      "mask-size": "contain",
      "-webkit-mask-size": "contain",
      "mask-position": "center",
      "-webkit-mask-position": "center",
      "mask-repeat": "no-repeat",
      "-webkit-mask-repeat": "no-repeat",
    }),
  );
</script>

{#if isVisible}
  <div class="rc-gradient-border" style={container}>
    <div style={icon}></div>
  </div>
{/if}
