(function() {
    var ORBIT_RADIUS = 2.5;      // distance from origin
    var ORBIT_SPEED = 0.2;     // radians per second
    var SPIN_SPEED = 1.5;      // radians per second
    var ORBIT_Y = 2;         // height above ground
    
    var solids = ["tetrahedron", "cube", "octahedron", "dodecahedron", "icosahedron"];
    var count = solids.length;
    var entities = {};
    var startTime = Date.now();

    function findEntities() {
        var found = Entities.findEntities({x:0, y:0, z:0}, 200);
        solids.forEach(function(name) {
            found.forEach(function(id) {
                var props = Entities.getEntityProperties(id, ["name"]);
                if (props.name === name) {
                    entities[name] = id;
                }
            });
        });
        
        // If we didn't find all 5, try again shortly
        if (Object.keys(entities).length < solids.length) {
            print("Only found " + Object.keys(entities).length + " solids, retrying...");
            Script.setTimeout(findEntities, 500);
        } else {
            print("Found all solids, starting update loop");
            Script.update.connect(update);
        }
    }

    // Initial delay before first attempt
    Script.setTimeout(findEntities, 500);

    function update(dt) {
        var elapsed = (Date.now() - startTime) / 1000;
        
        solids.forEach(function(name, i) {
            var id = entities[name];
            if (!id) return;
            
            // orbit angle offset per solid so they're evenly spaced
            var orbitAngle = elapsed * ORBIT_SPEED + (i / count) * 2 * Math.PI;
            
            var x = Math.cos(orbitAngle) * ORBIT_RADIUS;
            var z = Math.sin(orbitAngle) * ORBIT_RADIUS;
            
            // spin around local Y axis
            var spinAngle = elapsed * SPIN_SPEED;
            
            Entities.editEntity(id, {
                position: { x: x, y: ORBIT_Y, z: z },
                rotation: Quat.fromPitchYawRollRadians(spinAngle, spinAngle, -spinAngle * 0.5)
            });
        });
    }

    Script.update.connect(update);
    findEntities();
})();
