import { useCallback, useRef, useState } from 'react';
/**
 * State machine for managing the file upload lifecycle.
 * The consumer provides an `upload` function — this hook never calls any API directly.
 */
export function useFileUploadStore(options) {
    const optionsRef = useRef(options);
    optionsRef.current = options;
    const [entries, setEntries] = useState([]);
    const idCounterRef = useRef(0);
    const nextId = useCallback(() => {
        idCounterRef.current += 1;
        return `file-${idCounterRef.current}`;
    }, []);
    const addFiles = useCallback((files) => {
        const { upload: up, withoutApply: wa, onUpload: ou, maxFiles: mf } = optionsRef.current;
        const pending = [];
        const filesToUpload = [];
        setEntries((prev) => {
            const remaining = mf === undefined ? files.length : Math.max(0, mf - prev.length);
            const sliced = files.slice(0, remaining);
            for (const file of sliced) {
                const id = nextId();
                pending.push({ id, file });
            }
            return [
                ...prev,
                ...pending.map(({ id, file }) => ({ status: 'pending', id, file })),
            ];
        });
        if (pending.length === 0)
            return;
        if (wa) {
            ou === null || ou === void 0 ? void 0 : ou(pending.map((e) => e.file));
            return;
        }
        filesToUpload.push(...pending);
        for (const { id, file } of filesToUpload) {
            setEntries((prev) => prev.map((e) => (e.id === id ? { status: 'uploading', id, file } : e)));
            up(file)
                .then((meta) => {
                setEntries((prev) => prev.map((e) => e.id === id ? { status: 'done', id, file, meta } : e));
            })
                .catch((error) => {
                setEntries((prev) => prev.map((e) => e.id === id ? { status: 'error', id, file, error } : e));
            });
        }
    }, [nextId]);
    const removeFile = useCallback((id) => {
        setEntries((prev) => prev.filter((e) => e.id !== id));
    }, []);
    const reset = useCallback(() => {
        setEntries([]);
    }, []);
    const isLoading = entries.some((e) => e.status === 'uploading');
    const uploadedMetas = entries
        .filter((e) => e.status === 'done')
        .map((e) => e.meta);
    return { entries, isLoading, addFiles, removeFile, reset, uploadedMetas };
}
//# sourceMappingURL=useFileUploadStore.js.map
