/**
 * Uploads a file and reports real progress.
 * fetch() can't report upload progress, so this uses XMLHttpRequest.
 */
export function uploadFile(
  file: File,
  onProgress?: (percent: number) => void
): Promise<{ url: string; isVideo: boolean } | { error: string }> {
  return new Promise((resolve) => {
    const form = new FormData();
    form.append("file", file);

    const xhr = new XMLHttpRequest();
    xhr.open("POST", "/api/upload");

    xhr.upload.onprogress = (e) => {
      if (e.lengthComputable) {
        onProgress?.(Math.round((e.loaded / e.total) * 100));
      }
    };

    xhr.onload = () => {
      try {
        const d = JSON.parse(xhr.responseText);
        resolve(xhr.status < 300 ? d : { error: d.error ?? "Upload failed" });
      } catch {
        resolve({ error: "Upload failed" });
      }
    };

    xhr.onerror = () => resolve({ error: "Upload failed — check your connection" });
    xhr.send(form);
  });
}
