let canvas = document.getElementById('scene');
let ctx = canvas.getContext("2d");

function resizeCanvas() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);

//les petits croco !
const imagesSrc = [
  "/user/pages/01.home/croco_bleu.png",
  "/user/pages/01.home/croco_jaune.png",
  "/user/pages/01.home/croco_orange.png",
  "/user/pages/01.home/croco_vert.png",
  "/user/pages/01.home/croco_rouge.png"
];

class Boule {
  constructor() {
    this.size = 10 + Math.random() * 30;

    this.pos = {
      x: Math.random() * canvas.width,
      y: -this.size * 6
    };

    this.vx = -0.5 + Math.random();
    this.vy = 1 + Math.random() * 3;
    this.gravity = 0.03;

    
    this.angle = Math.random() * Math.PI * 2;
    this.rotationSpeed = -0.01 + Math.random() * 0.02;  //rotationimages

    this.img = new Image();
    this.img.src =
      imagesSrc[Math.floor(Math.random() * imagesSrc.length)];
  }

  draw() {
    const width = 6 * this.size;
    const height = 3 * this.size; //taille des imags

    ctx.save();
    ctx.translate(
      this.pos.x + width / 2,
      this.pos.y + height / 2
    );
    ctx.rotate(this.angle);

 ctx.drawImage(
      this.img,
      -width / 2,
      -height / 2,
      width,
      height
    );

    ctx.restore();
  }

  move() {
    this.vy += this.gravity;  //effet pluie
    this.pos.x += this.vx;
    this.pos.y += this.vy;

    this.angle += this.rotationSpeed;

  
    if (this.pos.x <= 0 || this.pos.x >= canvas.width - this.size * 6) {
      this.vx *= -1;
      this.rotationSpeed *= -1; //rebond sur les 2cotés
    }

    this.draw();
  }
}

let boules = [];

function createBoule() {
  boules.push(new Boule());
}

setInterval(createBoule, 50);

function anime() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  for (let i = 0; i < boules.length; i++) {
    let a = boules[i];

    for (let j = i + 1; j < boules.length; j++) {
      let b = boules[j];
      let dx = b.pos.x - a.pos.x;
      let dy = b.pos.y - a.pos.y;
      let dist = Math.sqrt(dx * dx + dy * dy);

      if (dist < a.size + b.size) {
        let nx = dx / dist;
        let ny = dy / dist;
        let p = 0.5;

        a.vx -= nx * p;
        a.vy -= ny * p;
        b.vx += nx * p;
        b.vy += ny * p;
      }
    }

    a.move();
  }

  requestAnimationFrame(anime);
}

anime();
