// Plutus Three.js Environment 13: pirate_hunt_3d style (ship at sea, Sky, Water shader).

import * as THREE from 'three';
import { createScene, setupSkyEnvironment } from './createScene.js';
import { createLighting } from './createLighting.js';
import { createWater, createSimpleWater, createShip } from './map.js';
import { loadGameAssets, loadTexture } from './loadAssets.js';

export { loadGameAssets, loadTexture, loadGlb } from './loadAssets.js';
export { createScene, setupSkyEnvironment } from './createScene.js';
export { createLighting } from './createLighting.js';
export { createWater, createSimpleWater, createShip } from './map.js';

export async function createEnvironment(baseUrl = '/') {
  const assets = await loadGameAssets(baseUrl);
  const { scene, sky, sun } = createScene();
  createLighting(scene);

  let waterNormals: THREE.Texture | null = null;
  const waterUrl = assets.waterNormals;
  if (waterUrl) {
    try {
      waterNormals = await loadTexture(waterUrl);
    } catch {
      // fallback handled below
    }
  }

  let water: THREE.Mesh | null = null;
  if (waterNormals) {
    water = createWater(scene, sun, waterNormals) as unknown as THREE.Mesh;
  } else {
    createSimpleWater(scene);
  }

  const shipUrl = assets.ship;
  if (shipUrl) {
    const resolved = shipUrl.startsWith('http') ? shipUrl : (baseUrl.replace(/\/$/, '') + '/' + shipUrl);
    await createShip(scene, resolved);
  }

  return { scene, sky, sun, water };
}
