"use client";

import { CategoryPresetIcon } from "@/components/menu/category-preset-icon";
import { resolveMediaUrl } from "@/lib/api/client";
import type { CafeThemePalette } from "@/lib/cafe-theme";
import { cn } from "@/lib/utils";

type CategoryVisualProps = {
  icon?: string | null;
  iconPresetId?: string | null;
  iconStyle?: string | null;
  imageUrl?: string | null;
  size?: "xs" | "sm" | "md";
  className?: string;
  brandColors?: Pick<
    CafeThemePalette,
    "primary" | "secondary" | "accent" | "surface" | "textMuted"
  >;
};

const sizeClasses = {
  xs: "h-5 w-5 text-sm",
  sm: "h-7 w-7 text-base",
  md: "h-10 w-10 text-xl",
} as const;

export function CategoryVisual({
  icon,
  iconPresetId,
  iconStyle,
  imageUrl,
  size = "sm",
  className,
  brandColors,
}: CategoryVisualProps) {
  const imgSrc = resolveMediaUrl(imageUrl);
  const emoji = icon?.trim();

  if (imgSrc) {
    return (
      // eslint-disable-next-line @next/next/no-img-element
      <img
        src={imgSrc}
        alt=""
        className={cn(
          "shrink-0 rounded-md border border-border/80 object-cover",
          sizeClasses[size],
          className
        )}
      />
    );
  }

  if (iconPresetId) {
    return (
      <CategoryPresetIcon
        presetId={iconPresetId}
        style={iconStyle}
        size={size}
        className={className}
        brandColors={brandColors}
      />
    );
  }

  if (emoji) {
    return (
      <span
        className={cn(
          "flex shrink-0 items-center justify-center rounded-md border",
          brandColors ? "qr-border" : "border-border/60 bg-muted/40",
          sizeClasses[size],
          className
        )}
        style={
          brandColors
            ? {
                backgroundColor: `color-mix(in srgb, ${brandColors.secondary} 55%, ${brandColors.surface})`,
                borderColor: `color-mix(in srgb, ${brandColors.primary} 18%, transparent)`,
              }
            : undefined
        }
        aria-hidden
      >
        {emoji}
      </span>
    );
  }

  return null;
}
