// App entry: pirate_hunt_3d style - ship at sea, 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(0, 10, 40);
camera.lookAt(0, 0, 0);

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

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

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

  infoEl.textContent = 'Environment 13 (pirate_hunt_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 13 · Failed to load';
});

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