"use client";

import Image from "next/image";
import { useState } from "react";

/**
 * A user-uploaded image — an avatar, a logo, a gallery photo — in a box whose
 * size is known.
 *
 * The reason this exists is **layout stability, not null handling**. Every call
 * site was a bare `<img>` with its size expressed only in Tailwind classes, so
 * the browser knew nothing about the box until the bytes arrived and each row
 * of avatars reflowed as they loaded. `next/image` requires `width`/`height`,
 * which reserves the box up front; the numbers passed in are the rendered size
 * read off the classes already on the element, so nothing about the layout
 * changes. (`images.unoptimized: true` means the request itself is still a
 * plain `<img>` fetch — see `next.config.ts`.)
 *
 * An earlier revision of this comment claimed that `profile_pic || default`
 * "let an empty-string column through". That was wrong: `"" || default` yields
 * the default, because `""` is falsy. The one value `||` really does let
 * through is a **whitespace-only** string, which is truthy and would reach
 * `src="   "`; `.trim()` below is what catches that.
 *
 * The `null` return is a guard for the declared type, not a bug being fixed:
 * `src` is `string | null | undefined`, and `next/image` *throws* on a missing
 * `src` where `<img>` merely drew a broken graphic. No current call site can
 * reach it — each one resolves to a local default first — but the type permits
 * it, so it is handled here rather than at fourteen call sites.
 */
export default function RemoteImage({
  src,
  alt,
  width,
  height,
  className,
  fallbackSrc,
}: {
  src?: string | null;
  alt: string;
  width: number;
  height: number;
  className?: string;
  fallbackSrc?: string;
}) {
  /* `.trim()` rather than a bare `||`: a whitespace-only value is truthy. */
  const [failedSrc, setFailedSrc] = useState<string | null>(null);
  const source = src?.trim() || "";
  const resolved = source && source !== failedSrc ? source : fallbackSrc?.trim() || "";
  if (!resolved) return null;

  return (
    <Image
      src={resolved}
      onError={fallbackSrc && resolved !== fallbackSrc ? () => setFailedSrc(source) : undefined}
      alt={alt}
      width={width}
      height={height}
      className={className}
      unoptimized
    />
  );
}
