import React, { createContext, useContext, useState } from "react"; import { api } from "../api/client"; export interface UploadContextModel { uploadFile: (file: File) => Promise; uploading: boolean; error: string | null; } const UploadContext = createContext(undefined); export const UploadProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { const [uploading, setUploading] = useState(false); const [error, setError] = useState(null); const uploadFile = async (file: File): Promise => { setUploading(true); setError(null); try { const arrayBuffer = await file.arrayBuffer(); const binary = new Uint8Array(arrayBuffer); const res = await api.post("/uploads", binary, { headers: { "Content-Type": file.type, "Content-Disposition": `attachment; filename="${file.name}"`, }, }); return res.data.url as string; } catch (err: any) { console.error("File upload failed:", err); setError(err.response?.data?.detail || "Failed to upload file"); return null; } finally { setUploading(false); } }; return ( {children} ); }; export const useUpload = (): UploadContextModel => { const ctx = useContext(UploadContext); if (!ctx) throw new Error("useUpload must be used within UploadProvider"); return ctx; };