const { useState, useEffect, useRef, useCallback } = React;

// ─── API ──────────────────────────────────────────────────────────────────────
// Vercel では .php が実行されずソースが返る → iOS で
// "The string did not match the expected pattern." になる。
// 静的 JSON を優先し、PHP はフォールバック。
const API = {
  stagesCandidates: ["/api/stages.json", "/api/stages", "/api/stages.php"],
  stageCandidates: (id) => [
    `/data/stages/${id}.json`,
    `/api/stage?id=${id}`,
    `/api/stage.php?id=${id}`,
  ],
};

async function fetchJSON(url) {
  const res = await fetch(url, { cache: "no-store" });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const text = await res.text();
  // PHP 未実行（ソースそのまま）を弾く
  if (/^\s*<\?php/i.test(text)) {
    throw new Error("PHP not executed");
  }
  try {
    return JSON.parse(text);
  } catch {
    throw new Error("Invalid JSON");
  }
}

async function fetchFirstJSON(urls) {
  let lastErr = null;
  for (const url of urls) {
    try {
      return await fetchJSON(url);
    } catch (e) {
      lastErr = e;
    }
  }
  throw lastErr || new Error("All API candidates failed");
}

// ─── helpers ──────────────────────────────────────────────────────────────────
let _uid = 1;
const uid = () => _uid++;

function clamp(v, a, b) {
  return Math.max(a, Math.min(b, v));
}

function dist2(ax, ay, bx, by) {
  const dx = ax - bx;
  const dy = ay - by;
  return dx * dx + dy * dy;
}

function lerp(a, b, t) {
  return a + (b - a) * t;
}

function easeOutBack(t) {
  const c1 = 1.70158;
  const c3 = c1 + 1;
  return 1 + c3 * Math.pow(t - 1, 3) + c1 * Math.pow(t - 1, 2);
}

function levelMult(level) {
  return 1 + (level - 1) * 1.25 + Math.pow(level - 1, 1.35) * 0.2;
}

function unitStats(def, level) {
  const m = levelMult(level);
  return {
    dmg: Math.round(def.baseDmg * m),
    range: def.range * (1 + (level - 1) * 0.1),
    fireRate: def.fireRate * (1 + (level - 1) * 0.08),
  };
}

// ─── path utilities ───────────────────────────────────────────────────────────
function buildPathPoints(path, cellSize) {
  return path.map(([c, r]) => ({
    x: c * cellSize + cellSize / 2,
    y: r * cellSize + cellSize / 2,
  }));
}

function pathLength(pts) {
  let len = 0;
  for (let i = 1; i < pts.length; i++) {
    len += Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y);
  }
  return len;
}

function posOnPath(pts, dist) {
  if (pts.length === 0) return { x: 0, y: 0, done: true, t: 1 };
  if (dist <= 0) return { x: pts[0].x, y: pts[0].y, done: false, t: 0 };
  let remain = dist;
  let total = 0;
  const segs = [];
  for (let i = 1; i < pts.length; i++) {
    const len = Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y);
    segs.push(len);
    total += len;
  }
  for (let i = 0; i < segs.length; i++) {
    if (remain <= segs[i]) {
      const t = segs[i] === 0 ? 0 : remain / segs[i];
      return {
        x: lerp(pts[i].x, pts[i + 1].x, t),
        y: lerp(pts[i].y, pts[i + 1].y, t),
        done: false,
        t: total === 0 ? 0 : dist / total,
      };
    }
    remain -= segs[i];
  }
  const last = pts[pts.length - 1];
  return { x: last.x, y: last.y, done: true, t: 1 };
}

function isPathCell(pathSet, c, r) {
  return pathSet.has(`${c},${r}`);
}

function isTreeCell(treeSet, c, r) {
  return treeSet.has(`${c},${r}`);
}

// ─── audio ────────────────────────────────────────────────────────────────────
function createAudio() {
  let ctx = null;
  const ensure = () => {
    if (!ctx) ctx = new (window.AudioContext || window.webkitAudioContext)();
    if (ctx.state === "suspended") ctx.resume();
    return ctx;
  };
  const beep = (freq, dur, type = "square", vol = 0.04) => {
    try {
      const c = ensure();
      const o = c.createOscillator();
      const g = c.createGain();
      o.type = type;
      o.frequency.value = freq;
      g.gain.value = vol;
      g.gain.exponentialRampToValueAtTime(0.0001, c.currentTime + dur);
      o.connect(g);
      g.connect(c.destination);
      o.start();
      o.stop(c.currentTime + dur);
    } catch (_) {}
  };
  return {
    unlock: () => ensure(),
    place: () => beep(520, 0.08, "triangle", 0.05),
    merge: () => {
      beep(400, 0.06, "square", 0.04);
      setTimeout(() => beep(640, 0.1, "square", 0.05), 50);
    },
    shoot: () => beep(880, 0.03, "square", 0.018),
    hit: () => beep(220, 0.04, "sawtooth", 0.028),
    kill: () => beep(180, 0.08, "triangle", 0.04),
    buy: () => beep(660, 0.07, "triangle", 0.05),
    wave: () => {
      beep(330, 0.1);
      setTimeout(() => beep(440, 0.12), 80);
    },
    win: () => {
      [523, 659, 784, 1046].forEach((f, i) =>
        setTimeout(() => beep(f, 0.15, "triangle", 0.05), i * 100)
      );
    },
    lose: () => {
      [400, 300, 200].forEach((f, i) =>
        setTimeout(() => beep(f, 0.18, "sawtooth", 0.04), i * 120)
      );
    },
    evolve: () => {
      [440, 554, 659, 880].forEach((f, i) =>
        setTimeout(() => beep(f, 0.12, "triangle", 0.05), i * 90)
      );
    },
  };
}

// ─── Canvas drawing ───────────────────────────────────────────────────────────
function drawRoundedRect(ctx, x, y, w, h, r) {
  const rr = Math.min(r, w / 2, h / 2);
  ctx.beginPath();
  ctx.moveTo(x + rr, y);
  ctx.arcTo(x + w, y, x + w, y + h, rr);
  ctx.arcTo(x + w, y + h, x, y + h, rr);
  ctx.arcTo(x, y + h, x, y, rr);
  ctx.arcTo(x, y, x + w, y, rr);
  ctx.closePath();
}

