import { useEffect, useState } from "react";
import { buildLoreIndex } from "./lore";

// `public/Lore.csv` is ~400KB, so it is fetched once, lazily, and shared by
// every card rather than bundled into the main chunk.  The promise is cached at
// module scope: a roster renders 20-odd Units, and they must not each kick off
// their own request.
let pending;

const loadLore = () => {
	if (!pending) {
		pending = fetch("Lore.csv")
			.then((response) => {
				if (!response.ok) throw new Error(`Lore.csv: ${response.status}`);
				return response.text();
			})
			.then(buildLoreIndex)
			.catch((error) => {
				// A missing or unreadable export is not worth failing a card over -
				// the datasheet simply prints without its flavour text.
				console.error(error);
				return { lookup: () => undefined, size: 0 };
			});
	}
	return pending;
};

/**
 * Resolves to the lore index, or `null` until it has loaded.
 */
export const useLore = () => {
	const [index, setIndex] = useState(null);

	useEffect(() => {
		let live = true;
		loadLore().then((loaded) => live && setIndex(loaded));
		return () => {
			live = false;
		};
	}, []);

	return index;
};
