/* ClientBase, page 404 (pages-404.jsx)
   --------------------------------------------------------------------------
   Quand l'utilisateur arrive sur une URL inconnue, plutôt qu'une page vide
   ou un fallback maladroit vers la home, on affiche une page 404 sympa
   avec un mini-jeu d'attrape-RDV. Pendant 20 s, des chips RDV apparaissent
   à des positions aléatoires dans une zone de jeu : à chaque clic = +1
   point + chip qui disparaît. Score final + CTA retour.

   But : transformer un cul-de-sac en moment de jeu mémorable. Si quelqu'un
   tombe par hasard sur /quelque-chose-de-faux, il rigole et clique vers
   la home. */

const NotFoundGame = () => {
  const [phase, setPhase] = React.useState("idle"); // idle | playing | done
  const [score, setScore] = React.useState(0);
  const [timeLeft, setTimeLeft] = React.useState(20);
  const [targets, setTargets] = React.useState([]); // [{ id, x, y, dur }]
  const playRef = React.useRef(null);
  const fieldRef = React.useRef(null);
  const intervals = React.useRef({ tick: null, spawn: null });

  // Lance/relance la partie
  const start = () => {
    setPhase("playing");
    setScore(0);
    setTimeLeft(20);
    setTargets([]);
  };

  // Boucle de jeu : timer + spawner. On nettoie tout sur fin/démontage.
  React.useEffect(() => {
    if (phase !== "playing") return;
    intervals.current.tick = setInterval(() => {
      setTimeLeft(t => {
        if (t <= 1) {
          clearInterval(intervals.current.tick);
          clearInterval(intervals.current.spawn);
          setPhase("done");
          setTargets([]);
          return 0;
        }
        return t - 1;
      });
    }, 1000);

    let nextId = 1;
    const spawnOne = () => {
      const dur = 1500 + Math.random() * 800; // chaque cible vit 1.5–2.3s
      const id = nextId++;
      setTargets(curr => {
        // Position aléatoire en pourcentage du terrain de jeu, avec marges
        // pour éviter que la chip sorte du cadre.
        const x = 6 + Math.random() * 84; // 6%-90%
        const y = 8 + Math.random() * 78; // 8%-86%
        const next = [...curr, { id, x, y, dur }];
        // Auto-disparition au bout de `dur` ms si la cible n'a pas été cliquée
        setTimeout(() => {
          setTargets(c => c.filter(t => t.id !== id));
        }, dur);
        return next;
      });
    };
    // Cadence : un spawn toutes les 550 ms (env.). Démarre une fois après 50 ms
    // pour ne pas attendre la 1re seconde à blanc.
    setTimeout(spawnOne, 50);
    intervals.current.spawn = setInterval(spawnOne, 550);

    return () => {
      clearInterval(intervals.current.tick);
      clearInterval(intervals.current.spawn);
    };
  }, [phase]);

  const catchOne = (id) => {
    setTargets(curr => curr.filter(t => t.id !== id));
    setScore(s => s + 1);
  };

  // Verdict final selon le score : message + emoji + sous-texte.
  const verdict = (() => {
    if (score >= 30) return { emoji: "🚀", title: "Wow, vous gérez !",         sub: "Sérieusement, vous devriez postuler pour gérer notre support." };
    if (score >= 20) return { emoji: "💪", title: "Pro confirmé·e",            sub: "Avec un agenda comme ClientBase, vous serez intouchable." };
    if (score >= 12) return { emoji: "👍", title: "Pas mal du tout",           sub: "ClientBase vous donnerait un coup de pouce pour les RDV plus délicats." };
    if (score >= 6)  return { emoji: "🌱", title: "Petit warm-up",             sub: "Promis, gérer ses vrais RDV est plus facile que ça." };
    return                  { emoji: "😄", title: "Bon, c'est juste un jeu",   sub: "Heureusement, ClientBase gère vos RDV à votre place." };
  })();

  return (
    <section style={{ padding: "48px 20px 80px", minHeight: "calc(100vh - 64px)" }}>
      <div className="container" style={{ maxWidth: 720, textAlign: "center" }}>
        <div style={{
          display: "inline-flex", alignItems: "center", gap: 6,
          padding: "5px 12px 5px 10px",
          background: "var(--accent-soft)", border: "1px solid var(--accent-soft-2)",
          borderRadius: 999, fontSize: 12, fontWeight: 540, color: "var(--accent-ink)",
          marginBottom: 16,
        }}>
          <span style={{ width: 6, height: 6, borderRadius: 50, background: "var(--accent)" }}/>
          Erreur 404
        </div>

        <h1 style={{
          margin: 0, fontFamily: "var(--ff-display)",
          fontSize: "clamp(34px, 5vw, 56px)", fontWeight: 600,
          letterSpacing: "-0.035em", lineHeight: 1.05,
        }}>
          Cette page n'existe pas…
          <br/>
          <span style={{
            backgroundImage: "linear-gradient(to top, color-mix(in oklab, var(--accent) 45%, transparent) 36%, transparent 36%)",
            paddingInline: "0.04em",
            boxDecorationBreak: "clone",
            WebkitBoxDecorationBreak: "clone",
          }}>mais voici un petit jeu.</span>
        </h1>

        <p style={{
          marginTop: 16, fontSize: 15.5, color: "var(--ink-3)",
          maxWidth: 520, margin: "16px auto 0", lineHeight: 1.55,
        }}>
          Attrapez le maximum de rendez-vous en 20 secondes. Cliquez sur chaque chip dès qu'elle apparaît, avant qu'elle disparaisse.
        </p>

        {/* HUD : timer + score + bouton */}
        <div style={{
          marginTop: 26, display: "flex", justifyContent: "center",
          alignItems: "center", gap: 14, flexWrap: "wrap",
        }}>
          <div style={{
            padding: "8px 14px",
            background: "var(--surface)", border: "1px solid var(--line)",
            borderRadius: 999, fontSize: 13, color: "var(--ink-2)",
            display: "inline-flex", alignItems: "center", gap: 8,
            fontVariantNumeric: "tabular-nums",
          }}>
            <Icon name="clock" size={14} style={{ color: "var(--ink-3)" }}/>
            <span>
              <strong style={{ fontWeight: 660, color: phase === "playing" && timeLeft <= 5 ? "oklch(55% 0.18 25)" : "var(--ink)" }}>
                {timeLeft}s
              </strong>
            </span>
          </div>
          <div style={{
            padding: "8px 14px",
            background: "var(--surface)", border: "1px solid var(--line)",
            borderRadius: 999, fontSize: 13, color: "var(--ink-2)",
            display: "inline-flex", alignItems: "center", gap: 8,
            fontVariantNumeric: "tabular-nums",
          }}>
            <Icon name="sparkle" size={14} style={{ color: "var(--accent)" }}/>
            <span>Score : <strong style={{ fontWeight: 660, color: "var(--accent)" }}>{score}</strong></span>
          </div>
          {phase !== "playing" && (
            <button onClick={start}
              className="btn btn-accent"
              style={{ height: 38, fontSize: 13.5 }}>
              {phase === "idle" ? "▶ Lancer le jeu" : "🔁 Rejouer"}
            </button>
          )}
        </div>

        {/* Terrain de jeu : fond doux, hauteur fixe pour ne pas sauter
            entre les phases, position relative pour les chips absolute. */}
        <div ref={fieldRef} style={{
          position: "relative",
          marginTop: 22,
          height: 360,
          background: "linear-gradient(180deg, var(--accent-soft) 0%, var(--bg-alt) 100%)",
          border: "1px solid var(--accent-soft-2)",
          borderRadius: 18,
          overflow: "hidden",
          cursor: phase === "playing" ? "crosshair" : "default",
        }}>
          {phase === "idle" && (
            <div style={{
              position: "absolute", inset: 0,
              display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
              gap: 10,
            }}>
              {/* 🎯 qui respire doucement pour signaler que la zone est vivante */}
              <div style={{
                fontSize: 64,
                animation: "cb404IdleBreath 2.4s ease-in-out infinite",
                filter: "drop-shadow(0 6px 14px color-mix(in oklab, var(--accent) 30%, transparent))",
              }}>🎯</div>
              <div style={{ fontSize: 14, color: "var(--ink-3)" }}>
                Prêt·e ? Cliquez sur « Lancer le jeu » pour commencer.
              </div>
            </div>
          )}
          {phase === "done" && (
            <div style={{
              position: "absolute", inset: 0,
              display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
              gap: 8, padding: 24, textAlign: "center",
            }}>
              {/* Emoji du verdict en bounce in spring + glow doux */}
              <div style={{
                fontSize: 56,
                animation: "cb404VerdictBounce .65s cubic-bezier(.34, 1.56, .64, 1) both",
                filter: "drop-shadow(0 8px 18px color-mix(in oklab, var(--accent) 35%, transparent))",
              }}>{verdict.emoji}</div>
              <div style={{
                fontFamily: "var(--ff-display)", fontSize: 24, fontWeight: 580,
                letterSpacing: "-0.025em", color: "var(--ink)",
                animation: "cb404DoneIn .45s cubic-bezier(.22,1,.36,1) .15s both",
              }}>
                {score} RDV en 20 secondes
              </div>
              <div style={{
                fontSize: 14, color: "var(--accent-ink)", fontWeight: 540,
                animation: "cb404DoneIn .45s cubic-bezier(.22,1,.36,1) .25s both",
              }}>
                {verdict.title}
              </div>
              <div style={{
                marginTop: 4, maxWidth: 380, fontSize: 13, color: "var(--ink-3)",
                lineHeight: 1.5,
                animation: "cb404DoneIn .45s cubic-bezier(.22,1,.36,1) .35s both",
              }}>
                {verdict.sub}
              </div>
            </div>
          )}
          {phase === "playing" && targets.map(t => (
            <button key={t.id}
              onClick={() => catchOne(t.id)}
              className="cb404-target"
              style={{
                position: "absolute",
                left: `${t.x}%`, top: `${t.y}%`,
                padding: "8px 12px 8px 10px",
                background: "linear-gradient(135deg, var(--accent) 0%, oklch(45% 0.22 288) 100%)",
                color: "#fff", border: "none", borderRadius: 999,
                fontSize: 13, fontWeight: 600,
                display: "inline-flex", alignItems: "center", gap: 6,
                cursor: "pointer", fontFamily: "inherit",
                boxShadow: "0 8px 20px -8px var(--accent)",
                // Pop-in spring puis fade-out fluide. Le translate(-50%, -50%)
                // est appliqué dans l'anim elle-même pour rester cohérent.
                animation: `cb404PopIn .28s cubic-bezier(.34, 1.56, .64, 1) both, cb404PopOut ${t.dur}ms cubic-bezier(.4, 0, .6, 1) forwards`,
              }}>
              <span aria-hidden style={{
                width: 18, height: 18, borderRadius: 50,
                background: "rgba(255,255,255,0.25)",
                display: "inline-flex", alignItems: "center", justifyContent: "center",
              }}>
                <Icon name="calendar" size={11}/>
              </span>
              RDV
            </button>
          ))}
        </div>

        <div style={{
          marginTop: 28, display: "flex", justifyContent: "center", gap: 10, flexWrap: "wrap",
        }}>
          <a href="/" onClick={e => { e.preventDefault(); window.location.href = "/"; }}
            className="btn btn-accent btn-lg">
            ← Retour à l'accueil
          </a>
          <a href="/blog" onClick={e => { e.preventDefault(); window.location.href = "/blog"; }}
            className="btn btn-ghost btn-lg">
            Lire le blog
          </a>
        </div>
      </div>

      <style>{`
        @keyframes cb404PopIn {
          0%   { opacity: 0; transform: translate(-50%, -50%) scale(0.4); }
          60%  { opacity: 1; transform: translate(-50%, -50%) scale(1.12); }
          100% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
        }
        @keyframes cb404PopOut {
          0%, 65% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
          85%     { opacity: 0.6; transform: translate(-50%, -50%) scale(0.92); }
          100%    { opacity: 0; transform: translate(-50%, -50%) scale(0.6) rotate(-8deg); }
        }
        @keyframes cb404DoneIn {
          from { opacity: 0; transform: translateY(6px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        @keyframes cb404VerdictBounce {
          0%   { opacity: 0; transform: scale(0.3) rotate(-8deg); }
          70%  { opacity: 1; transform: scale(1.15) rotate(4deg); }
          100% { opacity: 1; transform: scale(1) rotate(0); }
        }
        @keyframes cb404IdleBreath {
          0%, 100% { transform: scale(1) rotate(0); opacity: 0.95; }
          50%      { transform: scale(1.08) rotate(-3deg); opacity: 1; }
        }
        .cb404-target:hover {
          filter: brightness(1.12);
        }
      `}</style>
    </section>
  );
};

const NotFoundPage = () => <NotFoundGame/>;

if (typeof window !== "undefined") {
  window.NotFoundPage = NotFoundPage;
}
