// App entry: polytrack_3d style - track on water, Sky, Water, OrbitControls.
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { createEnvironment, setupSkyEnvironment } from './index.js';

const container = document.getElementById('container')!;
const infoEl = document.getElementById('info')!;

const camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 0.1, 10000);
camera.position.set(200, 120, 200);
camera.lookAt(165, 0, 225);

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.toneMapping = THREE.LinearToneMapping;
renderer.toneMappingExposure = 2.75;
renderer.outputColorSpace = THREE.SRGBColorSpace;
container.appendChild(renderer.domElement);

const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(165, 0, 225);
controls.enableDamping = true;

async function init() {
  infoEl.textContent = 'Environment 14 · Loading...';
  const baseUrl = import.meta.env.BASE_URL || '/';
  const { scene, sky, water } = await createEnvironment(baseUrl);
  setupSkyEnvironment(scene, renderer, sky);

  infoEl.textContent = 'Environment 14 (polytrack_3d)';

  function animate() {
    requestAnimationFrame(animate);
    controls.update();
    if (water && (water.material as THREE.ShaderMaterial)?.uniforms?.time) {
      (water.material as THREE.ShaderMaterial).uniforms.time.value += 0.016 * 0.5;
    }
    renderer.render(scene, camera);
  }
  animate();
}

init().catch((err) => {
  console.error(err);
  infoEl.textContent = 'Environment 14 · Failed to load';
});

window.addEventListener('resize', () => {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
});
