"use client";

import { useState } from "react";

/**
 * Portrait plate with a printed-monogram fallback.
 *
 * Two instructor photographs on the upstream TECH-C host return 404, and the
 * page must not show a broken-image glyph. When the source fails we render the
 * person's initials on the paper stock instead — which reads as an intentional
 * placeholder in this layout rather than an error.
 */
export function PersonPlate({
  src,
  name,
  size = "md",
}: {
  src: string;
  name: string;
  size?: "md" | "lg";
}) {
  const [failed, setFailed] = useState(false);

  const box = size === "lg" ? "h-24 w-20" : "h-20 w-16";
  const initials = name
    .replace(/\b(S\.Pd|S\.Kom|S\.T|M\.Pd|M\.Kom)\b/gi, "")
    .trim()
    .split(/\s+/)
    .slice(0, 2)
    .map((w) => w[0]?.toUpperCase() ?? "")
    .join("");

  return (
    <div className={`${box} shrink-0 overflow-hidden border border-doc-line bg-doc-paper-2`}>
      {failed ? (
        <div className="grid size-full place-items-center bg-doc-paper-2">
          <span className="display text-[1.05rem] text-doc-ink-3">{initials}</span>
        </div>
      ) : (
        /* eslint-disable-next-line @next/next/no-img-element */
        <img
          src={src}
          alt={name}
          loading="lazy"
          onError={() => setFailed(true)}
          className="plate-img size-full object-contain"
        />
      )}
    </div>
  );
}