function drawTree(ctx, x, y, size, seed) {
  const s = size;
  ctx.fillStyle = "rgba(0,0,0,0.15)";
  ctx.beginPath();
  ctx.ellipse(x, y + s * 0.35, s * 0.35, s * 0.12, 0, 0, Math.PI * 2);
  ctx.fill();
  ctx.fillStyle = "#8b5a2b";
  ctx.fillRect(x - s * 0.08, y - s * 0.05, s * 0.16, s * 0.35);
  const colors =
    seed % 2 === 0 ? ["#3a9d5c", "#2d8a4e", "#4cb86a"] : ["#2f9e44", "#40916c", "#52b788"];
  for (let i = 0; i < 3; i++) {
    ctx.fillStyle = colors[i];
    ctx.beginPath();
    ctx.arc(
      x + (i - 1) * s * 0.12,
      y - s * 0.22 - i * s * 0.02,
      s * (0.28 - i * 0.03),
      0,
      Math.PI * 2
    );
    ctx.fill();
  }
  ctx.fillStyle = seed % 3 === 0 ? "#e76f51" : "#ffd166";
  ctx.beginPath();
  ctx.arc(x + s * 0.12, y - s * 0.18, s * 0.07, 0, Math.PI * 2);
  ctx.fill();
  ctx.beginPath();
  ctx.arc(x - s * 0.1, y - s * 0.28, s * 0.06, 0, Math.PI * 2);
  ctx.fill();
}

function drawCritter(ctx, x, y, size, def, level, facing, anim) {
  const s = size * (1 + (level - 1) * 0.08);
  const bob = Math.sin(anim * 6 + x * 0.01) * 1.5;
  const cy = y + bob;

  ctx.fillStyle = "rgba(0,0,0,0.18)";
  ctx.beginPath();
  ctx.ellipse(x, y + s * 0.32, s * 0.28, s * 0.1, 0, 0, Math.PI * 2);
  ctx.fill();

  ctx.fillStyle = def.color;
  ctx.beginPath();
  ctx.ellipse(x, cy + s * 0.05, s * 0.28, s * 0.26, 0, 0, Math.PI * 2);
  ctx.fill();

  ctx.fillStyle = def.accent;
  ctx.beginPath();
  ctx.ellipse(x, cy + s * 0.1, s * 0.16, s * 0.14, 0, 0, Math.PI * 2);
  ctx.fill();

  ctx.fillStyle = def.color;
  ctx.beginPath();
  ctx.arc(x, cy - s * 0.18, s * 0.22, 0, Math.PI * 2);
  ctx.fill();

  ctx.fillStyle = def.color;
  if (def.id === "puppy" || def.id === "fox") {
    ctx.beginPath();
    ctx.moveTo(x - s * 0.18, cy - s * 0.28);
    ctx.lineTo(x - s * 0.28, cy - s * 0.48);
    ctx.lineTo(x - s * 0.02, cy - s * 0.34);
    ctx.fill();
    ctx.beginPath();
    ctx.moveTo(x + s * 0.18, cy - s * 0.28);
    ctx.lineTo(x + s * 0.28, cy - s * 0.48);
    ctx.lineTo(x + s * 0.02, cy - s * 0.34);
    ctx.fill();
    if (def.id === "fox") {
      ctx.fillStyle = def.accent;
      ctx.beginPath();
      ctx.moveTo(x - s * 0.16, cy - s * 0.3);
      ctx.lineTo(x - s * 0.24, cy - s * 0.42);
      ctx.lineTo(x - s * 0.06, cy - s * 0.32);
      ctx.fill();
    }
  } else if (def.id === "kitty") {
    ctx.beginPath();
    ctx.moveTo(x - s * 0.16, cy - s * 0.28);
    ctx.lineTo(x - s * 0.22, cy - s * 0.48);
    ctx.lineTo(x - s * 0.02, cy - s * 0.32);
    ctx.fill();
    ctx.beginPath();
    ctx.moveTo(x + s * 0.16, cy - s * 0.28);
    ctx.lineTo(x + s * 0.22, cy - s * 0.48);
    ctx.lineTo(x + s * 0.02, cy - s * 0.32);
    ctx.fill();
  } else if (def.id === "birdy") {
    ctx.fillStyle = "#ffd166";
    ctx.beginPath();
    ctx.arc(x, cy - s * 0.36, s * 0.1, 0, Math.PI * 2);
    ctx.fill();
    ctx.fillStyle = def.accent;
    ctx.beginPath();
    ctx.ellipse(x + facing * s * 0.2, cy, s * 0.14, s * 0.1, facing * 0.4, 0, Math.PI * 2);
    ctx.fill();
  }

  ctx.fillStyle = "#1a1a1a";
  ctx.beginPath();
  ctx.arc(x - s * 0.07, cy - s * 0.2, s * 0.035, 0, Math.PI * 2);
  ctx.arc(x + s * 0.07, cy - s * 0.2, s * 0.035, 0, Math.PI * 2);
  ctx.fill();
  ctx.fillStyle = "rgba(255,120,120,0.35)";
  ctx.beginPath();
  ctx.ellipse(x - s * 0.14, cy - s * 0.12, s * 0.05, s * 0.03, 0, 0, Math.PI * 2);
  ctx.ellipse(x + s * 0.14, cy - s * 0.12, s * 0.05, s * 0.03, 0, 0, Math.PI * 2);
  ctx.fill();
  ctx.strokeStyle = "#1a1a1a";
  ctx.lineWidth = 1.5;
  ctx.beginPath();
  ctx.arc(x, cy - s * 0.12, s * 0.06, 0.15, Math.PI - 0.15);
  ctx.stroke();

  if (level >= 3) {
    const wx = x + facing * s * 0.32;
    const wy = cy + s * 0.02;
    ctx.save();
    ctx.translate(wx, wy);
    ctx.rotate(facing > 0 ? -0.5 : 0.5 + Math.PI);
    ctx.fillStyle = "#c0c0c0";
    ctx.fillRect(0, -s * 0.04, s * 0.45, s * 0.08);
    ctx.fillStyle = "#ffd166";
    ctx.fillRect(-s * 0.06, -s * 0.1, s * 0.1, s * 0.2);
    ctx.restore();
  } else {
    ctx.strokeStyle = "#8b4513";
    ctx.lineWidth = 3;
    ctx.lineCap = "round";
    ctx.beginPath();
    ctx.moveTo(x + facing * s * 0.18, cy + s * 0.02);
    ctx.lineTo(x + facing * s * 0.42, cy - s * 0.18 + Math.sin(anim * 10) * 2);
    ctx.stroke();
    ctx.fillStyle = "#e76f51";
    ctx.beginPath();
    ctx.arc(
      x + facing * s * 0.42,
      cy - s * 0.18 + Math.sin(anim * 10) * 2,
      s * 0.08,
      0,
      Math.PI * 2
    );
    ctx.fill();
  }

  const bx = x + s * 0.22;
  const by = cy - s * 0.38;
  ctx.fillStyle = level >= 5 ? "#ffd166" : "#fff";
  ctx.beginPath();
  ctx.arc(bx, by, s * 0.14, 0, Math.PI * 2);
  ctx.fill();
  ctx.strokeStyle = level >= 5 ? "#e9c46a" : "#2d6a4f";
  ctx.lineWidth = 2;
  ctx.stroke();
  ctx.fillStyle = "#1a1a1a";
  ctx.font = `bold ${Math.max(10, s * 0.2)}px Nunito, sans-serif`;
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.fillText(String(level), bx, by + 0.5);

  if (level >= 5) {
    ctx.strokeStyle = "rgba(255,209,102,0.55)";
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.arc(x, cy, s * 0.42 + Math.sin(anim * 5) * 2, 0, Math.PI * 2);
    ctx.stroke();
  }
}

