import { getImageField } from "@/utils/format";
import { avatarColor } from "@/theme/accents";
import type { RecordSpec, DataRow } from "@/types/spec";

interface TilesViewProps {
  rows: DataRow[];
  rec: RecordSpec | undefined;
  titleField: string;
  onViewDetail: (table: string, id: string) => void;
  table: string;
}

/** Image-forward compact grid — like a gallery/portfolio view. */
export function TilesView({ rows, rec, titleField, onViewDetail, table }: TilesViewProps) {
  return (
    <div class="grid gap-2" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(160px, 1fr))" }}>
      {rows.map((row) => {
        const image = getImageField(row, rec);
        const title = String(row[titleField] || "—");
        const color = avatarColor(title);
        return (
          <div
            key={String(row.id)}
            class="relative rounded-[var(--z-radius-card)] overflow-hidden cursor-pointer transition-all hover:scale-[1.02] hover:shadow-lg aspect-square"
            style={{ border: "var(--z-card-border)", boxShadow: "var(--z-card-shadow)" }}
            onClick={() => onViewDetail(table, String(row.id))}
          >
            {image ? (
              <img src={image} alt={title} class="w-full h-full object-cover" />
            ) : (
              <div class="w-full h-full flex items-center justify-center text-4xl font-bold" style={{ background: `${color}15`, color: `${color}80` }}>
                {title.charAt(0).toUpperCase()}
              </div>
            )}
            <div class="absolute bottom-0 left-0 right-0 px-2 py-1.5" style={{ background: "linear-gradient(transparent, rgba(0,0,0,0.7))" }}>
              <p class="text-[var(--z-font-sm)] font-medium text-white truncate">{title}</p>
            </div>
          </div>
        );
      })}
    </div>
  );
}
