// Games Room page

function GamesPage() {
  const { lang } = useT();
  const L = window.I18N[lang].games;
  const [filter, setFilter] = useState("all");

  const games = window.GAMES;
  const filtered = filter === "all" ? games : games.filter(g => g.template === filter);

  const filters = [
    { id: "all", label: L.filterAll, color: "var(--ink)" },
    ...window.TEMPLATES.map(t => ({ id: t.id, label: t[lang].name, color: t.color, emoji: t.emoji })),
  ];

  // Opens the actual game in a new tab
  const openGame = (g) => {
    window.open(`games/${g.id}/index.html`, "_blank", "noopener");
  };

  return (
    <div className="page-enter">
      <section style={{ paddingTop: 60, paddingBottom: 40 }}>
        <div className="container">
          <div className="eyebrow">{L.eyebrow} 🎮</div>
          <h1 style={{ marginTop: 18, maxWidth: 800 }}>{L.title}</h1>
          <p style={{ fontSize: "1.2rem", maxWidth: 640 }}>{L.sub}</p>

          {/* Filter chips */}
          <div className="row mt-3" style={{ gap: 10, marginTop: 24 }}>
            {filters.map(f => (
              <button key={f.id}
                onClick={() => setFilter(f.id)}
                className="btn btn-small"
                style={{
                  background: filter === f.id ? f.color : "var(--paper)",
                  color: filter === f.id ? "#fff" : "var(--ink)",
                  fontSize: "0.9rem",
                }}>
                {f.emoji ? `${f.emoji} ` : ""}{f.label}
              </button>
            ))}
          </div>
        </div>
      </section>

      <section style={{ paddingTop: 20 }}>
        <div className="container">
          {filtered.length === 0 ? (
            <div className="card center" style={{ padding: 60 }}>
              <Cloud size={80} />
              <p className="hand" style={{ fontSize: "1.4rem", marginTop: 20 }}>{L.empty}</p>
            </div>
          ) : (
            <div className="grid grid-3">
              {filtered.map((g, i) => <GameCard key={g.id} game={g} idx={i} lang={lang} onPlay={() => openGame(g)} L={L} />)}
            </div>
          )}
        </div>
      </section>
    </div>
  );
}

function GameCard({ game, idx, lang, onPlay, L }) {
  const tpl = window.TEMPLATES.find(t => t.id === game.template);
  return (
    <div className="card wiggle-hover" style={{
      padding: 0, overflow: "hidden",
      transform: `rotate(${[-1.5, 1, -0.5, 1.2, -1, 0.8][idx % 6]}deg)`,
      cursor: "pointer",
    }} onClick={onPlay}>
      <div style={{
        background: game.bg,
        padding: 28,
        position: "relative",
        aspectRatio: "1.1 / 1",
        display: "grid",
        placeItems: "center",
        borderBottom: "3px solid var(--ink)",
      }}>
        <KidDoodle kind={game.shape} color={game.heroColor} size={140} />
        {/* Template badge */}
        <div className="pill" style={{
          position: "absolute", top: 12, left: 12,
          background: tpl.color, color: "#fff",
          fontFamily: "var(--font-pixel)", fontSize: 9,
          border: "2px solid var(--ink)",
        }}>
          {tpl.emoji} {game.templateLabel}
        </div>
        {/* Plays badge */}
        <div className="pill" style={{
          position: "absolute", top: 12, right: 12,
          background: "var(--paper)", color: "var(--ink)",
          fontFamily: "var(--font-hand)", fontSize: 14,
          border: "2px solid var(--ink)",
        }}>
          ▶ {game.plays}
        </div>
        {/* Play button overlay */}
        <div className="btn btn-red" style={{
          position: "absolute", bottom: -22, right: 20,
          fontSize: "1rem", padding: "10px 20px",
        }}>{L.play}</div>
      </div>
      <div style={{ padding: "28px 20px 18px" }}>
        <div className="display" style={{ fontSize: "1.15rem", marginBottom: 4 }}>
          {lang === "th" ? game.titleTh : game.title}
        </div>
        <div className="hand" style={{ fontSize: "1rem", opacity: 0.65 }}>
          {L.by} {game.author}, {game.age}
        </div>
      </div>
    </div>
  );
}

// Game modal — mini playable mock
function GameModal({ game, lang, onClose, L }) {
  const [playing, setPlaying] = useState(false);

  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  return (
    <div style={{
      position: "fixed", inset: 0, background: "rgba(17,17,17,0.7)",
      display: "grid", placeItems: "center", zIndex: 100,
      padding: 20,
    }} onClick={onClose}>
      <div className="card" style={{
        background: "var(--paper)", maxWidth: 720, width: "100%",
        padding: 0, overflow: "hidden", transform: "none",
        animation: "modalIn 0.3s ease",
      }} onClick={(e) => e.stopPropagation()}>
        <div className="tape" style={{ background: "var(--orange)" }} />
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "20px 24px", borderBottom: "3px solid var(--ink)" }}>
          <div>
            <div className="display" style={{ fontSize: "1.4rem" }}>{lang === "th" ? game.titleTh : game.title}</div>
            <div className="hand" style={{ fontSize: "1.05rem", opacity: 0.7 }}>{L.by} {game.author}, {game.age}</div>
          </div>
          <button onClick={onClose} className="btn btn-small btn-ink">✕</button>
        </div>

        <div style={{ background: game.bg, padding: 30, position: "relative" }}>
          {playing ? (
            <MiniGame game={game} />
          ) : (
            <div style={{ aspectRatio: "16 / 10", background: "#fffaca", border: "3px dashed var(--ink)", borderRadius: 12, display: "grid", placeItems: "center", position: "relative" }}>
              <KidDoodle kind={game.shape} color={game.heroColor} size={140} />
              <button className="btn btn-red btn-big" style={{ position: "absolute", bottom: 24, left: "50%", transform: "translateX(-50%)" }} onClick={() => setPlaying(true)}>
                ▶ {L.modalPlay}
              </button>
            </div>
          )}
        </div>

        <div style={{ padding: 24 }}>
          <p style={{ fontSize: "1.1rem", margin: 0 }}>{lang === "th" ? game.storyTh : game.story}</p>
        </div>

        <style>{`
          @keyframes modalIn {
            from { opacity: 0; transform: scale(0.92); }
            to { opacity: 1; transform: scale(1); }
          }
        `}</style>
      </div>
    </div>
  );
}

