import Image from 'next/image';
import type { CmsSlot } from '@/components/cms/types';

export default function CmsElementProductManufacturerLogo({ slot }: { slot: CmsSlot }) {
  const manufacturer =
    slot.data?.manufacturer ??
    slot.data?.product?.manufacturer ??
    null;

  const media = manufacturer?.media ?? manufacturer?.translated?.media ?? null;
  const logoUrl: string | null = media?.url ?? null;
  const alt: string = media?.alt ?? manufacturer?.name ?? '';

  if (!logoUrl) {
    if (!alt) return null;
    return <span className="text-sm font-semibold text-surface-500 uppercase tracking-wider">{alt}</span>;
  }

  // SVG logos can't be resized by Next's optimizer (it refuses SVG by default),
  // so pass them through untouched. Raster logos go through the optimizer, which
  // resizes them to the displayed size and adds a long-lived cache header —
  // without this a tiny ~64px-tall logo can ship a multi-hundred-KB source.
  const isSvg = logoUrl.split('?')[0].toLowerCase().endsWith('.svg');

  return (
    <div className="flex items-center justify-end">
      <Image
        src={logoUrl}
        alt={alt}
        width={media?.width ?? 200}
        height={media?.height ?? 80}
        sizes="200px"
        className="max-h-16 w-auto object-contain"
        {...(isSvg ? { unoptimized: true } : {})}
      />
    </div>
  );
}
