import { useState } from "react";
import { categoryMeta, merchantLogoUrl, initials } from "@/lib/categories";
import { cn } from "@/lib/utils";

export function CategoryIcon({ category, size = 36, className }: { category?: string | null; size?: number; className?: string }) {
  const { icon: Icon, tint } = categoryMeta(category);
  return (
    <div
      className={cn("rounded-full grid place-items-center shrink-0", className)}
      style={{ width: size, height: size, background: `color-mix(in oklab, ${tint} 18%, transparent)`, color: tint }}
      aria-hidden
    >
      <Icon style={{ width: size * 0.45, height: size * 0.45 }} strokeWidth={2} />
    </div>
  );
}

/** Merchant logo with graceful fallback to a category-tinted icon or initials. */
export function MerchantAvatar({
  merchant, category, size = 36,
}: { merchant?: string | null; category?: string | null; size?: number }) {
  const [failed, setFailed] = useState(false);
  const url = merchantLogoUrl(merchant);

  if (!url || failed) {
    if (merchant) {
      const { tint } = categoryMeta(category);
      return (
        <div
          className="rounded-full grid place-items-center shrink-0 font-semibold"
          style={{ width: size, height: size, background: `color-mix(in oklab, ${tint} 18%, transparent)`, color: tint, fontSize: size * 0.34 }}
        >
          {initials(merchant)}
        </div>
      );
    }
    return <CategoryIcon category={category} size={size} />;
  }

  return (
    <img
      src={url}
      alt={`${merchant} logo`}
      loading="lazy"
      onError={() => setFailed(true)}
      className="rounded-full object-contain bg-white/90 shrink-0"
      style={{ width: size, height: size }}
    />
  );
}
