import * as THREE from 'three';
import { Sky } from 'three/addons/objects/Sky.js';
import { EnvConfig } from './config.js';

export function createScene(): { scene: THREE.Scene; sky: Sky; sun: THREE.Vector3 } {
  const scene = new THREE.Scene();

  const sky = new Sky();
  sky.scale.setScalar(EnvConfig.sky.scale);
  scene.add(sky);

  const uniforms = sky.material.uniforms;
  uniforms.turbidity.value = EnvConfig.sky.turbidity;
  uniforms.rayleigh.value = EnvConfig.sky.rayleigh;
  uniforms.mieCoefficient.value = EnvConfig.sky.mieCoefficient;
  uniforms.mieDirectionalG.value = EnvConfig.sky.mieDirectionalG;

  const phi = THREE.MathUtils.degToRad(90 - EnvConfig.sky.sunElevation);
  const theta = THREE.MathUtils.degToRad(EnvConfig.sky.sunAzimuth);
  const sun = new THREE.Vector3().setFromSphericalCoords(1, phi, theta);
  uniforms.sunPosition.value.copy(sun);

  return { scene, sky, sun };
}

export function setupSkyEnvironment(
  scene: THREE.Scene,
  renderer: THREE.WebGLRenderer,
  sky: Sky
): void {
  const pmrem = new THREE.PMREMGenerator(renderer);
  pmrem.compileEquirectangularShader();
  const envMap = pmrem.fromScene(sky as unknown as THREE.Scene, 0.04);
  scene.environment = envMap.texture;
}
