// --- Global Variables ---
let scene, camera, renderer, controls;

// --- Initialization ---
function init() {
    // Scene
    scene = new THREE.Scene();
    scene.background = new THREE.Color(0x9ee3f9);

    // Renderer
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.outputColorSpace = THREE.SRGBColorSpace;
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.outputEncoding = THREE.sRGBEncoding;
    renderer.shadowMap.enabled = true;
    //renderer.shadowMap.type = THREE.PCFSoftShadowMap;
    document.body.appendChild(renderer.domElement);

    initCameras(renderer);
    initSun(scene);
    initControls(scene, camera, renderer);
    initMotions();
    initPanels();

    // Event Listeners
    window.addEventListener('resize', onWindowResize, false);

    // Load the city model
    // Ground Plane (Unchanged)
    const groundGeometry = new THREE.PlaneGeometry(100, 100);
    const groundMaterial = new THREE.MeshLambertMaterial({ color: 0x91ca49, side: THREE.DoubleSide });
    const ground = new THREE.Mesh(groundGeometry, groundMaterial);
    const loader = new THREE.GLTFLoader();
    loader.load('assets/models/ground.glb', function (gltf) {
        const group = gltf.scene;
        group.traverse(function (child) {
            if (child.isMesh) {
                child.castShadow = true;
                child.receiveShadow = true;
                child.userData.parentGroup = group;
            }
        });
        buildings.push(group);
        scene.add(group);
    }, undefined, function (error) {s
        console.error('Error loading model:', error);
    });
    initBuildings();
    initTime();
}

// --- Animation Loop ---
function animate(timestamp) {
    requestAnimationFrame(animate);
    totalGameSecondsElapsed = animateUpdateTime(timestamp);
    updateBuildings();
    updatePanels();
    updateSun(scene);
    
    updateFps();
    
    animateCamera()
    controls.update();
    renderer.render(scene, camera);
}

// --- Start ---
window.onload = function () {
    init();
    animate(0); // Start animation loop, pass initial timestamp 0
}
