"use client";

import { useEffect, useState } from "react";

/**
 * Preview thumbnails come from object URLs, which have to be revoked when the
 * file list changes or the component unmounts — otherwise every re-pick leaks a
 * blob for the lifetime of the page.
 *
 * **Unresolved `react-hooks/set-state-in-effect` exception.** The report is on
 * the `setUrls` below and it is kept rather than silenced; the rule is not
 * disabled or downgraded anywhere in this project. The reasoning, and the
 * evidence for it:
 *
 *  - What the effect does is exactly what the rule's own message describes as
 *    legitimate — allocate against an external system (`URL.createObjectURL`)
 *    and release it again from the cleanup. The `setState` is only how the
 *    allocation is published to the tree; it is not a derivation that belongs
 *    in render.
 *  - Deriving in render instead means `useMemo`, and that is unsafe *here* in
 *    a way it usually is not: React documents a memo as a hint it may discard
 *    and recompute, and a discarded array of blob URLs has no cleanup path, so
 *    the leak this hook exists to prevent comes back. StrictMode makes it
 *    concrete rather than theoretical — the render runs twice, producing two
 *    sets of URLs, and a `useEffect` cleanup keyed on the memo only ever sees
 *    the second.
 *  - A lazy `useState` initialiser allocates once and then never tracks the
 *    file list, so re-picking shows the previous thumbnails.
 *  - `useSyncExternalStore` does not apply: there is no external store to
 *    subscribe to, and `getSnapshot` is called repeatedly and must be free of
 *    side effects, which allocating a blob is not.
 *
 * The cleanup is covered by `tests/objectUrlLifecycle.test.ts`, which counts
 * `createObjectURL` against `revokeObjectURL` across a file-list change, a
 * StrictMode mount and an unmount. Exported for that reason.
 *
 * `files` is the caller's own state in both call sites, so its identity is
 * stable between picks and this does not re-allocate on every render.
 */
export function useObjectUrls(files: File[]) {
  const [urls, setUrls] = useState<string[]>([]);

  useEffect(() => {
    const created = files.map((file) => URL.createObjectURL(file));
    setUrls(created);
    return () => created.forEach((url) => URL.revokeObjectURL(url));
  }, [files]);

  return urls;
}
