"use client";

import Image from "next/image";
import { useTranslation } from "react-i18next";

/**
 * The horizontally scrolling images attached to a post or a reply. Clicking
 * one opens the lightbox.
 *
 * One component for what were three byte-similar copies of this strip —
 * `CommunityPostBody`, `InnerPostCard` and the reply rows — each of which had
 * the same two defects.
 *
 * Takes the payload shape — `reply_images[]`, where `image` is
 * `getimg($image->image)` and so **nullable** — and skips the null rows. The
 * previous signature declared `image: string`, which was a latent throw rather
 * than a cosmetic problem: `next/image` raises on a missing `src` where a bare
 * `<img>` merely drew a broken graphic.
 *
 * Each thumbnail is a real `<button>`, not an `<Image onClick>`. The handler
 * no longer takes the event: it was only ever used to stop the click reaching
 * a parent row's navigation, which a button in the normal flow does not need —
 * and an image with a click handler is unreachable by keyboard and announced
 * as a graphic rather than as something that opens.
 */
export default function CommunityImageStrip({
  images,
  onImageClick,
  altPrefix,
  className = "flex pt-4 pb-4 overflow-x-auto space-x-4 mb-4",
}: {
  images: ReadonlyArray<{ id?: number | string; image: string | null }> | null | undefined;
  onImageClick: (image: string) => void;
  /** Reads as "<altPrefix> 1", "<altPrefix> 2"… in the accessible name. */
  altPrefix: string;
  /** The row's own spacing, which differs between a post and a reply. */
  className?: string;
}) {
  const { t } = useTranslation();

  const shown = (images ?? []).filter(
    (entry): entry is { id?: number | string; image: string } =>
      typeof entry.image === "string" && entry.image.trim() !== ""
  );
  if (shown.length === 0) return null;

  return (
    <div className={className} id="style-1">
      {shown.map((imageObj, index) => (
        <button
          key={imageObj.id ?? imageObj.image}
          type="button"
          /* The layout classes move to the button so the strip is unchanged:
             the button is the flex item the image used to be. */
          className="flex-shrink-0 snap-center cursor-pointer hover:opacity-90 transition-opacity duration-200"
          onClick={() => onImageClick(imageObj.image)}
          title={t("COMMON.CLICK_TO_VIEW")}
        >
          <Image
            className="w-[300px] h-[200px] object-cover block"
            src={imageObj.image}
            width={300}
            height={200}
            unoptimized
            alt={`${altPrefix} ${index + 1}`}
          />
        </button>
      ))}
    </div>
  );
}
