"use client";
import * as React from "react";
import {
  uploadAttachmentsForChat
} from "./upload-adapter.js";
const EMPTY_STATE = [];
function computeOverallProgress(entries) {
  if (entries.length === 0) return 0;
  const total = entries.reduce((sum, entry) => sum + entry.progress, 0);
  const average = total / entries.length;
  if (!Number.isFinite(average)) return 0;
  if (average < 0) return 0;
  if (average > 1) return 1;
  return average;
}
function useAiChatUpload(options = {}) {
  const [files, setFiles] = React.useState(EMPTY_STATE);
  const [busy, setBusy] = React.useState(false);
  const optionsRef = React.useRef(options);
  React.useEffect(() => {
    optionsRef.current = options;
  }, [options]);
  const overallProgress = React.useMemo(() => computeOverallProgress(files), [files]);
  const reset = React.useCallback(() => {
    setFiles(EMPTY_STATE);
    setBusy(false);
  }, []);
  const upload = React.useCallback(
    async (incoming) => {
      if (!incoming || incoming.length === 0) {
        return { items: [], failed: [] };
      }
      const initialEntries = incoming.map((file) => ({
        fileName: file.name,
        size: file.size,
        progress: 0,
        status: "uploading"
      }));
      setFiles(initialEntries);
      setBusy(true);
      const callerOptions = optionsRef.current;
      const callerProgress = callerOptions.onProgress;
      const result = await uploadAttachmentsForChat(incoming, {
        ...callerOptions,
        onProgress: (fileIndex, progress) => {
          const ratio = progress.total > 0 ? Math.max(0, Math.min(1, progress.loaded / progress.total)) : 0;
          setFiles((current) => {
            if (fileIndex < 0 || fileIndex >= current.length) return current;
            const next = current.slice();
            const entry = next[fileIndex];
            if (!entry) return current;
            next[fileIndex] = { ...entry, progress: ratio };
            return next;
          });
          if (callerProgress) {
            try {
              callerProgress(fileIndex, progress);
            } catch {
            }
          }
        }
      }).catch((err) => {
        const message = err instanceof Error ? err.message : "Upload batch failed.";
        return {
          items: [],
          failed: incoming.map((file, inputIndex) => ({
            fileName: file.name,
            originalFileName: file.name,
            inputIndex,
            reason: "network",
            message
          }))
        };
      });
      setFiles((current) => {
        const failedByName = /* @__PURE__ */ new Map();
        for (const failure of result.failed) {
          if (!failedByName.has(failure.fileName)) {
            failedByName.set(failure.fileName, failure);
          }
        }
        return current.map((entry, index) => {
          const success = result.items.find(
            (item, itemIndex) => itemIndex === index && item.fileName === entry.fileName
          );
          if (success) {
            return {
              ...entry,
              progress: 1,
              status: "done",
              attachmentId: success.attachmentId
            };
          }
          const failure = failedByName.get(entry.fileName);
          if (failure) {
            failedByName.delete(entry.fileName);
            return {
              ...entry,
              status: "error",
              reason: failure.reason,
              error: failure.message
            };
          }
          return {
            ...entry,
            status: "error",
            reason: "network"
          };
        });
      });
      setBusy(false);
      return result;
    },
    []
  );
  return {
    files,
    overallProgress,
    busy,
    upload,
    reset
  };
}
export {
  useAiChatUpload
};
//# sourceMappingURL=useAiChatUpload.js.map
