import { ref } from 'vue';
import * as THREE from 'three';

export default function useFileLoader() {
  const loading = ref(false);
  const progress = ref(0);
  const error = ref(null);

  const requestData = async (url) => {
    loading.value = true;
    error.value = null;
    progress.value = 0;

    try {
      const loader = new THREE.FileLoader();
      
      return new Promise((resolve, reject) => {
        loader.load(
          url,
          // onLoad
          (data) => {
            try {
              const jsonData = JSON.parse(data);
              loading.value = false;
              progress.value = 100;
              resolve(jsonData);
            } catch (parseError) {
              error.value = parseError;
              loading.value = false;
              reject(parseError);
            }
          },
          // onProgress
          (progressEvent) => {
            if (progressEvent.lengthComputable) {
              progress.value = (progressEvent.loaded / progressEvent.total) * 100;
            }
          },
          // onError
          (err) => {
            error.value = err;
            loading.value = false;
            reject(err);
          }
        );
      });
    } catch (err) {
      error.value = err;
      loading.value = false;
      throw err;
    }
  };

  return {
    loading,
    progress,
    error,
    requestData
  };
}