<script setup lang="js">
import { onMounted, onUnmounted, ref } from "vue";
import * as THREE from "three";
import gsap from "gsap";

import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader.js";

const canvasRef = ref(null);
let renderer, scene, camera, model;

function initThree(canvas) {
  renderer = new THREE.WebGLRenderer({
    canvas,
    antialias: true,
    alpha: true,
  });

  renderer.outputColorSpace = THREE.SRGBColorSpace;
  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera(45, 1, 0.1, 100);
  camera.position.set(0, 0, 5);

  const light = new THREE.DirectionalLight(0xffffff, 1);
  light.position.set(2, 2, 5);
  scene.add(light);

  scene.add(new THREE.AmbientLight(0xffffff, 0.5));

  loadModel();

  gsap.ticker.add(render);
}

function loadModel() {
  if (model) {
    scene.remove(model);
  }
  let modelUrl = "/models/Monitor_draco.glb";
  let dracoPath = "/draco/";

  const dracoLoader = new DRACOLoader();
  dracoLoader.setDecoderPath(dracoPath);

  const loader = new GLTFLoader();
  loader.setDRACOLoader(dracoLoader);

  loader.load(
    modelUrl,
    (gltf) => {
      model = gltf.scene;

      const box = new THREE.Box3().setFromObject(model);
      const center = box.getCenter(new THREE.Vector3());
      const size = box.getSize(new THREE.Vector3());
      model.position.set(0, 0, 0);
      scene.add(model);

      document.title = "Model geladen";
    },
    (progress) => {
      const percent = ((progress.loaded / progress.total) * 100).toFixed(1);
      console.log(`Loading: ${percent}%`);
      document.title = `${percent}%`;
    },
    (error) => {
      console.error("Fehler beim Laden des Modells:", error);
      document.title = "Fehler beim Laden!";
    },
  );
}

function render() {
  if (!renderer) return;
  renderer.render(scene, camera);
}
function onResize() {
  if (!renderer || !canvasRef.value) return;
  const r = canvasRef.getBoundingClientRect();
  const dpr = Math.min(window.devicePixelRatio || 1, 2);

  const width = canvasRef.value.clientWidth;
  const height = canvasRef.value.clientHeight;

  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
  renderer.setSize(width, height, false);

  camera.aspect = (r.width || 1) / (r.height || 1);
  camera.updateProjectionMatrix();
}

onMounted(() => {
  initThree(canvasRef.value);
  onResize();
  window.addEventListener("resize", onResize);
});

onUnmounted(() => {
  gsap.ticker.remove(render);
  window.removeEventListener("resize", onResize);
  renderer?.dispose();
});
</script>
<template>
  <div class="wrapper">
    <div class="spacer">Scroll Down</div>

    <canvas class="canvas" ref="canvasRef"></canvas>
  </div>
</template>

<style>
.spacer {
  width: 100%;
  height: 20vh;
  display: grid;
  place-items: center;
  font-weight: 600;
}
.canvas {
  display: block;
}
</style>
