'use client';

import { useState } from 'react';
import type { PostImage } from '@ai-radar/shared';

/**
 * The story image.
 *
 * A plain `<img>`, not `next/image`. The optimiser needs every source
 * domain allowlisted in advance, and these URLs come from an external
 * agent pointing at whatever site published the story — an unlisted host
 * renders nothing at all, which is worse than an unoptimised image.
 *
 * **It removes itself when the image fails to load.** These URLs are
 * supplied by an agent and point at somebody else's CDN: they go stale,
 * get moved, and sometimes never existed. A broken-image box with alt
 * text sitting above the briefing looks like the site is broken, and the
 * design never depended on the image being there — so the honest
 * fallback is no image at all.
 */
export function StoryImage({ image }: { image: PostImage }) {
  const [failed, setFailed] = useState(false);

  if (failed) return null;

  return (
    <figure className="story-image">
      <img
        src={image.url}
        alt={image.alt}
        loading="lazy"
        decoding="async"
        // The URL usually points at a company's CDN, and there is no
        // reason to tell them which story on our site the reader is on.
        referrerPolicy="no-referrer"
        onError={() => setFailed(true)}
      />
      {image.credit && <figcaption>{image.credit}</figcaption>}
    </figure>
  );
}
