<script lang="ts">
  import { getColorModeContext } from "../../stores/color-mode";
  import { getOptionalPackageInfoContext } from "../../stores/packageInfo";
  import { getPaywallContext } from "../../stores/paywall";
  import { getSelectedStateContext } from "../../stores/selected";
  import { getOptionalVariablesContext } from "../../stores/variables";
  import type { IconProps } from "../../types/components/icon";
  import {
    css,
    mapBorder,
    mapBorderRadius,
    mapColor,
    mapShadow,
    mapSize,
    mapSpacing,
  } from "../../utils/base-utils";
  import {
    evaluateVisibilityConditions,
    getActiveStateProps,
  } from "../../utils/style-utils";

  const props: IconProps = $props();
  const selectedState = getSelectedStateContext();
  const packageInfo = getOptionalPackageInfoContext();
  const { selectedPackageId } = getPaywallContext();
  const variables = getOptionalVariablesContext();
  const {
    base_url,
    formats,
    size,
    margin,
    padding,
    color,
    icon_background: background,
  } = $derived.by(() => {
    return {
      ...props,
      ...getActiveStateProps($selectedState, props.overrides),
    };
  });

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

  const container = $derived(
    css({
      width: mapSize(size.width),
      height: mapSize(size.height),
      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(
    evaluateVisibilityConditions(
      {
        selectedPackageId: $selectedPackageId,
        packageInfo: $packageInfo,
        variables: $variables ?? {},
      },
      props.overrides,
      props.visible,
    ),
  );

  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}