function drawEnemy(ctx, x, y, size, enemy, anim) {
  const scale = enemy.scale || 1;
  const s = size * scale;
  const bob = Math.sin(anim * 8 + enemy.id) * 1.2;
  const cy = y + bob;
  const hpRatio = enemy.hp / enemy.maxHp;

  ctx.fillStyle = "rgba(0,0,0,0.18)";
  ctx.beginPath();
  ctx.ellipse(x, y + s * 0.28, s * 0.26, s * 0.09, 0, 0, Math.PI * 2);
  ctx.fill();

  if (enemy.type === "bat") {
    ctx.fillStyle = enemy.color;
    const flap = Math.sin(anim * 14) * 0.35;
    ctx.save();
    ctx.translate(x - s * 0.1, cy);
    ctx.rotate(-0.4 + flap);
    ctx.beginPath();
    ctx.ellipse(0, 0, s * 0.28, s * 0.14, 0, 0, Math.PI * 2);
    ctx.fill();
    ctx.restore();
    ctx.save();
    ctx.translate(x + s * 0.1, cy);
    ctx.rotate(0.4 - flap);
    ctx.beginPath();
    ctx.ellipse(0, 0, s * 0.28, s * 0.14, 0, 0, Math.PI * 2);
    ctx.fill();
    ctx.restore();
    ctx.fillStyle = "#5a4a7a";
    ctx.beginPath();
    ctx.arc(x, cy, s * 0.16, 0, Math.PI * 2);
    ctx.fill();
  } else if (enemy.type === "boar" || enemy.type === "boss") {
    ctx.fillStyle = enemy.color;
    ctx.beginPath();
    ctx.ellipse(x, cy + s * 0.02, s * 0.3, s * 0.24, 0, 0, Math.PI * 2);
    ctx.fill();
    ctx.fillStyle = "#f4a261";
    ctx.beginPath();
    ctx.ellipse(x + s * 0.22, cy + s * 0.04, s * 0.12, s * 0.1, 0, 0, Math.PI * 2);
    ctx.fill();
    ctx.fillStyle = "#fff";
    ctx.beginPath();
    ctx.moveTo(x + s * 0.18, cy + s * 0.1);
    ctx.lineTo(x + s * 0.28, cy + s * 0.22);
    ctx.lineTo(x + s * 0.14, cy + s * 0.14);
    ctx.fill();
    if (enemy.type === "boss") {
      ctx.strokeStyle = "rgba(230,57,70,0.6)";
      ctx.lineWidth = 3;
      ctx.beginPath();
      ctx.arc(x, cy, s * 0.4 + Math.sin(anim * 4) * 2, 0, Math.PI * 2);
      ctx.stroke();
    }
  } else {
    ctx.fillStyle = enemy.color;
    ctx.beginPath();
    ctx.ellipse(x, cy + s * 0.05, s * 0.28, s * 0.22 + Math.sin(anim * 5) * 2, 0, 0, Math.PI * 2);
    ctx.fill();
    ctx.fillStyle = "rgba(255,255,255,0.35)";
    ctx.beginPath();
    ctx.ellipse(x - s * 0.08, cy - s * 0.02, s * 0.1, s * 0.08, -0.3, 0, Math.PI * 2);
    ctx.fill();
  }

  ctx.fillStyle = "#1a1a1a";
  ctx.beginPath();
  ctx.arc(x - s * 0.07, cy - s * 0.04, s * 0.04, 0, Math.PI * 2);
  ctx.arc(x + s * 0.07, cy - s * 0.04, s * 0.04, 0, Math.PI * 2);
  ctx.fill();
  ctx.fillStyle = "#fff";
  ctx.beginPath();
  ctx.arc(x - s * 0.06, cy - s * 0.05, s * 0.015, 0, Math.PI * 2);
  ctx.arc(x + s * 0.08, cy - s * 0.05, s * 0.015, 0, Math.PI * 2);
  ctx.fill();

  const label = String(Math.ceil(enemy.hp));
  ctx.font = `bold ${Math.max(11, s * 0.28)}px Nunito, sans-serif`;
  const tw = ctx.measureText(label).width;
  const bw = tw + 10;
  const bh = Math.max(16, s * 0.32);
  const bx = x - bw / 2;
  const by = cy - s * 0.48;
  ctx.fillStyle = hpRatio < 0.3 ? "rgba(230,57,70,0.9)" : "rgba(20,20,20,0.75)";
  drawRoundedRect(ctx, bx, by, bw, bh, 8);
  ctx.fill();
  ctx.fillStyle = "#fff";
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.fillText(label, x, by + bh / 2 + 0.5);
}

function drawProjectile(ctx, p) {
  ctx.fillStyle = p.color || "#ffd166";
  ctx.beginPath();
  ctx.arc(p.x, p.y, p.r || 4, 0, Math.PI * 2);
  ctx.fill();
  ctx.fillStyle = "rgba(255,255,255,0.6)";
  ctx.beginPath();
  ctx.arc(p.x - 1, p.y - 1, (p.r || 4) * 0.4, 0, Math.PI * 2);
  ctx.fill();
}

function drawParticle(ctx, p) {
  ctx.globalAlpha = clamp(p.life / p.maxLife, 0, 1);
  ctx.fillStyle = p.color;
  ctx.beginPath();
  ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
  ctx.fill();
  ctx.globalAlpha = 1;
}

function drawDamageNum(ctx, d) {
  const a = clamp(d.life / d.maxLife, 0, 1);
  ctx.globalAlpha = a;
  ctx.fillStyle = d.color || "#fff";
  ctx.font = `bold ${14 + (1 - a) * 4}px Nunito, sans-serif`;
  ctx.textAlign = "center";
  ctx.fillText(d.text, d.x, d.y);
  ctx.globalAlpha = 1;
}

