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

export function createWater(
  scene: THREE.Scene,
  sunDirection: THREE.Vector3,
  waterNormals: THREE.Texture
): Water {
  const geometry = new THREE.PlaneGeometry(EnvConfig.water.size, EnvConfig.water.size);
  const water = new Water(geometry, {
    textureWidth: 512,
    textureHeight: 512,
    waterNormals,
    sunDirection: sunDirection.clone().normalize(),
    sunColor: 0xffffff,
    waterColor: EnvConfig.water.color,
    distortionScale: EnvConfig.water.distortionScale,
    fog: false,
    side: THREE.DoubleSide,
  });
  water.rotation.x = -Math.PI / 2;
  water.position.y = EnvConfig.water.positionY;
  scene.add(water);
  return water;
}

export function createSimpleWater(scene: THREE.Scene): void {
  const geometry = new THREE.PlaneGeometry(EnvConfig.water.size, EnvConfig.water.size);
  const material = new THREE.MeshStandardMaterial({
    color: EnvConfig.water.color,
    metalness: 0.1,
    roughness: 0.95,
  });
  const water = new THREE.Mesh(geometry, material);
  water.rotation.x = -Math.PI / 2;
  water.position.y = EnvConfig.water.positionY;
  scene.add(water);
}

const PLANE_NAMES = ['Plane', 'Plane001', 'Plane002', 'Plane003', 'Plane004', 'Plane005', 'Plane006'];

export async function createShip(scene: THREE.Scene, shipUrl: string): Promise<THREE.Group | null> {
  try {
    const model = await loadGlb(shipUrl);
    model.scale.setScalar(EnvConfig.ship.scale);
    model.traverse((c) => {
      if (c instanceof THREE.Mesh) {
        if (PLANE_NAMES.includes(c.name)) c.visible = false;
        c.castShadow = true;
        c.receiveShadow = true;
      }
    });
    scene.add(model);
    return model;
  } catch {
    // Fallback: simple box ship
    const hull = new THREE.Mesh(
      new THREE.BoxGeometry(8, 3, 20),
      new THREE.MeshStandardMaterial({ color: 0x4a3728, roughness: 0.8 })
    );
    hull.position.y = 1.5;
    hull.castShadow = true;
    const mast = new THREE.Mesh(
      new THREE.CylinderGeometry(0.3, 0.4, 12, 8),
      new THREE.MeshStandardMaterial({ color: 0x5a4a3a })
    );
    mast.position.set(0, 9, 0);
    const group = new THREE.Group();
    group.add(hull);
    group.add(mast);
    scene.add(group);
    return group;
  }
}
