"use client";

import { useEffect } from "react";

/**
 * Two unrelated broken-image gaps, both fixed the same way (swap to the
 * real `no-image.jpg` already in `public/images/`, not an invented
 * placeholder):
 *
 * 1. Free-tool pages' CMS bodies (`/summary-generator`,
 *    `/summary-writing-services`, ...) embed real `<img onerror="imgError
 *    (this);">` tags in their "related blog" card lists — a global JS
 *    function the live site defines in its own `custom.js`. This app had
 *    no `imgError` anywhere, so a broken image threw `ReferenceError:
 *    imgError is not defined` instead of silently falling back, same gap
 *    as `scrollTodiv` (see `BlogTocScroll`).
 *
 * 2. Separately: ~276 article bodies embed older content images via a
 *    literal `../GAH/data/page_upload/images/...` path (a real Joomla
 *    media-manager upload convention — confirmed by the same folder
 *    structure existing under a sibling brand's template,
 *    `templates/assignmentdesk/images/data/page_upload/`) whose actual
 *    files were never part of this local Joomla mirror's media library at
 *    all — not a URL-rewriting bug on this app's side, a genuine gap in
 *    what got copied into the local reference environment. No `onerror`
 *    attribute on these (unlike case 1), so they show the browser's
 *    native broken-image icon with no way to recover client-side other
 *    than listening for every `<img>`'s native `error` event directly.
 */
export function ImgErrorFallback() {
  useEffect(() => {
    (window as unknown as { imgError?: (img: HTMLImageElement) => void }).imgError = (img: HTMLImageElement) => {
      img.onerror = null;
      img.src = "/images/no-image.jpg";
    };

    // Capture phase: `error` events on `<img>` don't bubble, so this has to
    // listen on the ancestor with `capture: true` rather than a normal
    // delegated listener.
    const onImgError = (event: Event) => {
      const img = event.target;
      if (!(img instanceof HTMLImageElement)) return;
      if (img.dataset.fallbackApplied) return;
      img.dataset.fallbackApplied = "true";
      img.src = "/images/no-image.jpg";
    };
    document.addEventListener("error", onImgError, true);

    return () => {
      delete (window as unknown as { imgError?: (img: HTMLImageElement) => void }).imgError;
      document.removeEventListener("error", onImgError, true);
    };
  }, []);

  return null;
}