// ─── Game simulation ──────────────────────────────────────────────────────────
function createGame(stage, audio) {
  const cell = stage.cellSize;
  const cols = stage.cols;
  const rows = stage.rows;
  const pathPts = buildPathPoints(stage.path, cell);
  const pathSet = new Set(stage.path.map(([c, r]) => `${c},${r}`));
  const treeSet = new Set((stage.trees || []).map(([c, r]) => `${c},${r}`));
  const shopMap = Object.fromEntries(stage.shop.map((s) => [s.id, s]));
  const maxLevel = stage.maxLevel || 5;

  const worldW = cols * cell;
  const worldH = rows * cell;

  const state = {
    gold: stage.startGold,
    lives: stage.lives,
    waveIndex: -1,
    phase: "prep",
    units: [],
    enemies: [],
    projectiles: [],
    particles: [],
    dmgNums: [],
    selectedShop: null,
    selectedUnitId: null,
    toast: null,
    toastT: 0,
    time: 0,
    spawnQueue: [],
    enemiesRemaining: 0,
    kills: 0,
    shake: 0,
    hitstop: 0,
    evolveFx: null,
    hoverCell: null,
    waveTime: 0,
    message: "ユニットを配置して「ウェーブ開始」",
  };

  function toast(msg, dur = 1.6) {
    state.toast = msg;
    state.toastT = dur;
  }

  function canBuild(c, r) {
    if (c < 0 || r < 0 || c >= cols || r >= rows) return false;
    if (isPathCell(pathSet, c, r)) return false;
    if (isTreeCell(treeSet, c, r)) return false;
    if (state.units.some((u) => u.c === c && u.r === r)) return false;
    return true;
  }

  function cellCenter(c, r) {
    return { x: c * cell + cell / 2, y: r * cell + cell / 2 };
  }

  function snapBuildCell(c, r) {
    if (canBuild(c, r)) return { c, r };
    let best = null;
    let bestD = Infinity;
    for (let dr = -2; dr <= 2; dr++) {
      for (let dc = -2; dc <= 2; dc++) {
        const nc = c + dc;
        const nr = r + dr;
        if (!canBuild(nc, nr)) continue;
        const d = dc * dc + dr * dr;
        if (d < bestD) {
          bestD = d;
          best = { c: nc, r: nr };
        }
      }
    }
    return best;
  }

  function findStarterCells(n) {
    const adj = [];
    for (const [pc, pr] of stage.path) {
      for (const [dc, dr] of [
        [1, 0],
        [-1, 0],
        [0, 1],
        [0, -1],
      ]) {
        const c = pc + dc;
        const r = pr + dr;
        if (canBuild(c, r) && !adj.some((a) => a.c === c && a.r === r)) {
          adj.push({ c, r });
        }
      }
    }
    adj.sort((a, b) => a.r - b.r || a.c - b.c);
    return adj.slice(0, n);
  }

  function addParticles(x, y, color, n = 8) {
    for (let i = 0; i < n; i++) {
      const a = (Math.PI * 2 * i) / n + Math.random() * 0.4;
      const sp = 40 + Math.random() * 80;
      state.particles.push({
        x,
        y,
        vx: Math.cos(a) * sp,
        vy: Math.sin(a) * sp,
        r: 2 + Math.random() * 3,
        color,
        life: 0.35 + Math.random() * 0.3,
        maxLife: 0.5,
      });
    }
  }

  function addDmg(x, y, text, color) {
    state.dmgNums.push({
      x: x + (Math.random() - 0.5) * 10,
      y: y - 10,
      text: String(text),
      color: color || "#fff",
      life: 0.7,
      maxLife: 0.7,
      vy: -40,
    });
  }

  function placeUnit(c, r, typeId, level = 1) {
    const def = shopMap[typeId];
    if (!def || !canBuild(c, r)) return null;
    const pos = cellCenter(c, r);
    const u = {
      id: uid(),
      typeId,
      level,
      c,
      r,
      x: pos.x,
      y: pos.y,
      cooldown: 0,
      facing: 1,
      mergeFlash: 0,
    };
    state.units.push(u);
    addParticles(pos.x, pos.y, def.accent, 10);
    return u;
  }

  {
    const starters = findStarterCells(3);
    const types = ["puppy", "puppy", "kitty"];
    starters.forEach((cellPos, i) => {
      placeUnit(cellPos.c, cellPos.r, types[i] || "puppy", 1);
    });
  }

  function tryBuyPlace(c, r) {
    if (!state.selectedShop) return false;
    if (state.phase === "won" || state.phase === "lost") return false;
    const def = shopMap[state.selectedShop];
    if (!def) return false;
    if (state.gold < def.cost) {
      toast("ゴールドが足りないよ！");
      return false;
    }
    const snapped = snapBuildCell(c, r);
    if (!snapped) {
      toast("ここには置けないよ");
      return false;
    }
    state.gold -= def.cost;
    placeUnit(snapped.c, snapped.r, def.id, 1);
    audio.place();
    audio.buy();
    state.selectedUnitId = null;
    return true;
  }

  function trySelectOrMerge(c, r) {
    let unit = state.units.find((u) => u.c === c && u.r === r);

    if (state.selectedShop) {
      if (unit) {
        state.selectedShop = null;
        state.selectedUnitId = unit.id;
        return true;
      }
      return tryBuyPlace(c, r);
    }

    if (!unit) {
      let best = null;
      let bestD = Infinity;
      for (const u of state.units) {
        const d = (u.c - c) * (u.c - c) + (u.r - r) * (u.r - r);
        if (d <= 1 && d < bestD) {
          bestD = d;
          best = u;
        }
      }
      unit = best;
    }

    if (!unit) {
      state.selectedUnitId = null;
      return false;
    }

    if (state.selectedUnitId && state.selectedUnitId !== unit.id) {
      const a = state.units.find((u) => u.id === state.selectedUnitId);
      if (a && a.typeId === unit.typeId && a.level === unit.level && a.level < maxLevel) {
        const newLevel = unit.level + 1;
        const pos = { c: unit.c, r: unit.r, x: unit.x, y: unit.y };
        state.units = state.units.filter((u) => u.id !== a.id && u.id !== unit.id);
        const merged = placeUnit(pos.c, pos.r, unit.typeId, newLevel);
        if (merged) {
          merged.mergeFlash = 0.4;
          audio.merge();
          state.shake = Math.min(1, state.shake + 0.35);
          toast(`${shopMap[unit.typeId].name} Lv.${newLevel}！`);
          if (newLevel >= maxLevel) {
            state.evolveFx = {
              t: 0,
              max: 1.8,
              typeId: unit.typeId,
              x: pos.x,
              y: pos.y,
            };
            audio.evolve();
            toast("進化した！ ✨", 2.2);
          }
        }
        state.selectedUnitId = null;
        return true;
      }
    }

    state.selectedUnitId = unit.id;
    state.selectedShop = null;
    return true;
  }

  function sellSelected() {
    if (!state.selectedUnitId) return;
    const u = state.units.find((x) => x.id === state.selectedUnitId);
    if (!u) return;
    const def = shopMap[u.typeId];
    const refund = Math.floor(def.cost * 0.5 * Math.pow(1.6, u.level - 1));
    state.gold += refund;
    state.units = state.units.filter((x) => x.id !== u.id);
    state.selectedUnitId = null;
    addParticles(u.x, u.y, def.color, 12);
    toast(`売却 +${refund}G`);
    audio.buy();
  }

  function startWave() {
    if (state.phase !== "prep") return;
    if (state.waveIndex + 1 >= stage.waves.length) return;
    state.waveIndex += 1;
    state.phase = "combat";
    state.selectedShop = null;
    state.selectedUnitId = null;
    const wave = stage.waves[state.waveIndex];
    state.spawnQueue = [];
    let total = 0;
    for (const sp of wave.spawns) {
      for (let i = 0; i < sp.count; i++) {
        state.spawnQueue.push({
          at: sp.delay + i * sp.interval,
          type: sp.type,
          hp: sp.hp,
          speed: sp.speed,
          gold: sp.gold,
          color: sp.color,
          scale: sp.scale || 1,
        });
        total++;
      }
    }
    state.spawnQueue.sort((a, b) => a.at - b.at);
    state.enemiesRemaining = total;
    state.waveTime = 0;
    state.message = wave.name;
    toast(wave.name + " スタート！");
    audio.wave();
  }

  function spawnEnemy(spec) {
    const e = {
      id: uid(),
      type: spec.type,
      hp: spec.hp,
      maxHp: spec.hp,
      speed: spec.speed,
      gold: spec.gold,
      color: spec.color,
      scale: spec.scale || 1,
      dist: 0,
      x: pathPts[0].x,
      y: pathPts[0].y,
      alive: true,
    };
    state.enemies.push(e);
  }

  function damageEnemy(e, dmg) {
    if (!e.alive) return;
    e.hp -= dmg;
    addDmg(e.x, e.y - 8, dmg, dmg >= 20 ? "#ffd166" : "#fff");
    addParticles(e.x, e.y, e.color, 4);
    audio.hit();
    state.shake = Math.min(1, state.shake + 0.08);
    if (e.hp <= 0) {
      e.alive = false;
      e.hp = 0;
      state.gold += e.gold;
      state.kills += 1;
      state.enemiesRemaining = Math.max(0, state.enemiesRemaining - 1);
      addParticles(e.x, e.y, "#ffd166", 14);
      addDmg(e.x, e.y, `+${e.gold}G`, "#ffd166");
      audio.kill();
    }
  }

  function update(dt) {
    const cap = Math.min(dt, 0.05);
    state.time += cap;

    if (state.toastT > 0) {
      state.toastT -= cap;
      if (state.toastT <= 0) state.toast = null;
    }
    if (state.shake > 0) state.shake = Math.max(0, state.shake - cap * 2.2);
    if (state.evolveFx) {
      state.evolveFx.t += cap;
      if (state.evolveFx.t >= state.evolveFx.max) state.evolveFx = null;
    }

    for (const p of state.particles) {
      p.x += p.vx * cap;
      p.y += p.vy * cap;
      p.vy += 120 * cap;
      p.life -= cap;
    }
    state.particles = state.particles.filter((p) => p.life > 0);
    for (const d of state.dmgNums) {
      d.y += d.vy * cap;
      d.life -= cap;
    }
    state.dmgNums = state.dmgNums.filter((d) => d.life > 0);
    for (const u of state.units) {
      if (u.mergeFlash > 0) u.mergeFlash -= cap;
    }

    if (state.phase !== "combat") return;
    if (state.hitstop > 0) {
      state.hitstop -= cap;
      return;
    }

    state.waveTime += cap;

    while (state.spawnQueue.length && state.spawnQueue[0].at <= state.waveTime) {
      spawnEnemy(state.spawnQueue.shift());
    }

    for (const e of state.enemies) {
      if (!e.alive) continue;
      e.dist += e.speed * cap;
      const p = posOnPath(pathPts, e.dist);
      e.x = p.x;
      e.y = p.y;
      if (p.done) {
        e.alive = false;
        state.lives -= 1;
        state.enemiesRemaining = Math.max(0, state.enemiesRemaining - 1);
        state.shake = Math.min(1, state.shake + 0.55);
        toast("ライフを失った…");
        if (state.lives <= 0) {
          state.lives = 0;
          state.phase = "lost";
          audio.lose();
        }
      }
    }
    state.enemies = state.enemies.filter((e) => e.alive);

    const rangeScale = cell;
    for (const u of state.units) {
      const def = shopMap[u.typeId];
      const stats = unitStats(def, u.level);
      u.cooldown -= cap;
      let best = null;
      let bestDist = -1;
      const rangePx = stats.range * rangeScale;
      const r2 = rangePx * rangePx;
      for (const e of state.enemies) {
        if (!e.alive) continue;
        if (dist2(u.x, u.y, e.x, e.y) <= r2) {
          if (e.dist > bestDist) {
            best = e;
            bestDist = e.dist;
          }
        }
      }
      if (best) {
        u.facing = best.x >= u.x ? 1 : -1;
        if (u.cooldown <= 0) {
          u.cooldown = 1 / stats.fireRate;
          state.projectiles.push({
            x: u.x,
            y: u.y - 4,
            tx: best.x,
            ty: best.y,
            targetId: best.id,
            speed: 300 + u.level * 25,
            dmg: stats.dmg,
            color: u.level >= 4 ? "#ffd166" : def.accent,
            r: 3 + u.level * 0.5,
            life: 1.2,
          });
          audio.shoot();
        }
      }
    }

    for (const p of state.projectiles) {
      const target = state.enemies.find((e) => e.id === p.targetId && e.alive);
      if (target) {
        p.tx = target.x;
        p.ty = target.y;
      }
      const dx = p.tx - p.x;
      const dy = p.ty - p.y;
      const d = Math.hypot(dx, dy) || 1;
      const step = p.speed * cap;
      if (d <= step + 6) {
        p.life = 0;
        if (target) {
          damageEnemy(target, p.dmg);
          if (p.dmg >= 25) state.hitstop = 0.04;
        }
      } else {
        p.x += (dx / d) * step;
        p.y += (dy / d) * step;
        p.life -= cap;
      }
    }
    state.projectiles = state.projectiles.filter((p) => p.life > 0);

    if (
      state.spawnQueue.length === 0 &&
      state.enemies.length === 0 &&
      state.phase === "combat"
    ) {
      if (state.waveIndex >= stage.waves.length - 1) {
        state.phase = "won";
        state.gold += 50;
        audio.win();
        toast("ステージクリア！ 🎉", 3);
      } else {
        state.phase = "prep";
        const bonus = 30 + state.waveIndex * 12;
        state.gold += bonus;
        state.message = "準備フェーズ — ユニットを強化しよう";
        toast(`クリア！ +${bonus}G`, 2);
      }
    }
  }

  function draw(ctx, viewW, viewH) {
    const scale = Math.min(viewW / worldW, viewH / worldH);
    const ox = (viewW - worldW * scale) / 2;
    const oy = (viewH - worldH * scale) / 2;
    const shakeAmt = state.shake * state.shake * 10;
    const sx = (Math.random() - 0.5) * shakeAmt;
    const sy = (Math.random() - 0.5) * shakeAmt;

    ctx.save();
    ctx.clearRect(0, 0, viewW, viewH);
    ctx.fillStyle = "#1b4332";
    ctx.fillRect(0, 0, viewW, viewH);
    ctx.translate(ox + sx, oy + sy);
    ctx.scale(scale, scale);

    for (let r = 0; r < rows; r++) {
      for (let c = 0; c < cols; c++) {
        ctx.fillStyle = (c + r) % 2 === 0 ? "#74c69d" : "#52b788";
        ctx.fillRect(c * cell, r * cell, cell, cell);
      }
    }

    ctx.strokeStyle = "#c4b5a0";
    ctx.lineWidth = cell * 0.72;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
    ctx.beginPath();
    pathPts.forEach((p, i) => (i === 0 ? ctx.moveTo(p.x, p.y) : ctx.lineTo(p.x, p.y)));
    ctx.stroke();
    ctx.strokeStyle = "#d9cbb8";
    ctx.lineWidth = cell * 0.42;
    ctx.beginPath();
    pathPts.forEach((p, i) => (i === 0 ? ctx.moveTo(p.x, p.y) : ctx.lineTo(p.x, p.y)));
    ctx.stroke();

    const sp = pathPts[0];
    ctx.fillStyle = "rgba(230,57,70,0.35)";
    ctx.beginPath();
    ctx.arc(sp.x, sp.y, cell * 0.28, 0, Math.PI * 2);
    ctx.fill();
    ctx.fillStyle = "#e76f51";
    ctx.font = `bold ${cell * 0.28}px Nunito`;
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.fillText("IN", sp.x, sp.y);

    const bp = pathPts[pathPts.length - 1];
    ctx.fillStyle = "#8b5a2b";
    for (let i = -2; i <= 2; i++) {
      ctx.fillRect(bp.x - cell * 0.35, bp.y - cell * 0.1 + i * cell * 0.12, cell * 0.7, 4);
      ctx.fillRect(
        bp.x - cell * 0.3 + (i + 2) * cell * 0.14,
        bp.y - cell * 0.22,
        4,
        cell * 0.4
      );
    }
    ctx.fillStyle = "#ffd166";
    ctx.font = `bold ${cell * 0.22}px Nunito`;
    ctx.fillText("BASE", bp.x, bp.y + cell * 0.38);

    for (const [c, r] of stage.trees || []) {
      drawTree(ctx, c * cell + cell / 2, r * cell + cell / 2, cell, c * 13 + r);
    }

    if (state.selectedShop && state.phase !== "won" && state.phase !== "lost") {
      for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) {
          if (canBuild(c, r)) {
            ctx.fillStyle = "rgba(255,209,102,0.16)";
            ctx.strokeStyle = "rgba(255,209,102,0.4)";
            ctx.lineWidth = 1.5;
            drawRoundedRect(ctx, c * cell + 4, r * cell + 4, cell - 8, cell - 8, 8);
            ctx.fill();
            ctx.stroke();
          }
        }
      }
      if (state.hoverCell) {
        const snapped = snapBuildCell(state.hoverCell.c, state.hoverCell.r);
        if (snapped) {
          const def = shopMap[state.selectedShop];
          ctx.fillStyle = "rgba(255,209,102,0.4)";
          drawRoundedRect(
            ctx,
            snapped.c * cell + 3,
            snapped.r * cell + 3,
            cell - 6,
            cell - 6,
            8
          );
          ctx.fill();
          const pos = cellCenter(snapped.c, snapped.r);
          ctx.globalAlpha = 0.55;
          drawCritter(ctx, pos.x, pos.y, cell * 0.75, def, 1, 1, state.time);
          ctx.globalAlpha = 1;
        }
      }
    }

    if (state.selectedUnitId) {
      const u = state.units.find((x) => x.id === state.selectedUnitId);
      if (u) {
        const def = shopMap[u.typeId];
        const stats = unitStats(def, u.level);
        ctx.strokeStyle = "rgba(255,255,255,0.35)";
        ctx.fillStyle = "rgba(255,255,255,0.06)";
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.arc(u.x, u.y, stats.range * cell, 0, Math.PI * 2);
        ctx.fill();
        ctx.stroke();
        ctx.strokeStyle = "rgba(255,209,102,0.9)";
        ctx.lineWidth = 2.5;
        drawRoundedRect(ctx, u.c * cell + 2, u.r * cell + 2, cell - 4, cell - 4, 8);
        ctx.stroke();
      }
    }

    for (const u of state.units) {
      const def = shopMap[u.typeId];
      const flash = u.mergeFlash > 0;
      if (flash) {
        ctx.save();
        const t = easeOutBack(1 - u.mergeFlash / 0.4);
        ctx.translate(u.x, u.y);
        ctx.scale(0.8 + t * 0.35, 0.8 + t * 0.35);
        ctx.translate(-u.x, -u.y);
      }
      drawCritter(ctx, u.x, u.y, cell * 0.78, def, u.level, u.facing, state.time);
      if (flash) ctx.restore();
    }

    const sortedE = [...state.enemies].sort((a, b) => a.y - b.y);
    for (const e of sortedE) drawEnemy(ctx, e.x, e.y, cell * 0.7, e, state.time);
    for (const p of state.projectiles) drawProjectile(ctx, p);
    for (const p of state.particles) drawParticle(ctx, p);
    for (const d of state.dmgNums) drawDamageNum(ctx, d);

    if (state.evolveFx) {
      const fx = state.evolveFx;
      const t = fx.t / fx.max;
      ctx.save();
      ctx.translate(fx.x, fx.y);
      if (t < 0.55) {
        const s = cell * (0.5 + t * 0.6);
        ctx.fillStyle = "rgba(10,10,20,0.85)";
        ctx.beginPath();
        ctx.ellipse(0, 0, s * 0.55, s * 0.7, 0, 0, Math.PI * 2);
        ctx.fill();
        for (let i = 0; i < 8; i++) {
          const a = state.time * 3 + i * 0.8;
          const rr = s * 0.5 + Math.sin(state.time * 5 + i) * 6;
          ctx.fillStyle = "#ffd166";
          ctx.beginPath();
          ctx.arc(Math.cos(a) * rr, Math.sin(a) * rr, 3, 0, Math.PI * 2);
          ctx.fill();
        }
        ctx.fillStyle = "#fff";
        ctx.font = `bold ${cell * 0.28}px "M PLUS Rounded 1c", sans-serif`;
        ctx.textAlign = "center";
        ctx.fillText("進化中...", 0, -s * 0.9);
        ctx.font = `bold ${cell * 0.35}px Nunito`;
        ctx.fillText("???", 0, s * 0.15);
      } else {
        const burst = (t - 0.55) / 0.45;
        ctx.globalAlpha = 1 - burst;
        ctx.strokeStyle = "#ffd166";
        ctx.lineWidth = 4;
        ctx.beginPath();
        ctx.arc(0, 0, cell * 0.3 + burst * cell * 1.2, 0, Math.PI * 2);
        ctx.stroke();
        ctx.globalAlpha = 1;
      }
      ctx.restore();
    }

    ctx.restore();
    return { scale, ox, oy, worldW, worldH, cell };
  }

  function screenToCell(clientX, clientY, canvas, view) {
    const rect = canvas.getBoundingClientRect();
    const x = ((clientX - rect.left) / rect.width) * canvas.width;
    const y = ((clientY - rect.top) / rect.height) * canvas.height;
    const wx = (x - view.ox) / view.scale;
    const wy = (y - view.oy) / view.scale;
    const c = Math.floor(wx / cell);
    const r = Math.floor(wy / cell);
    return { c, r, wx, wy };
  }

  return {
    state,
    stage,
    shopMap,
    maxLevel,
    worldW,
    worldH,
    cell,
    update,
    draw,
    screenToCell,
    tryBuyPlace,
    trySelectOrMerge,
    startWave,
    sellSelected,
    setShop(id) {
      state.selectedShop = state.selectedShop === id ? null : id;
      state.selectedUnitId = null;
    },
    toast,
  };
}

