<script setup>
import { computed } from "vue";

const props = defineProps({
  name: { type: String, default: "" },
  size: {
    type: String,
    default: "md",
    validator: (value) => ["xs", "sm", "md", "lg", "xl"].includes(value),
  },
  class: { type: [String, Object, Array], default: "" },
});

const COLOR_CLASSES = [
  "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300",
  "bg-emerald-100 text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-300",
  "bg-lime-100 text-lime-800 dark:bg-lime-900/30 dark:text-lime-300",
  "bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300",
  "bg-sky-100 text-sky-800 dark:bg-sky-900/30 dark:text-sky-300",
  "bg-cyan-100 text-cyan-800 dark:bg-cyan-900/30 dark:text-cyan-300",
  "bg-teal-100 text-teal-800 dark:bg-teal-900/30 dark:text-teal-300",
  "bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300",
  "bg-violet-100 text-violet-800 dark:bg-violet-900/30 dark:text-violet-300",
  "bg-indigo-100 text-indigo-800 dark:bg-indigo-900/30 dark:text-indigo-300",
  "bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300",
  "bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300",
  "bg-rose-100 text-rose-800 dark:bg-rose-900/30 dark:text-rose-300",
  "bg-pink-100 text-pink-800 dark:bg-pink-900/30 dark:text-pink-300",
  "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300",
  "bg-slate-100 text-slate-800 dark:bg-slate-900/30 dark:text-slate-300",
];

const initials = computed(() => {
  const raw = (props.name || "").trim();
  if (!raw) return "?";

  const parts = raw.split(/\s+/).filter(Boolean);
  if (parts.length === 1) {
    const first = parts[0][0] ?? "";
    const second = parts[0][1] ?? "";
    return (first + second).toUpperCase();
  }

  const first = parts[0][0] ?? "";
  const last = parts[parts.length - 1][0] ?? "";
  return (first + last).toUpperCase();
});

const colorClass = computed(() => {
  const key = props.name || "user";
  let hash = 0;

  for (let i = 0; i < key.length; i += 1) {
    hash = (hash * 31 + key.charCodeAt(i)) >>> 0;
  }

  const index = COLOR_CLASSES.length ? hash % COLOR_CLASSES.length : 0;
  return COLOR_CLASSES[index] || "";
});

const sizeClass = computed(() => {
  switch (props.size) {
    case "xs":
      return "w-7 h-7 text-[0.625rem]";
    case "sm":
      return "w-8 h-8 text-xs";
    case "lg":
      return "w-10 h-10 text-sm";
    case "xl":
      return "w-12 h-12 text-base";
    case "md":
    default:
      return "w-9 h-9 text-sm";
  }
});
</script>

<template>
  <div
    class="inline-flex items-center justify-center rounded-full font-semibold select-none"
    :class="[colorClass, sizeClass, props.class]"
    role="img"
    :aria-label="name || 'Gebruiker'"
    :title="name"
  >
    <span aria-hidden="true">{{ initials }}</span>
  </div>
</template>