// A tiny actually-playable mini game (uses keyboard / click)
function MiniGame({ game }) {
  const { lang } = useT();
  const [score, setScore] = useState(0);
  const [tick, setTick] = useState(0);
  const [heroX, setHeroX] = useState(60);
  const [heroY, setHeroY] = useState(0);
  const [jumping, setJumping] = useState(false);
  const [obstacles, setObstacles] = useState([]);
  const [gameOver, setGameOver] = useState(false);
  const keys = useRef({});

  useEffect(() => {
    const down = (e) => { keys.current[e.key] = true; if (e.key === " " || e.key === "ArrowUp") jump(); };
    const up = (e) => { keys.current[e.key] = false; };
    window.addEventListener("keydown", down);
    window.addEventListener("keyup", up);
    return () => { window.removeEventListener("keydown", down); window.removeEventListener("keyup", up); };
  });

  const jump = () => {
    if (jumping || gameOver) return;
    setJumping(true);
    let v = 14;
    const id = setInterval(() => {
      setHeroY(y => {
        const ny = y + v;
        v -= 1;
        if (ny <= 0) {
          clearInterval(id);
          setJumping(false);
          return 0;
        }
        return ny;
      });
    }, 30);
  };

  useEffect(() => {
    if (gameOver) return;
    const id = setInterval(() => {
      setTick(t => t + 1);
      setScore(s => s + 1);
      setObstacles(obs => {
        const moved = obs.map(o => ({ ...o, x: o.x - 8 })).filter(o => o.x > -40);
        if (Math.random() < 0.05 && (moved.length === 0 || moved[moved.length-1].x < 280)) {
          moved.push({ x: 600, id: Date.now() });
        }
        return moved;
      });
    }, 50);
    return () => clearInterval(id);
  }, [gameOver]);

  // collision detection
  useEffect(() => {
    for (const o of obstacles) {
      if (o.x < heroX + 30 && o.x > heroX - 20 && heroY < 35) {
        setGameOver(true);
        return;
      }
    }
  }, [obstacles, heroY, heroX]);

  const restart = () => {
    setScore(0); setHeroY(0); setJumping(false); setObstacles([]); setGameOver(false);
  };

  return (
    <div style={{ position: "relative" }}>
      <div style={{
        aspectRatio: "16 / 10",
        background: "linear-gradient(180deg, #BEE7FF 0%, #FFFAC5 70%)",
        border: "3px solid var(--ink)",
        borderRadius: 12,
        position: "relative",
        overflow: "hidden",
        userSelect: "none",
      }} onClick={jump}>
        {/* Ground */}
        <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, height: 60, background: "var(--green)", borderTop: "3px solid var(--ink)" }} />
        {/* Clouds */}
        <div style={{ position: "absolute", top: 30, left: 60 + Math.sin(tick * 0.05) * 20 }}><Cloud size={70} /></div>
        <div style={{ position: "absolute", top: 50, right: 80 }}><Cloud size={50} /></div>
        {/* Hero */}
        <div style={{ position: "absolute", bottom: 60 + heroY, left: heroX, transition: "none" }}>
          <KidDoodle kind={game.shape} color={game.heroColor} size={72} />
        </div>
        {/* Obstacles */}
        {obstacles.map(o => (
          <div key={o.id} style={{ position: "absolute", bottom: 60, left: o.x }}>
            <svg width="40" height="50" viewBox="0 0 40 50">
              <path d="M16 4 Q4 4, 4 18 L4 46 L36 46 L36 18 Q36 4, 24 4 Z" fill="var(--purple)" stroke="var(--ink)" strokeWidth="3" />
            </svg>
          </div>
        ))}
        {/* Score */}
        <div className="pill" style={{ position: "absolute", top: 10, right: 10, background: "var(--ink)", color: "var(--paper)", fontFamily: "var(--font-pixel)", fontSize: 12 }}>
          {String(score).padStart(5, "0")}
        </div>
        {/* Help text */}
        {!gameOver && score < 20 && (
          <div style={{ position: "absolute", bottom: 80, left: "50%", transform: "translateX(-50%) rotate(-3deg)" }}>
            <div className="pill" style={{ background: "var(--paper)", color: "var(--ink)", border: "3px solid var(--ink)", fontFamily: "var(--font-hand)", fontSize: 16, padding: "6px 14px" }}>
              ↑ {lang === "th" ? "หรือกดเพื่อกระโดด" : "or tap to jump!"}
            </div>
          </div>
        )}
        {/* Game over */}
        {gameOver && (
          <div style={{ position: "absolute", inset: 0, background: "rgba(255,235,80,0.92)", display: "grid", placeItems: "center" }}>
            <div className="center">
              <div className="display" style={{ fontSize: "2rem" }}>GAME OVER</div>
              <div className="hand" style={{ fontSize: "1.4rem", marginBottom: 16 }}>Score: {score}</div>
              <button className="btn btn-red" onClick={restart}>Try again →</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.GamesPage = GamesPage;
