const MAX_APPARITIONS = 70;

const DIALOGUES = ["ARRÊTE", "STOP", "QU'EST-CE QUE TU FAIS", "EH", "ÇA SUFFIT", "JE TE DIS D'ARRÊTER"];

let clickedCount = 0;

const MAX_CLICKS = 10;

let endTriggered = false;
let currentDialogue = null;
let dialogueTimeout = null;

let compteur = 0;

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

let restartTriggered = false;
let restartInterval = null;

let infiniteMode = false;
const INFINITE_IMAGE = "/user/pages/01.home/robot_guerrier.png";

let processingClick = false; 




let eyeElement = null;

function createEyeGif() {
  if (eyeElement) return;

  eyeElement = document.createElement("img");
  eyeElement.src = "/user/pages/01.home/oeil.gif";

  eyeElement.style.width = "200px";
  eyeElement.style.height = "200px";
  eyeElement.style.position = "absolute";
  eyeElement.style.top = "50px";
  eyeElement.style.left = "50px";
  eyeElement.style.zIndex = "10"; 

  document.body.appendChild(eyeElement);
}




function replaceEyeWithImage() {

  document
    .querySelectorAll('img[src*="oeil.gif"]')
    .forEach(img => img.remove());

  eyeElement = null;

  const finalEye = document.createElement("img");
  finalEye.src = "/user/pages/01.home/oeil_colere.png";

  finalEye.style.width = "200px";
  finalEye.style.height = "200px";
  finalEye.style.position = "absolute";
  finalEye.style.top = "50px";
  finalEye.style.left = "50px";
  finalEye.style.zIndex = "20";

  document.body.appendChild(finalEye);
}




let resizeCanvas = () => {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;  
}
resizeCanvas()


let onResize = (event) => {
  resizeCanvas()
}

window.addEventListener('resize', onResize);


function showDialogue() {
  if (endTriggered) return;

  currentDialogue =
    DIALOGUES[Math.floor(Math.random() * DIALOGUES.length)];

  if (dialogueTimeout) {
    clearTimeout(dialogueTimeout);
  }

  dialogueTimeout = setTimeout(() => {
    currentDialogue = null;
  }, 2000);
}


function triggerEnd() {
  endTriggered = true;

  boules.forEach(boule => {
    boule.vx = 0;
    boule.vy = 0;
  });

  clearInterval(interval);

  currentDialogue = "Très bien, puisque c'est comme ça !";

  if (dialogueTimeout) {
    clearTimeout(dialogueTimeout);
    dialogueTimeout = null;
  }

  replaceEyeWithImage();

  setTimeout(() => {
    restartScene();
  }, 3000);
}


function restartScene() {
  endTriggered = false;
  restartTriggered = true;
  infiniteMode = true;

  currentDialogue = null;

  boules.forEach(boule => {
    boule.vx = -2 + Math.random() * 4;
    boule.vy = -2 + Math.random() * 4;

    boule.images = [INFINITE_IMAGE];
    boule.currentImage = 0;
    boule.img.src = INFINITE_IMAGE;

    boule.isClickable = false;
  });

  restartInterval = setInterval(() => {
    let maboule = new Boule(
      Math.random() * canvas.width,
      Math.random() * canvas.height,
      10 + Math.random() * 30
    );

    maboule.images = [INFINITE_IMAGE];
    maboule.currentImage = 0;
    maboule.img.src = INFINITE_IMAGE;

    maboule.isClickable = false;

    boules.push(maboule);
  }, 500);

  window.requestAnimationFrame(anime);
}




function showDialogue() {

  currentDialogue =
    DIALOGUES[Math.floor(Math.random() * DIALOGUES.length)];

  if (dialogueTimeout) {
    clearTimeout(dialogueTimeout);
  }

  dialogueTimeout = setTimeout(() => {
    currentDialogue = null;
  }, 2000);
}


class Boule {
  constructor(x, y, s) {
    this.pos = {
      x: x,
      y: y
    }
    this.size = s
    this.vx = -2+Math.random()*4;
    this.vy = -2+Math.random()*4;

    this.isClickable = true;

    this.currentImage = 0;

    this.images = [
      "/user/pages/01.home/robot_neuf.png",
      "/user/pages/01.home/robot_detruit.png"
    ];

    this.img = new Image();
    this.img.src = this.images[this.currentImage];
  }


  draw(){
      ctx.drawImage(this.img, this.pos.x, this.pos.y, 5*this.size, 5*this.size);
    
  }

  changeImage() {
    if (infiniteMode || endTriggered) return;

    this.currentImage = (this.currentImage + 1) % this.images.length;
    this.img.src = this.images[this.currentImage];
    this.isClickable = false;

  
    clickedCount++;
    showDialogue();
  
    if (clickedCount === MAX_CLICKS) {
      triggerEnd();
    }
  }
  
  
  move(){
    this.pos.x += this.vx;
    this.pos.y += this.vy;

    if(this.pos.x >= canvas.width-this.size || this.pos.x <= 0){
      this.vx *= -1;
    }
    if(this.pos.y >= canvas.height-this.size || this.pos.y <= 0){
      this.vy *= -1;
    }

    this.draw();
  }
}

let boules = [];



let onClick = (event) => {
  if (processingClick) return;
  processingClick = true;

  let rect = canvas.getBoundingClientRect();
  let mouseX = event.clientX - rect.left;
  let mouseY = event.clientY - rect.top;

  boules.forEach(boule => {
    if (!boule.isClickable || infiniteMode || endTriggered) return;

    let centerX = boule.pos.x + (5 * boule.size) / 2;
    let centerY = boule.pos.y + (5 * boule.size) / 2;

    let dist = Math.sqrt(
      Math.pow(mouseX - centerX, 2) +
      Math.pow(mouseY - centerY, 2)
    );

    if (dist < (5 * boule.size) / 2) {
      boule.changeImage();
    }
  });

  processingClick = false;
};

canvas.addEventListener("click", onClick);



function createBoule() {

  if (compteur >= MAX_APPARITIONS) {
    console.log("Limite atteinte : plus de création de boules");
    return;
  }

  let maboule = new Boule(
    canvas.width / 2,
    canvas.height / 2,
    10 + Math.random() * 30
  );

  boules.push(maboule);


  compteur++;

  console.log("Boule créée :", compteur);
}

const interval = setInterval(() => {

  if (compteur >= MAX_APPARITIONS) {
    clearInterval(interval);
    return;
  }

  createBoule();

}, 500);



let anime = () => {

  if (endTriggered) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    boules.forEach(boule => boule.draw());

    if (currentDialogue) {
      ctx.font = "bold 110px Arial";
      ctx.fillStyle = "red";
      ctx.textAlign = "center";
      ctx.fillText(currentDialogue, canvas.width / 2, 500);
    }

    return;
  }

  ctx.clearRect(0, 0, canvas.width, canvas.height);

  if (currentDialogue) {
    ctx.font = "bold 70px Arial";
    ctx.fillStyle = "red";
    ctx.textAlign = "center";
    ctx.fillText(currentDialogue, canvas.width / 2, 100);
  }

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

  window.requestAnimationFrame(anime);
};


window.requestAnimationFrame(anime);


let onMouseMove = (event) => {
  let h = 360 * (event.x / canvas.width);

  
  let s = 100 * (event.y / canvas.height)
  console.log('s', s);
  

}

window.addEventListener('mousemove', onMouseMove);