import { useEffect, useState } from "react";
import type { Attachment } from "../../../types/post";

/**
 * Resolves each attachment's aspect ratio (width / height). Seeds from
 * backend-provided width/height when present (no flash), then refines by
 * loading the image and reading its intrinsic size — so it works even when the
 * backend omits dimensions. Entries are `undefined` until known.
 */
export function useImageRatios(
  attachments: Attachment[],
  sources: (string | undefined)[],
): (number | undefined)[] {
  const seed = attachments.map((a) =>
    a.width && a.height ? a.width / a.height : undefined,
  );
  const [ratios, setRatios] = useState<(number | undefined)[]>(seed);

  const key = sources.join("|");
  useEffect(() => {
    let cancelled = false;
    setRatios(
      attachments.map((a) =>
        a.width && a.height ? a.width / a.height : undefined,
      ),
    );
    sources.forEach((src, i) => {
      if (!src) return;
      const img = new Image();
      img.onload = () => {
        if (cancelled || !img.naturalWidth || !img.naturalHeight) return;
        setRatios((prev) => {
          const next = prev.slice();
          next[i] = img.naturalWidth / img.naturalHeight;
          return next;
        });
      };
      img.src = src;
    });
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [key]);

  return ratios;
}
