import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';

export class SceneLoader {
  constructor() {
    this.loadingScreen = document.getElementById('loading-screen');
    this.loadingText = document.getElementById('loading-text');
    this.loadingProgressBar = document.getElementById('loading-progress-bar');
    this.loadingPercentage = document.getElementById('loading-percentage');
    this.modelsToLoad = [
      { file: 'bold.glb', type: 'bold' },
      { file: 'innovation.glb', type: 'innovation' },
      { file: 'agility.glb', type: 'agility' },
      { file: 'storytelling.glb', type: 'storytelling' }
    ];
    this.loadedModels = {};
    this.loadedCount = 0;
    this.totalModels = this.modelsToLoad.length;
  }

  setLoadingMessage(message) {
    this.loadingText.textContent = message;
  }

  updateProgress(progress) {
    const percentage = Math.round(progress * 100);
    this.loadingProgressBar.style.width = `${percentage}%`;
    this.loadingPercentage.textContent = `${percentage}%`;
  }

  hideLoadingScreen() {
    this.loadingScreen.classList.add('hidden');
    setTimeout(() => {
      this.loadingScreen.style.display = 'none';
    }, 800);
  }

  async loadAllModels() {
    return new Promise((resolve) => {
      const loader = new GLTFLoader();
      const dracoLoader = new DRACOLoader();
      dracoLoader.setDecoderPath('node_modules/three/examples/jsm/libs/draco/');
      loader.setDRACOLoader(dracoLoader);

      this.modelsToLoad.forEach((modelInfo, index) => {
        this.setLoadingMessage(`Loading experience...`);
        loader.load(`/${modelInfo.file}`,
          (gltf) => {
            this.loadedModels[modelInfo.type] = {
              scene: gltf.scene,
              animations: gltf.animations,
              gltf: gltf
            };
            this.loadedCount++;
            const progress = this.loadedCount / this.totalModels;
            this.updateProgress(progress);
            if (this.loadedCount === this.totalModels) {
              this.setLoadingMessage('Initializing Experience...');
              setTimeout(() => {
                this.hideLoadingScreen();
                resolve(this.loadedModels);
              }, 500);
            }
          },
          (progress) => {
            const fileProgress = progress.loaded / progress.total;
            const totalProgress = (this.loadedCount + fileProgress) / this.totalModels;
            this.updateProgress(totalProgress);
          },
          (error) => {
            console.error(`Error loading ${modelInfo.file}:`, error);
          }
        );
      });
    });
  }
}
