<script setup lang="ts">
import { onMounted, watch } from 'vue';
import { useSimulation } from '../composables/useSimulation';
import { useThreeScene } from '../composables/three/useThreeScene';
import { useSunSystem } from '../composables/three/useSunSystem';
import { useCityObjects } from '../composables/three/useCityObjects';
import { useCameraControls } from '../composables/three/useCameraControls';
import { useInteraction } from '../composables/three/useInteraction';

// --- Simulation State ---
const { state, updateTime } = useSimulation();

// --- Composables ---
const { canvasContainer, initScene, getScene, getCamera, getRenderer } = useThreeScene();

// We can't access scene/camera until initScene runs, but we need to setup composables.
// Since scene creation is synchronous in initScene, we can wrap initialization in init().

const init = () => {
    initScene(); // Creates scene, camera, renderer

    const scene = getScene();
    const camera = getCamera();
    const renderer = getRenderer();

    // 1. City Objects
    const { initCity, interactableObjects, clearCity } = useCityObjects();
    // @ts-ignore - 'buildings' added to state dynamically
    initCity(scene, state.value.buildings);

    // Watch for new buildings
    watch(() => state.value.buildings.length, () => {
        clearCity(scene);
        // @ts-ignore
        initCity(scene, state.value.buildings);
    });

    // 2. Sun System
    const { initSun, updateSun } = useSunSystem(scene, state);
    initSun();

    // 3. Camera Controls
    const { initControls, updateControls, getControls } = useCameraControls(camera, renderer);
    initControls();

    // 4. Interaction
    const { initInteraction } = useInteraction(camera, renderer, scene, interactableObjects, getControls);
    initInteraction();

    // 5. Animation Loop
    const animate = () => {
        requestAnimationFrame(animate);
        
        const delta = 0.016; // Approx 60fps, or use clock
        updateTime(delta); 
        updateSun();
        updateControls();
        
        renderer.render(scene, camera);
    };

    animate();
};

onMounted(() => {
    init();
});
</script>

<template>
    <div ref="canvasContainer" class="canvas-container"></div>
</template>

<style scoped>
.canvas-container {
    width: 100%;
    height: 100vh;
    display: block;
}
</style>
