"use client";

import { useState, type CSSProperties } from "react";
import { CATEGORIES } from "@/lib/ui-config";
import type { CategoryId } from "@/lib/types";
import { Icons } from "./icons";

export function CategoryTile({
  category,
  size = "sm",
}: {
  category: CategoryId;
  size?: "sm" | "md" | "lg";
}) {
  const cat = CATEGORIES[category] || CATEGORIES.other;
  const Icon = Icons[cat.icon as keyof typeof Icons];
  const iconSize = { sm: 22, md: 28, lg: 40 }[size];
  return (
    <div
      className="cat-tile"
      style={{ ["--cat-color" as string]: cat.color } as CSSProperties}
    >
      <Icon size={iconSize} stroke={1.6} />
    </div>
  );
}

export function CoverImage({
  src,
  alt,
  category,
  style,
}: {
  src?: string | null;
  alt?: string;
  category: CategoryId;
  style?: CSSProperties;
}) {
  const [err, setErr] = useState(false);
  if (!src || err) {
    return (
      <div
        className="cover-fallback"
        style={
          {
            ...style,
            "--cat-color": (CATEGORIES[category] || CATEGORIES.other).color,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          } as CSSProperties
        }
      >
        <CategoryTile category={category} size="md" />
      </div>
    );
  }
  return (
    // eslint-disable-next-line @next/next/no-img-element
    <img
      src={src}
      alt={alt}
      onError={() => setErr(true)}
      style={{ objectFit: "cover", ...style }}
    />
  );
}