// ─── Components ───────────────────────────────────────────────────────────────

function TitleScreen({ stages, loading, error, onSelect }) {
  return (
    <div className="screen">
      <div className="title-hero">
        <div className="badge">★ MONSTER SURVIVAL ★</div>
        <h1 className="logo">
          モンスター
          <br />
          サバイバル
        </h1>
        <p className="logo-sub">あなたのデジタルペットの楽園！</p>
        <div className="critter-row" aria-hidden>
          <span>🐶</span>
          <span>🐱</span>
          <span>🐦</span>
          <span>🦊</span>
        </div>
      </div>

      <div className="panel" style={{ marginBottom: 16 }}>
        <div style={{ fontWeight: 800, fontSize: 14, marginBottom: 4 }}>ステージを選ぼう</div>
        <div style={{ color: "var(--muted)", fontSize: 12, fontWeight: 600 }}>
          ステージデータは JSON から取得
        </div>

        {loading && (
          <div className="loading" style={{ marginTop: 20 }}>
            <div className="spinner" />
            ステージ読込中…
          </div>
        )}
        {error && <div className="error-box">{error}</div>}

        {!loading && !error && (
          <div className="stage-list">
            {stages.map((s) => (
              <button key={s.id} className="stage-card" onClick={() => onSelect(s.id)}>
                <div className="stage-num">{s.id}</div>
                <div>
                  <div className="stage-name">{s.name}</div>
                  <div className="stage-meta">
                    {s.subtitle || ""} · 🌊 {s.waves} · ❤️ {s.lives} · 🪙 {s.startGold}
                  </div>
                </div>
                <div className="stage-go">PLAY</div>
              </button>
            ))}
          </div>
        )}

        <p className="howto">
          <strong>遊び方:</strong> ショップで購入 → 草地に配置 →{" "}
          <strong>同じレベル同士を連続タップでマージ</strong> → ウェーブを生き残ろう！
        </p>
      </div>
    </div>
  );
}

