"use client";

import { useEffect, useRef } from "react";

/**
 * Renders sanitized article HTML and hides any image that fails to load.
 *
 * A number of CMS records point at assets that 404 on the marketing host, and
 * a broken <img> still occupies its alt/placeholder box in the flow. There is
 * no CSS selector for "failed to load", and these images come from a raw HTML
 * string rather than JSX, so the check has to run against the DOM after mount:
 * images already settled by then report naturalWidth 0, and ones still in
 * flight are caught by the error listener.
 */
export function BlogContent({ html }: { html: string }) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const root = ref.current;
    if (!root) return;

    const hide = (img: HTMLImageElement) => {
      img.style.display = "none";
    };
    const onError = (event: Event) => hide(event.currentTarget as HTMLImageElement);

    const images = Array.from(root.querySelectorAll("img"));
    for (const img of images) {
      if (img.complete && img.naturalWidth === 0) hide(img);
      else img.addEventListener("error", onError);
    }

    return () => {
      for (const img of images) img.removeEventListener("error", onError);
    };
  }, [html]);

  return (
    <div ref={ref} className="blog-detail-content" dangerouslySetInnerHTML={{ __html: html }} />
  );
}
