// THE BALL - Versione Italiana v2
const LIVELLI = {
  tutorial: {
    path: [null,null,null,null,null,'spike',null,null,null,'spike','spike',null,null,'enemy',null,null,'spike',null,'enemy',null,null,null,'spike','enemy'],
    tileWidth: 120,
  },
  livello1: {
    path: [null,null,null,'spike',null,'spike',null,'enemy','spike',null,null,null,'enemy',null,'enemy','spike',null,null,'spike',null,'spike'],
    tileWidth: 120,
  }
};

const dom = {
  home: document.getElementById('home'),
  game: document.getElementById('game'),
  btnTutorial: document.getElementById('btn-tutorial'),
  btnLvl1: document.getElementById('btn-lvl1'),
  btnExit: document.getElementById('btn-exit'),
  btnHome: document.getElementById('btn-home'),
  canvas: document.getElementById('canvas'),
  score: document.getElementById('score'),
  status: document.getElementById('status'),
  end: document.getElementById('end')
};

const ctx = dom.canvas.getContext('2d');
let stato = null;

function resetGioco(livelloNome) {
  const livello = LIVELLI[livelloNome];
  stato = {
    livello: livelloNome,
    path: livello.path.slice(),
    tileWidth: livello.tileWidth,
    player: { x: 120, y: 260, vy:0, r:18, grounded:true },
    cameraX: 0,
    speed: 2.4,
    spawned: [],
    score: 0,
    finito: false
  };
  dom.score.textContent = 'Punti: 0';
  dom.status.textContent = 'In corso';
  dom.end.style.display = 'none';
}

function spawn() {
  const gs = stato;
  const tilesPass = Math.floor(gs.cameraX / gs.tileWidth);
  const maxIndex = Math.min(gs.path.length-1, tilesPass + Math.ceil(dom.canvas.width / gs.tileWidth) + 2);
  for (let i = gs.spawned.length; i <= maxIndex; i++) {
    const t = gs.path[i];
    if (!t) { gs.spawned.push(null); continue; }
    if (t==='spike') {
      gs.spawned.push({type:'spike',x:i*gs.tileWidth,y:275,w:32,h:40}); // alzate per collisione reale
    } else if (t==='enemy') {
      gs.spawned.push({type:'enemy',x:i*gs.tileWidth,y:272,w:36,h:36,dir:-1,vx:1,baseX:i*gs.tileWidth});
    } else gs.spawned.push(null);
  }
}

function aggiorna(dt) {
  const gs = stato;
  if (gs.finito) return;
  gs.cameraX += gs.speed * dt;
  spawn();
  const p = gs.player;
  p.vy += 0.45;
  p.y += p.vy;
  if (p.y >= 260) { p.y = 260; p.vy = 0; p.grounded = true; } else p.grounded=false;

  for (const e of gs.spawned) {
    if (!e || e.type!=='enemy') continue;
    e.x += e.vx * e.dir * dt;
    if (e.x < e.baseX - 20) e.dir = 1;
    if (e.x > e.baseX + 20) e.dir = -1;
  }

  for (const e of gs.spawned) {
    if (!e) continue;
    const eb = {x:e.x-gs.cameraX, y:e.y, w:e.w, h:e.h};
    if (e.type==='spike') {
      if (cerchioRettangoloCollide(p.x, p.y, p.r, eb.x, eb.y, eb.w, eb.h)) {
        fineLivello(false, 'Hai colpito una spina!');
        return;
      }
    } else if (e.type==='enemy' && !e.dead) {
    if (cerchioRettangoloCollide(p.x, p.y, p.r, eb.x, eb.y, eb.w, eb.h)) {
  // Controllo: il giocatore scende ed è sopra il nemico
     const playerBottom = p.y + p.r;
     const enemyTop = e.y;
    if (p.vy > 0 && playerBottom < enemyTop + 10) {
    // Schiaccia nemico
    e.dead = true;
    p.vy = -9; // Rimbalzo più deciso
    gs.score += 100;
  } else if (!e.dead) {
    // Colpito lateralmente -> muore
    fineLivello(false, 'Sei stato colpito da un nemico!');
    return;
  }
}
    }
  }
  gs.score = Math.max(gs.score, Math.floor(gs.cameraX / 10));
  dom.score.textContent = 'Punti: ' + gs.score;
  if ((gs.cameraX + p.x)/gs.tileWidth >= gs.path.length) fineLivello(true,'Livello completato!');
}

