---
import { isImageIcon, isInlineSvg } from "../theme/icon-kind.ts";
import { resolveIcon } from "../theme/icons.ts";
import { withBase } from "./islands/base-path.ts";

interface Props {
  name?: unknown;
  icon?: unknown;
  size?: number;
  class?: string;
  className?: string;
  color?: string;
  label?: string;
}

const {
  color,
  icon,
  name,
  size = 16,
  class: astroClass,
  className,
  label,
} = Astro.props;
const rawIcon = name ?? icon;
const customIcon =
  rawIcon !== undefined && rawIcon !== null && typeof rawIcon !== "string"
    ? rawIcon
    : null;
const iconName = typeof rawIcon === "string" ? rawIcon : null;
const rawSvg = iconName && isInlineSvg(iconName) ? iconName.trim() : null;
const imageSrc = iconName && !rawSvg && isImageIcon(iconName) ? iconName : null;
const resolvedIcon =
  iconName && !(imageSrc || rawSvg) ? resolveIcon(iconName) : null;
const resolvedClass = astroClass ?? className;
const customStyle = `display:inline-flex;width:${size}px;height:${size}px;${
  color ? `color:${color}` : ""
}`;
const style = color ? `color:${color}` : undefined;
---

{
  customIcon ? (
    <span
      aria-hidden={label ? undefined : "true"}
      aria-label={label}
      class={resolvedClass}
      role={label ? "img" : undefined}
      style={customStyle}
    >
      {customIcon}
    </span>
  ) : rawSvg ? (
    <span
      aria-hidden={label ? undefined : "true"}
      aria-label={label}
      class={resolvedClass}
      role={label ? "img" : undefined}
      set:html={rawSvg}
      style={customStyle}
    />
  ) : imageSrc ? (
    <img
      alt={label ?? ""}
      aria-hidden={label ? undefined : "true"}
      class={resolvedClass}
      height={size}
      src={withBase(imageSrc)}
      width={size}
    />
  ) : (
    resolvedIcon && (
    <svg
      aria-hidden={label ? undefined : "true"}
      aria-label={label}
      class={resolvedClass}
      height={size}
      role={label ? "img" : undefined}
      set:html={resolvedIcon.body}
      style={style}
      viewBox={resolvedIcon.viewBox}
      width={size}
      xmlns="http://www.w3.org/2000/svg"
    />
    )
  )
}
