<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Fútbol Manager Fichas</title>
<style>
  body { margin:0; background:#1a1a1a; display:flex; flex-direction:column;
         align-items:center; font-family: Arial, sans-serif; color:#fff; }
  canvas { background:#2d8a3e; border:4px solid #fff; margin-top:10px; }
  #hud { margin-top:10px; font-size:18px; }
  #ratings { margin-top:10px; font-size:12px; display:flex; gap:20px; }
  .team { display:flex; flex-wrap:wrap; gap:4px; width:340px; }
  .chip { padding:2px 6px; border-radius:4px; }
  .blue { background:#2a5cd8; }
  .red  { background:#d82a2a; }
  .btn { margin-top:10px; padding:8px 16px; cursor:pointer; }
</style>
</head>
<body>
<canvas id="game" width="900" height="600"></canvas>
<div id="hud">Azul <span id="scoreA">0</span> - <span id="scoreB">0</span> Rojo | ⏱ <span id="clock">0:00</span></div>
<div id="ratings">
  <div class="team" id="teamA"></div>
  <div class="team" id="teamB"></div>
</div>
<button class="btn" onclick="resetGame()">Reiniciar</button>

<script>
const cvs = document.getElementById('game');
const ctx = cvs.getContext('2d');
const W = cvs.width, H = cvs.height;

// --- CONFIG ---
const PLAYER_R = 12;
const BALL_R = 6;
const FRICTION = 0.985;
const PLAYER_SPEED = 0.9;
const BALL_FRICTION = 0.975;
const PASS_POWER = 6;
const SHOT_POWER = 10;
const GOAL_W = 20;
const GOAL_H = 160;
const GOAL_Y = (H - GOAL_H) / 2;

// --- STATE ---
let players = [];
let ball = {};
let score = { A: 0, B: 0 };
let gameTime = 0; // segundos
let lastActionTeam = null;

function makePlayer(team, x, y, role) {
  return {
    team, x, y, role,
    vx: 0, vy: 0,
    homeX: x, homeY: y,
    rating: 6.0,
    name: role + Math.floor(Math.random()*90+10),
    cooldown: 0,
    lastRatingFlash: 0,
    flashColor: null
  };
}

function changeRating(player, delta, reason) {
  const old = player.rating;
  player.rating = Math.max(1.0, Math.min(10.0, player.rating + delta));
  player.lastRatingFlash = 40;
  player.flashColor = delta > 0 ? '#7CFC7C' : '#FF7C7C';
  console.log(`${player.name} (${player.team}): ${old.toFixed(1)} -> ${player.rating.toFixed(1)} [${reason}]`);
}

function resetGame() {
  score = { A: 0, B: 0 };
  gameTime = 0;
  setupTeams();
  resetBall('center');
  updateHUD();
}

function setupTeams() {
  players = [];
  // Equipo A (azul) ataca hacia la derecha (gol en x=W)
  // Formación 4-3-3
  const layoutA = [
    ['GK', 40, H/2],
    ['DEF', 160, 120], ['DEF', 160, 260], ['DEF', 160, 340], ['DEF', 160, 480],
    ['MID', 320, 180], ['MID', 320, 300], ['MID', 320, 420],
    ['FW', 480, 150], ['FW', 480, 300], ['FW', 480, 450],
  ];
  layoutA.forEach(([role,x,y]) => players.push(makePlayer('A', x, y, role)));

  const layoutB = [
    ['GK', W-40, H/2],
    ['DEF', W-160, 120], ['DEF', W-160, 260], ['DEF', W-160, 340], ['DEF', W-160, 480],
    ['MID', W-320, 180], ['MID', W-320, 300], ['MID', W-320, 420],
    ['FW', W-480, 150], ['FW', W-480, 300], ['FW', W-480, 450],
  ];
  layoutB.forEach(([role,x,y]) => players.push(makePlayer('B', x, y, role)));
}

function resetBall(reason) {
  ball = { x: W/2, y: H/2, vx: 0, vy: 0 };
  // el que recibió gol saca (o centro si reason=center)
  if (reason === 'goalA' || reason === 'goalB') {
    // pequeño delay implícito: sólo colocamos pelota al centro con leve impulso al equipo que saca
    ball.x = W/2; ball.y = H/2;
  }
}

// --- UPDATE ---
function update() {
  gameTime += 1/60;

  // Movimiento de jugadores (IA simple)
  players.forEach(p => {
    if (p.cooldown > 0) p.cooldown--;
    if (p.lastRatingFlash > 0) p.lastRatingFlash--;

    const isClosest = getClosestToBall(p.team) === p;
    const ballDist = dist(p, ball);
    let tx = p.homeX, ty = p.homeY;

    // El más cercano persigue la pelota
    if (isClosest && ballDist < 300) {
      // interceptar posición futura
      tx = ball.x + ball.vx * 5;
      ty = ball.y + ball.vy * 5;
    } else if (ball.x > W/2 && p.team === 'A') {
      // ataque: subir un poco
      tx = p.homeX + 80;
    } else if (ball.x < W/2 && p.team === 'B') {
      tx = p.homeX - 80;
    } else if (ball.x < W/2 && p.team === 'A') {
      // replegarse
      tx = p.homeX - 40;
    } else if (ball.x > W/2 && p.team === 'B') {
      tx = p.homeX + 40;
    }

    // si es arquero y pelota cerca de su arco, quedarse
    if (p.role === 'GK') {
      const ownGoalX = p.team === 'A' ? 0 : W;
      const goalDist = Math.abs(ball.x - ownGoalX);
      if (goalDist < 200) {
        tx = ownGoalX + (p.team === 'A' ? 40 : -40);
        ty = Math.max(GOAL_Y, Math.min(GOAL_Y + GOAL_H, ball.y));
      }
    }

    const dx = tx - p.x, dy = ty - p.y;
    const d = Math.hypot(dx, dy) || 1;
    if (d > 5) {
      p.x += (dx/d) * PLAYER_SPEED;
      p.y += (dy/d) * PLAYER_SPEED;
    }

    // límites
    p.x = Math.max(PLAYER_R, Math.min(W-PLAYER_R, p.x));
    p.y = Math.max(PLAYER_R, Math.min(H-PLAYER_R, p.y));

    // Verificar posesión / pase
    if (ballDist < PLAYER_R + BALL_R && p.cooldown === 0) {
      handlePossession(p);
    }
  });

  // Movimiento pelota
  ball.x += ball.vx;
  ball.y += ball.vy;
  ball.vx *= BALL_FRICTION;
  ball.vy *= BALL_FRICTION;

  // Rebote paredes arriba/abajo
  if (ball.y < BALL_R) { ball.y = BALL_R; ball.vy *= -0.8; }
  if (ball.y > H-BALL_R) { ball.y = H-BALL_R; ball.vy *= -0.8; }

  // Goles
  const inGoalY = ball.y > GOAL_Y && ball.y < GOAL_Y + GOAL_H;
  if (ball.x < BALL_R && inGoalY) { scoreGoal('B'); return; }
  if (ball.x > W-BALL_R && inGoalY) { scoreGoal('A'); return; }

  // Rebote en arcos (postes laterales fuera de la portería)
  if (ball.x < BALL_R) { ball.x = BALL_R; ball.vx *= -0.8; }
  if (ball.x > W-BALL_R) { ball.x = W-BALL_R; ball.vx *= -0.8; }

  updateHUD();
}

function handlePossession(p) {
  // Determinar si elige pase, disparo o despeje
  const teammates = players.filter(q => q.team === p.team && q !== p);
  const goalX = p.team === 'A' ? W : 0;
  const distToGoal = Math.abs(goalX - p.x);

  // Disparo si está cerca del arco
  if (distToGoal < 320 && p.role !== 'GK') {
    const goalYcenter = H/2;
    const dx = goalX - ball.x;
    const dy = goalYcenter - ball.y + (Math.random()-0.5)*GOAL_H*0.6;
    const d = Math.hypot(dx, dy) || 1;
    ball.vx = (dx/d) * SHOT_POWER;
    ball.vy = (dy/d) * SHOT_POWER;
    p.cooldown = 40;
    // rating: si el disparo va al arco (dentro del rango Y), bonificación
    const willHitGoal = Math.abs(ball.y + ball.vy*5 - H/2) < GOAL_H/2;
    changeRating(p, willHitGoal ? 0.3 : -0.1, 'disparo');
    lastActionTeam = p.team;
    return;
  }

  // Buscar mejor compañero para pasar (adelante y con espacio)
  let best = null, bestScore = -Infinity;
  teammates.forEach(q => {
    if (q.role === 'GK' && p.role !== 'GK') return;
    const fwd = p.team === 'A' ? (q.x - p.x) : (p.x - q.x);
    const d = dist(p, q);
    if (d < 20 || d > 400) return;
    // Verificar que no haya rival muy cerca de la línea de pase
    const closeRival = players.some(r =>
      r.team !== p.team && pointOnSegment(r, p, q) && dist(r, {x:(p.x+q.x)/2,y:(p.y+q.y)/2}) < 60);
    let s = fwd * 0.5 - d * 0.2 - (closeRival ? 200 : 0);
    if (q.role === 'GK') s -= 100;
    if (s > bestScore) { bestScore = s; best = q; }
  });

  if (best && Math.random() < 0.85) {
    const dx = best.x - ball.x, dy = best.y - ball.y;
    const d = Math.hypot(dx, dy) || 1;
    ball.vx = (dx/d) * PASS_POWER;
    ball.vy = (dy/d) * PASS_POWER;
    p.cooldown = 25;
    changeRating(p, 0.2, 'pase');
    lastActionTeam = p.team;
  } else {
    // Despeje / pase de emergencia
    const dir = p.team === 'A' ? 1 : -1;
    ball.vx = dir * PASS_POWER * 0.8;
    ball.vy = (Math.random()-0.5) * PASS_POWER;
    p.cooldown = 25;
    changeRating(p, -0.05, 'despeje');
  }
}

function scoreGoal(team) {
  if (team === 'A') score.A++; else score.B++;
  // rating: el que metió gol +1.5 (último en tocar)
  // Simplificación: damos bonus al delantero más cercano al arco
  const scorers = players.filter(p => p.team === team && p.role === 'FW');
  if (scorers.length) {
    const s = scorers.reduce((a,b) => Math.abs(a.x-(team==='A'?W:0)) < Math.abs(b.x-(team==='A'?W:0)) ? a : b);
    changeRating(s, 1.5, 'GOL');
  }
  // El rival que estaba más cerca de la pelota pierde rating
  const loserTeam = team === 'A' ? 'B' : 'A';
  const loser = players.filter(p => p.team === loserTeam)
    .reduce((a,b) => dist(a, ball) < dist(b, ball) ? a : b);
  changeRating(loser, -0.8, 'gol recibido');

  updateHUD();
  setTimeout(() => resetBall(team === 'A' ? 'goalA' : 'goalB'), 300);
}

// --- HELPERS ---
function dist(a, b) { return Math.hypot(a.x-b.x, a.y-b.y); }
function getClosestToBall(team) {
  return players.filter(p => p.team === team)
    .reduce((a,b) => dist(a, ball) < dist(b, ball) ? a : b);
}
function pointOnSegment(p, a, b) {
  const d = dist(a, b);
  const d1 = dist(p, a), d2 = dist(p, b);
  return Math.abs(d1 + d2 - d) < 10;
}

// --- RENDER ---
function render() {
  // Cancha
  ctx.fillStyle = '#2d8a3e';
  ctx.fillRect(0, 0, W, H);
  // Líneas
  ctx.strokeStyle = 'rgba(255,255,255,0.5)';
  ctx.lineWidth = 2;
  ctx.strokeRect(20, 20, W-40, H-40);
  ctx.beginPath();
  ctx.moveTo(W/2, 20); ctx.lineTo(W/2, H-20); ctx.stroke();
  ctx.beginPath();
  ctx.arc(W/2, H/2, 60, 0, Math.PI*2); ctx.stroke();
  ctx.beginPath();
  ctx.arc(W/2, H/2, 3, 0, Math.PI*2); ctx.fillStyle='rgba(255,255,255,0.5)'; ctx.fill();

  // Arcos
  ctx.strokeStyle = '#fff';
  ctx.lineWidth = 4;
  ctx.strokeRect(0, GOAL_Y, GOAL_W, GOAL_H);
  ctx.strokeRect(W-GOAL_W, GOAL_Y, GOAL_W, GOAL_H);
  ctx.strokeRect(20, 120, 80, H-240);
  ctx.strokeRect(W-100, 120, 80, H-240);

  // Jugadores
  players.forEach(p => {
    // círculo
    ctx.fillStyle = p.team === 'A' ? '#2a5cd8' : '#d82a2a';
    ctx.beginPath();
    ctx.arc(p.x, p.y, PLAYER_R, 0, Math.PI*2);
    ctx.fill();
    ctx.strokeStyle = '#fff';
    ctx.lineWidth = 2;
    ctx.stroke();

    // flash rating
    if (p.lastRatingFlash > 0) {
      ctx.beginPath();
      ctx.arc(p.x, p.y, PLAYER_R + 4 + p.lastRatingFlash*0.1, 0, Math.PI*2);
      ctx.strokeStyle = p.flashColor;
      ctx.lineWidth = 2;
      ctx.stroke();
    }

    // letra rol
    ctx.fillStyle = '#fff';
    ctx.font = 'bold 10px Arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(p.role, p.x, p.y);
  });

  // Pelota
  ctx.fillStyle = '#fff';
  ctx.beginPath();
  ctx.arc(ball.x, ball.y, BALL_R, 0, Math.PI*2);
  ctx.fill();
  ctx.strokeStyle = '#000';
  ctx.lineWidth = 1;
  ctx.stroke();

  // Panel de ratings
  renderRatings();
}

function renderRatings() {
  const a = document.getElementById('teamA');
  const b = document.getElementById('teamB');
  a.innerHTML = ''; b.innerHTML = '';
  players.filter(p => p.team === 'A').forEach(p => {
    const d = document.createElement('span');
    d.className = 'chip blue';
    d.textContent = `${p.role} ${p.rating.toFixed(1)}`;
    a.appendChild(d);
  });
  players.filter(p => p.team === 'B').forEach(p => {
    const d = document.createElement('span');
    d.className = 'chip red';
    d.textContent = `${p.role} ${p.rating.toFixed(1)}`;
    b.appendChild(d);
  });
}

// --- HUD ---
function updateHUD() {
  document.getElementById('scoreA').textContent = score.A;
  document.getElementById('scoreB').textContent = score.B;
  const m = Math.floor(gameTime / 60);
  const s = Math.floor(gameTime % 60).toString().padStart(2, '0');
  document.getElementById('clock').textContent = `${m}:${s}`;
}

// --- LOOP ---
function loop() {
  update();
  render();
  requestAnimationFrame(loop);
}

resetGame();
loop();
</script>
</body>
</html>