function cerchioRettangoloCollide(cx, cy, cr, rx, ry, rw, rh) {
  const testX = Math.max(rx, Math.min(cx, rx+rw));
  const testY = Math.max(ry, Math.min(cy, ry+rh));
  const distX = cx - testX;
  const distY = cy - testY;
  return (distX*distX + distY*distY) <= (cr*cr);
}

function disegna() {
  const gs = stato;
  ctx.clearRect(0,0,dom.canvas.width,dom.canvas.height);
  ctx.fillStyle='#3b3b3b'; ctx.fillRect(0,300,dom.canvas.width,60);
  const p = gs.player;
  ctx.fillStyle='#ffd166'; ctx.beginPath(); ctx.arc(p.x,p.y,p.r,0,Math.PI*2); ctx.fill();
  ctx.fillStyle='rgba(0,0,0,0.25)'; ctx.beginPath(); ctx.ellipse(p.x,300+6,p.r*0.9,p.r*0.35,0,0,Math.PI*2); ctx.fill();
  for (const e of gs.spawned) {
    if (!e) continue;
    const sx = e.x - gs.cameraX;
    if (sx<-200 || sx>dom.canvas.width+200) continue;
    if (e.type==='spike') {
      ctx.fillStyle='#ff6b6b'; ctx.beginPath();
      ctx.moveTo(sx, e.y+e.h); ctx.lineTo(sx+e.w/2,e.y); ctx.lineTo(sx+e.w,e.y+e.h); ctx.fill();
    } else if (e.type==='enemy' && !e.dead) {
      ctx.fillStyle='#74c0fc'; ctx.fillRect(sx,e.y,e.w,e.h);
      ctx.fillStyle='#0b132b'; ctx.fillRect(sx+6,e.y+8,6,6); ctx.fillRect(sx+e.w-12,e.y+8,6,6);
    }
  }
}

let last=null;
let rafId = null;
function loop(ts) {
  if (stato.finito) return; // evita loop multipli dopo la morte

  if (!last) last = ts;
  const dt = Math.min(40, ts - last);
  aggiorna(dt / 16.666);
  disegna();
  last = ts;

  rafId = requestAnimationFrame(loop);
}

window.addEventListener('keydown', e=>{
  if(e.code==='Space'||e.code==='ArrowUp'){
    const p=stato.player;
    if(p.grounded){p.vy=-10; p.grounded=false;}
  }
});

dom.btnTutorial.onclick=()=>startLevel('tutorial');
dom.btnLvl1.onclick=()=>startLevel('livello1');
dom.btnExit.onclick=()=>window.close();
dom.btnHome.onclick=()=>{ dom.game.style.display='none'; dom.home.style.display='block'; };

function startLevel(name) {
  // Ferma eventuali loop precedenti
  if (rafId) cancelAnimationFrame(rafId);
  rafId = null;
  last = null;

  // Mostra il gioco e nascondi la home
  dom.home.style.display = 'none';
  dom.game.style.display = 'block';

  // Reset stato e avvia il nuovo livello
  resetGioco(name);
  stato.finito = false; // fondamentale!
  rafId = requestAnimationFrame(loop);
}

function fineLivello(success,msg){
  stato.finito=true;
  dom.status.textContent = success ? 'Completato' : 'Fallito';
  dom.end.style.display='block';
  dom.end.innerHTML='<h2 style="text-shadow:0 2px 8px rgba(0,0,0,.5)">'+msg+'</h2><div style="margin-top:10px;"><button id="back-home">Torna al Menu</button></div>';
  document.getElementById('back-home').onclick=()=>{ dom.game.style.display='none'; dom.home.style.display='block'; };
}
