window.sketch = ({ AFRAME, scene, startFrame }) => {
  const centerpiece = document.querySelector('#centerpiece-entity');
  const bgImg = document.querySelector('#bg');
  const bgPlane = document.querySelector('#bg-plane');
  const particlesContainer = document.querySelector('#particles');

  centerpiece.addEventListener('model-loaded', (event) => {
    const mesh = event.detail.model || centerpiece.getObject3D('mesh');
    if (!mesh) return;
    const box = new THREE.Box3().setFromObject(mesh);
    const size = box.getSize(new THREE.Vector3());
    const center = box.getCenter(new THREE.Vector3());
    mesh.position.sub(center);
    const maxDim = Math.max(size.x, size.y, size.z);
    const targetSize = 2.5;
    const scale = targetSize / maxDim;
    centerpiece.setAttribute('scale', `${scale} ${scale} ${scale}`);
  });

  bgImg.addEventListener('load', () => {
    const imgAspect = bgImg.naturalWidth / bgImg.naturalHeight;
    const distance = 16;
    const fov = 80;
    const visibleHeight = 2 * distance * Math.tan((fov / 2) * Math.PI / 180);
    const sceneAspect = window.innerWidth / window.innerHeight;
    const visibleWidth = visibleHeight * sceneAspect;
    const planeWidth = Math.max(visibleWidth, visibleHeight * imgAspect);
    const planeHeight = planeWidth / imgAspect;
    bgPlane.setAttribute('width', planeWidth);
    bgPlane.setAttribute('height', planeHeight);
  });

  const colors = ['#ff0080', '#00ddff', '#ffee00', '#ff6600', '#aa00ff', '#00ff88', '#ff0044', '#88ff00', '#ff44ff', '#44ffff'];

  const rings = [
    { radius: 2.8, count: 16, tiltX: 0,  tiltZ: 0,  speed: 22, bobDur: 3000 },
    { radius: 3.3, count: 20, tiltX: 62, tiltZ: 0,  speed: -30, bobDur: 4200 },
    { radius: 3.0, count: 14, tiltX: -48, tiltZ: 28, speed: 26, bobDur: 3600 }
  ];

  rings.forEach((ring, ringIdx) => {
    for (let i = 0; i < ring.count; i++) {
      const angle = (i / ring.count) * Math.PI * 2;
      const r = ring.radius + (Math.random() - 0.5) * 0.35;
      const x = Math.cos(angle) * r;
      const z = Math.sin(angle) * r;
      const y = (Math.random() - 0.5) * 0.5;

      const color = colors[(i * 3 + ringIdx * 2) % colors.length];
      const size = 0.04 + Math.random() * 0.08;

      const orbitGroup = document.createElement('a-entity');
      orbitGroup.setAttribute('rotation', `${ring.tiltX} 0 ${ring.tiltZ}`);
      orbitGroup.setAttribute('animation__rotate',
        `property: rotation; from: ${ring.tiltX} 0 ${ring.tiltZ}; to: ${ring.tiltX} 360 ${ring.tiltZ}; dur: ${Math.abs(ring.speed) * 1000}; loop: true; easing: linear; dir: ${ring.speed > 0 ? 'normal' : 'reverse'}`);

      const particle = document.createElement('a-sphere');
      particle.setAttribute('radius', size);
      particle.setAttribute('material', `color: ${color}; emissive: ${color}; emissiveIntensity: 0.65; metalness: 0.4; roughness: 0.3`);
      particle.setAttribute('position', `${x} ${y} ${z}`);

      const bobAmount = 0.15 + Math.random() * 0.22;
      const bobDur = ring.bobDur + Math.random() * 1200;
      const phase = Math.random() * 2000;
      particle.setAttribute('animation__bob',
        `property: position; from: ${x} ${y} ${z}; to: ${x} ${y + bobAmount} ${z}; dur: ${bobDur}; delay: ${phase}; dir: alternate; loop: true; easing: easeInOutSine`);

      const pulseDur = 1500 + Math.random() * 1800;
      const phase2 = Math.random() * 1000;
      particle.setAttribute('animation__pulse',
        `property: scale; from: 0.7 0.7 0.7; to: 1.5 1.5 1.5; dur: ${pulseDur}; delay: ${phase2}; dir: alternate; loop: true; easing: easeInOutSine`);

      orbitGroup.appendChild(particle);
      particlesContainer.appendChild(orbitGroup);
    }
  });

  // Stray chaotic particles for "interplay of structure and chaos"
  for (let i = 0; i < 12; i++) {
    const drift = document.createElement('a-sphere');
    const radius = 0.04 + Math.random() * 0.05;
    const c = colors[Math.floor(Math.random() * colors.length)];
    const px = (Math.random() - 0.5) * 5;
    const py = (Math.random() - 0.5) * 3;
    const pz = (Math.random() - 0.5) * 3;
    drift.setAttribute('radius', radius);
    drift.setAttribute('material', `color: ${c}; emissive: ${c}; emissiveIntensity: 0.5; opacity: 0.7; transparent: true`);
    drift.setAttribute('position', `${px} ${py} ${pz}`);
    drift.setAttribute('animation__driftx',
      `property: position; from: ${px} ${py} ${pz}; to: ${px + (Math.random()-0.5)*2} ${py} ${pz}; dur: ${6000 + Math.random()*6000}; dir: alternate; loop: true; easing: easeInOutSine`);
    drift.setAttribute('animation__drifty',
      `property: position; from: ${px} ${py} ${pz}; to: ${px} ${py + (Math.random()-0.5)*1.5} ${pz}; dur: ${5000 + Math.random()*5000}; dir: alternate; loop: true; easing: easeInOutSine`);
    particlesContainer.appendChild(drift);
  }

  centerpiece.setAttribute('animation__rotate',
    'property: rotation; from: 0 0 0; to: 0 360 0; dur: 45000; loop: true; easing: linear');
  centerpiece.setAttribute('animation__float',
    'property: position; from: 0 0 0; to: 0 0.35 0; dur: 6500; dir: alternate; loop: true; easing: easeInOutSine');
};