function GameView({ stageId, onExit }) {
  const [stage, setStage] = useState(null);
  const [error, setError] = useState(null);
  const [tick, setTick] = useState(0);
  const [ready, setReady] = useState(false);
  const canvasRef = useRef(null);
  const gameRef = useRef(null);
  const audioRef = useRef(null);
  const viewRef = useRef(null);
  const rafRef = useRef(0);
  const lastRef = useRef(0);

  useEffect(() => {
    let alive = true;
    setStage(null);
    setReady(false);
    setError(null);
    fetchFirstJSON(API.stageCandidates(stageId))
      .then((data) => {
        if (!alive) return;
        if (data.error && !data.path) throw new Error(data.error);
        setStage(data);
      })
      .catch((e) => {
        if (alive) setError(e.message || "ステージの読み込みに失敗");
      });
    return () => {
      alive = false;
    };
  }, [stageId]);

  useEffect(() => {
    if (!stage) return;
    if (!audioRef.current) audioRef.current = createAudio();
    gameRef.current = createGame(stage, audioRef.current);
    setReady(true);
    lastRef.current = performance.now();

    const loop = (now) => {
      const g = gameRef.current;
      const canvas = canvasRef.current;
      if (!g || !canvas) {
        rafRef.current = requestAnimationFrame(loop);
        return;
      }
      const dt = Math.min(0.05, (now - lastRef.current) / 1000);
      lastRef.current = now;
      g.update(dt);

      const parent = canvas.parentElement;
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      const cssW = parent.clientWidth;
      const cssH = parent.clientHeight;
      const w = Math.max(1, Math.floor(cssW * dpr));
      const h = Math.max(1, Math.floor(cssH * dpr));
      if (canvas.width !== w || canvas.height !== h) {
        canvas.width = w;
        canvas.height = h;
      }
      const ctx = canvas.getContext("2d");
      viewRef.current = g.draw(ctx, w, h);
      setTick((t) => (t + 1) % 100000);
      rafRef.current = requestAnimationFrame(loop);
    };
    rafRef.current = requestAnimationFrame(loop);
    return () => {
      cancelAnimationFrame(rafRef.current);
      setReady(false);
    };
  }, [stage]);

  const pointerCell = useCallback((e) => {
    const g = gameRef.current;
    const canvas = canvasRef.current;
    const view = viewRef.current;
    if (!g || !canvas || !view) return null;
    const pt = e.touches ? e.touches[0] || e.changedTouches[0] : e;
    return g.screenToCell(pt.clientX, pt.clientY, canvas, view);
  }, []);

  const onPointerDown = (e) => {
    e.preventDefault();
    audioRef.current && audioRef.current.unlock();
    const cell = pointerCell(e);
    if (!cell || !gameRef.current) return;
    gameRef.current.trySelectOrMerge(cell.c, cell.r);
  };

  const onPointerMove = (e) => {
    const g = gameRef.current;
    if (!g) return;
    const cell = pointerCell(e);
    if (!cell) return;
    g.state.hoverCell = { c: cell.c, r: cell.r };
  };

  if (error) {
    return (
      <div className="screen" style={{ justifyContent: "center", gap: 12 }}>
        <div className="panel">
          <div className="error-box">ステージ読込エラー: {error}</div>
          <button className="btn btn-ghost btn-block" style={{ marginTop: 12 }} onClick={onExit}>
            戻る
          </button>
        </div>
      </div>
    );
  }

  if (!stage || !ready) {
    return (
      <div className="screen" style={{ justifyContent: "center" }}>
        <div className="loading">
          <div className="spinner" />
          ステージ JSON を取得中…
          <div style={{ fontSize: 11 }}>GET /data/stages/{stageId}.json</div>
        </div>
      </div>
    );
  }

  const g = gameRef.current;
  const st = g.state;

  return (
    <div className="game-shell">
      <div className="hud">
        <div className="hud-left">
          <div className="pill gold">🪙 {st.gold}</div>
          <div className="pill life">❤️ {st.lives}</div>
        </div>
        <div className="hud-title">
          <b>{stage.name}</b>
          {st.waveIndex >= 0 ? stage.waves[st.waveIndex]?.name || "" : "準備中"}
        </div>
        <div className="hud-right">
          <div className="pill wave">
            🌊 {Math.max(0, st.waveIndex + 1)}/{stage.waves.length}
          </div>
        </div>
      </div>

      <div className="canvas-wrap">
        <canvas
          ref={canvasRef}
          onMouseDown={onPointerDown}
          onMouseMove={onPointerMove}
          onTouchStart={onPointerDown}
          onTouchMove={onPointerMove}
        />
        {st.toast && <div className="toast">{st.toast}</div>}
        {st.phase === "prep" && st.waveIndex < 0 && (
          <div className="hint-bar">
            初期ユニット配置済み！ ショップで追加 → 同じ子を連続タップでマージ →「ウェーブ開始」
          </div>
        )}
        {st.phase === "prep" && st.waveIndex >= 0 && (
          <div className="hint-bar">同じユニット同士を連続タップでマージ強化！</div>
        )}

        {st.phase === "won" && (
          <div className="overlay">
            <div className="panel overlay-card">
              <h2>クリア！</h2>
              <p>
                {stage.name} を守りきった！
                <br />
                撃破 {st.kills} · 残りライフ {st.lives}
              </p>
              <div className="overlay-actions">
                <button className="btn btn-primary btn-block" onClick={onExit}>
                  ステージ選択へ
                </button>
              </div>
            </div>
          </div>
        )}
        {st.phase === "lost" && (
          <div className="overlay">
            <div className="panel overlay-card">
              <h2>敗北…</h2>
              <p>
                ベースが突破されてしまった。
                <br />
                マージでユニットを強化してみよう！
              </p>
              <div className="overlay-actions">
                <button
                  className="btn btn-danger btn-block"
                  onClick={() => {
                    audioRef.current && audioRef.current.unlock();
                    gameRef.current = createGame(stage, audioRef.current);
                  }}
                >
                  もう一度
                </button>
                <button className="btn btn-ghost btn-block" onClick={onExit}>
                  ステージ選択へ
                </button>
              </div>
            </div>
          </div>
        )}
      </div>

      <div className="shop">
        {stage.shop.map((item) => {
          const selected = st.selectedShop === item.id;
          const cant = st.gold < item.cost;
          return (
            <button
              key={item.id}
              className={`shop-card ${selected ? "selected" : ""} ${cant ? "cant" : ""}`}
              onClick={() => {
                audioRef.current && audioRef.current.unlock();
                gameRef.current && gameRef.current.setShop(item.id);
              }}
            >
              <div className="shop-emoji" style={{ background: item.color }}>
                {item.emoji}
              </div>
              <div className="shop-name">{item.name}</div>
              <div className="shop-cost">🪙 {item.cost}</div>
            </button>
          );
        })}
      </div>

      <div className="controls-bar">
        <button className="btn btn-ghost" onClick={onExit}>
          戻る
        </button>
        <button
          className="btn btn-ghost"
          disabled={!st.selectedUnitId}
          onClick={() => gameRef.current && gameRef.current.sellSelected()}
        >
          売却
        </button>
        <button
          className="btn btn-accent"
          disabled={st.phase !== "prep"}
          onClick={() => {
            audioRef.current && audioRef.current.unlock();
            gameRef.current && gameRef.current.startWave();
          }}
        >
          {st.phase === "combat"
            ? "戦闘中…"
            : st.waveIndex + 1 >= stage.waves.length
            ? "完了"
            : "ウェーブ開始"}
        </button>
      </div>
      <span style={{ display: "none" }}>{tick}</span>
    </div>
  );
}

function App() {
  const [screen, setScreen] = useState("title");
  const [stages, setStages] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [stageId, setStageId] = useState(null);

  useEffect(() => {
    let alive = true;
    fetchFirstJSON(API.stagesCandidates)
      .then((data) => {
        if (!alive) return;
        setStages(data.stages || []);
        setLoading(false);
      })
      .catch((e) => {
        if (!alive) return;
        setError("ステージ一覧の取得に失敗: " + (e.message || e));
        setLoading(false);
      });
    return () => {
      alive = false;
    };
  }, []);

  if (screen === "game" && stageId) {
    return (
      <div className="app">
        <GameView
          stageId={stageId}
          onExit={() => {
            setScreen("title");
            setStageId(null);
          }}
        />
      </div>
    );
  }

  return (
    <div className="app">
      <TitleScreen
        stages={stages}
        loading={loading}
        error={error}
        onSelect={(id) => {
          setStageId(id);
          setScreen("game");
        }}
      />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
