window.sketch = ({ AFRAME, scene, startFrame }) => {
  const heartEntity = document.getElementById('heart-model');
  const bgImg = document.getElementById('bg');

  const readyBg = () => {
    const plane = document.getElementById('background');
    const aspect = bgImg.naturalWidth / bgImg.naturalHeight;
    plane.setAttribute('width', 10);
    plane.setAttribute('height', 10 / aspect);
  };
  if (bgImg.complete && bgImg.naturalWidth > 0) readyBg();
  else bgImg.addEventListener('load', readyBg, { once: true });

  heartEntity.addEventListener('model-loaded', (e) => {
    const mesh = e.detail.model || heartEntity.getObject3D('mesh');
    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 scale = 2 / maxDim;
    heartEntity.setAttribute('scale', `${scale} ${scale} ${scale}`);
    heartEntity.setAttribute('rotation', '0 0 0');
    heartEntity.setAttribute('animation', 'property: rotation; to: 0 360 0; dur: 20000; loop: true; easing: linear');
    heartEntity.setAttribute('animation__beat', 'property: scale; to: 2.2 2.2 2.2; dur: 1000; loop: true; easing: easeInOutQuad; dir: alternate');
  });

  const cellContainer = document.getElementById('cell-container');
  const cellColors = ['#ff6b8b', '#ff8fa3', '#ffa8b8', '#ffb3c1', '#ffc0cb', '#ffb6c1'];
  for (let i = 0; i < 2400; i++) {
    const cell = document.createElement('a-entity');
    const angle = (i / 2400) * Math.PI * 2;
    const orbitRadius = 2.5 + Math.random() * 2.0;
    const x = Math.cos(angle) * orbitRadius;
    const y = Math.sin(angle) * orbitRadius;
    const z = -1 + (Math.random() - 0.5) * 2.0;
    const cellRadius = 0.025 + Math.random() * 0.015;
    const color = cellColors[Math.floor(Math.random() * cellColors.length)];
    cell.setAttribute('class', 'blood-cell');
    cell.setAttribute('geometry', `primitive: sphere; radius: ${cellRadius}`);
    cell.setAttribute('material', `color: ${color}; opacity: 0.8; transparent: true`);
    cell.setAttribute('position', `${x} ${y} ${z}`);
    const moveDur = 5000 + Math.random() * 5000;
    const rotDur = 2000 + Math.random() * 3000;
    cell.setAttribute('animation', `property: position; to: ${-x} ${-y} ${z}; dur: ${moveDur}; loop: true; easing: easeInOutQuad`);
    cell.setAttribute('animation__rot', `property: rotation; to: 0 360 0; dur: ${rotDur}; loop: true; easing: linear`);
    cell.setAttribute('animation__pulse', `property: scale; to: 1.5 1.5 1.5; dur: 3000 + ${Math.random() * 2000}; loop: true; easing: easeInOutQuad; dir: alternate`);
    cellContainer.appendChild(cell);
  }
};
