import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader';

const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/gltf/');
loader.setDRACOLoader(dracoLoader);

onmessage = (event) => {
    const { floorItems, cameraPosition, uuids, renderDistance } = event.data;
    if (!floorItems) return

    const toAdd = [];
    const toRemove = [];

    const cameraPos = new THREE.Vector3(cameraPosition.x, cameraPosition.y, cameraPosition.z);

    // Check for items to be added
    floorItems.forEach((item) => {
        const itemPosition = new THREE.Vector3(...item.position);
        const distance = cameraPos.distanceTo(itemPosition);

        if (distance <= renderDistance && !uuids.includes(item.modeluuid)) {
            toAdd.push(item);
        }
    });

    // Sort the toAdd array based on distance (closest first)
    toAdd.sort((a, b) => {
        const aDistance = cameraPos.distanceTo(new THREE.Vector3(...a.position));
        const bDistance = cameraPos.distanceTo(new THREE.Vector3(...b.position));
        return aDistance - bDistance;
    });

    // Check for items to be removed
    uuids.forEach((uuid) => {
        const floorItem = floorItems.find((item) => item.modeluuid === uuid);
        if (floorItem) {
            const itemPosition = new THREE.Vector3(...floorItem.position);
            const distance = cameraPos.distanceTo(itemPosition);

            if (distance > renderDistance) {
                toRemove.push(uuid);
            }
        }
    });

    // Send the result back to the main thread
    postMessage({ toAdd, toRemove });
};
