<script lang="ts">
  import Tag from "./Tag.svelte";

  type TagItem =
    | string
    | { name?: string; _slug?: string; icon?: string; color?: string };
  type Variant = "white" | "green" | "blue";

  let {
    tags = [],
    variant = "white",
    tagBase = null,
  }: {
    tags?: TagItem[];
    variant?: Variant;
    tagBase?: string | null;
  } = $props();

  function displayName(t: TagItem): string {
    if (typeof t === "string") return t;
    return (
      (t as { name?: string; _slug?: string })?.name ??
      (t as { _slug?: string })?._slug ??
      ""
    );
  }

  function slug(t: TagItem): string {
    if (typeof t === "string") return t;
    return (
      (t as { _slug?: string })?._slug ?? (t as { name?: string })?.name ?? ""
    );
  }

  function tagIcon(t: TagItem): string | null {
    if (typeof t === "string") return null;
    const i = (t as { icon?: string }).icon?.trim();
    return i || null;
  }

  function tagColor(t: TagItem): string | null {
    if (typeof t === "string") return null;
    const c = (t as { color?: string }).color?.trim();
    return c || null;
  }
</script>

{#each (tags ?? []) as t}
  {@const name = displayName(t)}
  {#if name}
    <Tag
      label={name}
      variant={variant}
      href={tagBase ? `${tagBase}/${slug(t)}` : null}
      icon={tagIcon(t)}
      customColor={tagColor(t)}
    />
  {/if}
{/each}
