/**
 * Salle d'attente multijoueur — v2 optimisée
 * - Bouton Prêt : debounce + feedback visuel clair + protection double-clic
 * - Layout PC/mobile optimisé sans duplication
 * - Animations fluides et intuitives
 */
import { useEffect, useState, useRef, useCallback, useMemo } from "react";
import { motion, AnimatePresence } from "motion/react";
import { useLocation } from "wouter";
import { Home, Copy, Check, Users, X, Loader2, Wifi, WifiOff } from "lucide-react";
import { getSession, toggleReady, startGame, leaveSession, mpStorage, type Session } from "@/game/utils/sessionApi";
import { PoliceTape } from "@/game/ui/PoliceUI";
import ticketImg from "@/game/utils/ticketImg";
import { QRCodeSVG } from "qrcode.react";
import { trpc } from "@/lib/trpc";
import { getAvatarDisplay } from "@/game/utils/avatarConfig";
import { BadgeVisual } from "@/components/BadgeVisuals";

const FONT_BANGERS: React.CSSProperties = { fontFamily: "'Bangers', cursive" };
const FONT_FREDOKA: React.CSSProperties = { fontFamily: "'Fredoka One', cursive" };

const POLL_INTERVAL = 2000;

export function LobbyScreen() {
  const [, navigate] = useLocation();
  const { code, playerId, playerName, isHost, guestEmoji: localGuestEmoji } = mpStorage.load();

  const [session, setSession] = useState<Session | null>(null);
  const [error, setError] = useState("");
  const [copied, setCopied] = useState(false);
  const [starting, setStarting] = useState(false);
  const [togglingReady, setTogglingReady] = useState(false);
  const [showConfirmLeave, setShowConfirmLeave] = useState(false);
  const [showConfirmCancel, setShowConfirmCancel] = useState(false);
  const [connected, setConnected] = useState(true);

  const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
  const navigatedRef = useRef(false);
  const readyClickedRef = useRef(false); // protection double-clic au niveau ref
  // Compteur de retries réseau — protège contre les faux positifs transitoires
  const sessionNotFoundCount = useRef<number>(0);

  // ── Redirection si pas de session en mémoire ────────────────
  useEffect(() => {
    if (!code || !playerId) {
      navigate("/");
    }
  }, []);

  // ── Polling ─────────────────────────────────────────────────
  const fetchSession = useCallback(async () => {
    if (!code) return;
    try {
      const { session: s } = await getSession(code);
      setSession(s);
      setError("");
      setConnected(true);
      sessionNotFoundCount.current = 0;

      if (s.state === "playing" && !navigatedRef.current) {
        navigatedRef.current = true;
        navigate("/multiplayer");
      }
      if (s.state === "finished") {
        navigate("/");
      }
    } catch (e: any) {
      if (e.message?.includes("introuvable") || e.message?.includes("expirée")) {
        // Protection : attendre 3 erreurs consécutives avant de naviguer
        sessionNotFoundCount.current += 1;
        if (sessionNotFoundCount.current >= 3) {
          mpStorage.clear();
          navigate("/");
        } else {
          setConnected(false);
          setError("Connexion instable, nouvelle tentative…");
        }
      } else {
        setConnected(false);
        setError("Connexion perdue, nouvelle tentative…");
      }
    }
  }, [code, navigate]);

  useEffect(() => {
    fetchSession();
    pollRef.current = setInterval(fetchSession, POLL_INTERVAL);
    return () => {
      if (pollRef.current) clearInterval(pollRef.current);
    };
  }, [fetchSession]);

  // ── Copier le code ───────────────────────────────────────────
  const copyCode = () => {
    if (navigator.clipboard?.writeText) {
      navigator.clipboard.writeText(code).then(() => {
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      }).catch(() => fallbackCopy(code));
    } else {
      fallbackCopy(code);
    }
  };

  const fallbackCopy = (text: string) => {
    const ta = document.createElement("textarea");
    ta.value = text;
    ta.style.cssText = "position:fixed;top:0;left:0;opacity:0;";
    document.body.appendChild(ta);
    ta.focus();
    ta.select();
    try {
      document.execCommand("copy");
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch { /* impossible */ }
    document.body.removeChild(ta);
  };

  // ── Prêt — protection double-clic robuste ───────────────────
  const handleReady = async () => {
    if (togglingReady || isHost || amReady || readyClickedRef.current) return;
    readyClickedRef.current = true;
    setTogglingReady(true);
    try {
      const { session: s } = await toggleReady(code, playerId);
      setSession(s);
    } catch (e: any) {
      setError(e.message || "Erreur réseau, réessayez.");
      readyClickedRef.current = false; // permettre de réessayer si erreur
    } finally {
      setTogglingReady(false);
    }
  };

  // ── Démarrer ─────────────────────────────────────────────────
  const handleStart = async () => {
    if (starting || !session) return;
    setStarting(true);
    try {
      const { session: s } = await startGame(code, playerId);
      setSession(s);
      navigate("/multiplayer");
    } catch (e: any) {
      setError(e.message);
      setStarting(false);
    }
  };

  // ── Quitter ───────────────────────────────────────────────────
  const handleLeave = async () => {
    try {
      await leaveSession(code, playerId);
    } catch {}
    mpStorage.clear();
    navigate("/");
  };

  // ── Récupérer les profils (avatar + badge) des joueurs par leur nom ──
  // IMPORTANT: ces hooks DOIVENT être avant tout return conditionnel (règles des hooks React)
  const playerNamesKey = session?.players.map((p) => p.name).join(",") ?? "";
  const playerNames = useMemo(
    () => session?.players.map((p) => p.name) ?? [],
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [playerNamesKey]
  );
  const { data: playerProfiles, refetch: refetchProfiles } = trpc.gameAuth.getPlayerProfiles.useQuery(
    { playerNames },
    { enabled: playerNames.length > 0, staleTime: 0, refetchOnWindowFocus: false }
  );

  // Forcer le rechargement des profils quand la liste des joueurs change
  useEffect(() => {
    if (playerNames.length > 0) {
      refetchProfiles();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [playerNamesKey]);

  // ── Emojis des joueurs invités (sans compte) ──
  // refetchInterval: 3000 (au lieu de 2000ms) : dans le lobby, les emojis sont enregistrés
  // à l'arrivée et changent rarement. Le refetch sur changement de liste compense.
  const { data: guestEmojis, refetch: refetchGuestEmojis } = trpc.guestAvatar.getEmojis.useQuery(
    { sessionCode: code },
    { enabled: !!code, staleTime: 0, refetchOnWindowFocus: true, refetchInterval: 3000 }
  );
  // Rafraîchir immédiatement quand la liste des joueurs change
  useEffect(() => {
    if (code) refetchGuestEmojis();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [playerNamesKey]);

  // ── Écran de chargement ───────────────────────────────────────
  if (!session) {
    return (
      <div
        className="h-[100dvh] max-w-md md:max-w-lg lg:max-w-xl mx-auto flex flex-col items-center justify-center gap-4 overflow-hidden"
        style={{ background: "linear-gradient(160deg, #0c1a4e 0%, #1a083d 60%, #0c1a4e 100%)" }}
      >
        <motion.div
          animate={{ opacity: [0.4, 1, 0.4], scale: [0.95, 1.05, 0.95] }}
          transition={{ duration: 1.4, repeat: Infinity }}
        >
          <img src={ticketImg} alt="" style={{ width: "4rem" }} />
        </motion.div>
        <span style={FONT_FREDOKA} className="text-yellow-400/70 text-sm">
          Connexion au lobby…
        </span>
        {error && (
          <span style={FONT_FREDOKA} className="text-red-400 text-xs text-center px-6">
            {error}
          </span>
        )}
      </div>
    );
  }

  const allReady = session.players.every((p) => p.ready);
  const canStart = allReady && session.players.length >= 2;
  const myPlayer = session.players.find((p) => p.id === playerId);
  const amReady = myPlayer?.ready ?? false;

  // ── Composant carte joueur ────────────────────────────────────
  const PlayerCard = ({ player, size = "md" }: { player: Session["players"][0]; size?: "sm" | "md" }) => {
    const profile = playerProfiles?.[player.name];
    const avatarDisplay = profile ? getAvatarDisplay(profile.avatarType as "emoji" | "custom", profile.avatarId) : null;
    // Emoji depuis le serveur (tous les joueurs) ou fallback local immédiat (joueur local uniquement)
    const serverEmoji = (guestEmojis as Record<string, string> | undefined)?.[player.id];
    const guestEmojiForPlayer = !avatarDisplay
      ? (serverEmoji || (player.id === playerId ? localGuestEmoji : null))
      : null;
    const avatarSize = size === "md" ? "w-9 h-9" : "w-7 h-7";
    const avatarFontSize = size === "md" ? "1.35rem" : "1.1rem";
    return (
    <motion.div
      key={player.id}
      layout
      initial={{ x: -20, opacity: 0 }}
      animate={{ x: 0, opacity: 1 }}
      exit={{ x: 20, opacity: 0 }}
      transition={{ type: "spring", stiffness: 300, damping: 25 }}
      className={`flex items-center justify-between rounded-xl border-[3px] border-black ${
        size === "md" ? "px-4 py-3" : "px-3 py-2"
      } ${player.id === playerId ? "ring-2 ring-yellow-400 ring-offset-1 ring-offset-transparent" : ""} w-full`}
      style={{
        background: player.ready
          ? "rgba(34,197,94,0.18)"
          : "rgba(255,255,255,0.06)",
        boxShadow: player.ready ? "3px 3px 0px #16a34a" : "3px 3px 0px #000",
        transition: "background 0.3s ease, box-shadow 0.3s ease",
      }}
    >
      <div className="flex items-center gap-2 min-w-0">
        {/* Avatar du joueur */}
        <div
          className={`${avatarSize} rounded-full border-2 border-black/40 flex-shrink-0 overflow-hidden`}
          style={{
            background: "rgba(0,0,0,0.3)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          {avatarDisplay?.type === "emoji" ? (
            <span style={{ fontSize: avatarFontSize, lineHeight: 1, display: "block", textAlign: "center" }}>{avatarDisplay.content}</span>
          ) : avatarDisplay?.type === "image" ? (
            <img src={avatarDisplay.content} alt="" className="w-full h-full object-cover" />
          ) : guestEmojiForPlayer ? (
            <span style={{ fontSize: avatarFontSize, lineHeight: 1, display: "block", textAlign: "center" }}>{guestEmojiForPlayer}</span>
          ) : (
            // Joueur invité sans compte et sans emoji : première lettre du nom
            <span style={{ fontFamily: "'Bangers', cursive", fontSize: avatarFontSize, lineHeight: 1, color: "#fff", display: "block", textAlign: "center" }}>
              {(player.name?.[0] ?? "?").toUpperCase()}
            </span>
          )}
        </div>

        <div className="flex flex-col min-w-0">
          <span
            style={{ ...FONT_FREDOKA, fontSize: size === "md" ? "1rem" : "0.875rem" }}
            className="text-white font-medium truncate"
          >
            {player.name}
            {player.id === playerId && (
              <span className="text-yellow-400/60 text-xs ml-1">(vous)</span>
            )}
          </span>
          {/* Badge équipé */}
          {profile?.equippedBadgeId && (
            <div className={`${size === "md" ? "w-5 h-5" : "w-4 h-4"} mt-0.5`}>
              <BadgeVisual badgeId={profile.equippedBadgeId} animate={false} />
            </div>
          )}
        </div>
      </div>
      <div className="flex-shrink-0 ml-2">
        <AnimatePresence mode="wait">
          {player.id === session.hostId ? (
            <motion.span
              key="host"
              initial={{ scale: 0.8, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              style={FONT_FREDOKA}
              className={`text-yellow-400 bg-yellow-400/10 px-2 py-0.5 rounded-full border border-yellow-400/30 flex items-center gap-1 ${size === "md" ? "text-sm" : "text-xs"}`}
            >
              <Check className="w-3 h-3" /> Host
            </motion.span>
          ) : player.ready ? (
            <motion.span
              key="ready"
              initial={{ scale: 0.5, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              transition={{ type: "spring", stiffness: 400, damping: 15 }}
              style={FONT_FREDOKA}
              className={`text-green-400 bg-green-400/10 px-2 py-0.5 rounded-full border border-green-400/30 flex items-center gap-1 ${size === "md" ? "text-sm" : "text-xs"}`}
            >
              <Check className="w-3 h-3" /> Prêt
            </motion.span>
          ) : (
            <motion.span
              key="waiting"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              style={FONT_FREDOKA}
              className={`text-white/40 bg-white/5 px-2 py-0.5 rounded-full border border-white/10 ${size === "md" ? "text-sm" : "text-xs"}`}
            >
              En attente…
            </motion.span>
          )}
        </AnimatePresence>
      </div>
    </motion.div>
    );
  };

  return (
    <div
      className="h-[100dvh] w-screen flex flex-col overflow-hidden"
      style={{ background: "linear-gradient(160deg, #0c1a4e 0%, #1a083d 60%, #0c1a4e 100%)" }}
    >
      {/* ── Header ── */}
      <div className="w-full bg-[#111] border-b-4 border-yellow-400 flex items-center px-4 py-3 z-10 flex-shrink-0">
        <div className="flex-1 flex items-center justify-center gap-3">
          <span style={{ ...FONT_BANGERS, fontSize: "1.3rem", letterSpacing: "0.08em" }} className="text-yellow-400">
            SALLE D'ATTENTE
          </span>
          {/* Indicateur connexion */}
          <motion.div
            animate={{ opacity: connected ? 1 : [0.3, 1, 0.3] }}
            transition={{ duration: connected ? 0 : 1.2, repeat: connected ? 0 : Infinity }}
          >
            {connected
              ? <Wifi className="w-4 h-4 text-green-400/60" />
              : <WifiOff className="w-4 h-4 text-red-400" />
            }
          </motion.div>
        </div>
      </div>

      <PoliceTape />

      {/* ── Layout principal ── */}
      <div className="flex-1 overflow-hidden flex flex-col md:flex-row w-full mx-auto">

        {/* ══ COLONNE GAUCHE : code + QR + joueurs (mobile) ══ */}
        <div className="w-full md:w-[360px] lg:w-[400px] md:flex-shrink-0 flex flex-col overflow-hidden px-2.5 sm:px-3 md:px-4 py-2 sm:py-3 gap-2 sm:gap-3 md:border-r-4 md:border-yellow-400/20">

          {/* ── Code de session ── */}
          <motion.div
            initial={{ scale: 0.9, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            className="bg-yellow-400 border-[3px] sm:border-[4px] border-black rounded-xl sm:rounded-2xl p-3 w-full"
            style={{ boxShadow: "3px 3px 0px #000" }}
          >
            {/* Layout horizontal : code à gauche, QR à droite */}
            <div className="flex items-center gap-3">
              {/* Gauche : label + code + bouton copier */}
              <div className="flex-1 flex flex-col items-start justify-center min-w-0">
                <div style={FONT_FREDOKA} className="text-black/60 text-[10px] uppercase tracking-widest mb-0.5">
                  Code de la partie
                </div>
                <div
                  style={{ ...FONT_BANGERS, fontSize: "clamp(2.2rem, 8vw, 3.2rem)", letterSpacing: "0.22em", lineHeight: 1 }}
                  className="text-black select-all break-all"
                >
                  {code}
                </div>
                {/* Bouton Copier */}
                <motion.button
                  whileTap={{ scale: 0.9 }}
                  onClick={copyCode}
                  className="mt-2 flex items-center gap-1.5 bg-black/15 rounded-lg px-3 py-1.5 border border-black/20 active:bg-black/25 transition-colors"
                >
                  <AnimatePresence mode="wait">
                    {copied
                      ? <motion.div key="check" initial={{ scale: 0 }} animate={{ scale: 1 }}><Check className="w-4 h-4 text-black" /></motion.div>
                      : <motion.div key="copy" initial={{ scale: 0 }} animate={{ scale: 1 }}><Copy className="w-4 h-4 text-black" /></motion.div>
                    }
                  </AnimatePresence>
                  <span style={{ ...FONT_FREDOKA, fontSize: "0.85rem" }} className="text-black">
                    {copied ? "Copié !" : "Copier le code"}
                  </span>
                </motion.button>
              </div>
              {/* Droite : QR code + label */}
              <div className="flex flex-col items-center gap-1 flex-shrink-0">
                <div className="bg-white rounded-xl p-2 border-[3px] border-black" style={{ boxShadow: "3px 3px 0px #000" }}>
                  <QRCodeSVG
                    value={`${window.location.origin}/?join=${code}`}
                    size={110}
                    bgColor="#ffffff"
                    fgColor="#000000"
                    level="M"
                  />
                </div>
                <div style={FONT_FREDOKA} className="text-black/50 text-[10px]">
                  Scanner pour rejoindre
                </div>
              </div>
            </div>
          </motion.div>

          {/* ── Liste joueurs (mobile uniquement) ── */}
          <div className="md:hidden flex-1 flex flex-col gap-2 overflow-y-auto min-h-0">
            <div className="flex items-center gap-2 px-1 flex-shrink-0">
              <Users className="w-4 h-4 text-yellow-400/70" />
              <span style={FONT_FREDOKA} className="text-yellow-400/70 text-sm">
                Joueurs ({session.players.length}/10)
              </span>
            </div>
            <AnimatePresence>
              {session.players.map((player) => (
                <div key={player.id} className="flex-shrink-0">
                  <PlayerCard player={player} size="sm" />
                </div>
              ))}
            </AnimatePresence>
            {session.players.length < 2 && (
              <div style={FONT_FREDOKA} className="text-center text-white/40 text-sm px-4 py-2 flex-shrink-0">
                En attente d'un autre joueur…
              </div>
            )}
          </div>

          {/* ── Erreur ── */}
          <AnimatePresence>
            {error && (
              <motion.div
                initial={{ opacity: 0, y: -8 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -8 }}
                style={{ ...FONT_FREDOKA, background: "#FF3B30" }}
                className="text-white text-sm text-center px-3 py-2 rounded-xl border-[2px] border-black flex-shrink-0"
              >
                {error}
              </motion.div>
            )}
          </AnimatePresence>

          {/* ── Boutons d'action (mobile) ── */}
          <div className="md:hidden flex flex-col gap-2 pb-2 px-0 flex-shrink-0">
            {isHost ? (
              <>
                <ReadyButton
                  canStart={canStart}
                  starting={starting}
                  playerCount={session.players.length}
                  onClick={handleStart}
                  size="lg"
                />
                <motion.button
                  whileTap={{ scale: 0.94 }}
                  onClick={() => setShowConfirmCancel(true)}
                  className="w-full py-2.5 sm:py-3 bg-red-900/20 border-[3px] border-red-500/40 rounded-xl sm:rounded-2xl text-red-400/80 flex items-center justify-center gap-2 text-sm sm:text-base"
                  style={FONT_FREDOKA}
                >
                  <X className="w-4 h-4" />
                  Quitter la partie
                </motion.button>
              </>
            ) : (
              <>
                <GuestReadyButton
                  amReady={amReady}
                  togglingReady={togglingReady}
                  onClick={handleReady}
                  size="lg"
                />
                <motion.button
                  whileTap={{ scale: 0.94 }}
                  onClick={() => setShowConfirmLeave(true)}
                  className="w-full py-2.5 sm:py-3 bg-transparent border-[3px] border-white/20 rounded-xl sm:rounded-2xl text-white/50 flex items-center justify-center gap-2 text-sm sm:text-base"
                  style={FONT_FREDOKA}
                >
                  <Home className="w-4 h-4" />
                  Quitter la partie
                </motion.button>
              </>
            )}
          </div>

        </div>{/* /colonne gauche */}

        {/* ══ COLONNE DROITE : joueurs + boutons (PC uniquement) ══ */}
        <div className="hidden md:flex flex-col flex-1 overflow-hidden px-5 py-4 gap-3">

          {/* Titre */}
          <div className="flex items-center gap-2 flex-shrink-0">
            <Users className="w-5 h-5 text-yellow-400/70" />
            <span style={{ ...FONT_BANGERS, fontSize: "1.1rem", letterSpacing: "0.08em" }} className="text-yellow-400/70">
              JOUEURS ({session.players.length}/10)
            </span>
            {/* Barre de progression */}
            <div className="flex-1 h-1.5 bg-white/10 rounded-full overflow-hidden ml-2">
              <motion.div
                className="h-full bg-yellow-400/60 rounded-full"
                animate={{ width: `${(session.players.length / 10) * 100}%` }}
                transition={{ type: "spring", stiffness: 200 }}
              />
            </div>
          </div>

          {/* Liste joueurs scrollable */}
          <div className="flex-1 flex flex-col gap-2 overflow-y-auto min-h-0">
            <AnimatePresence>
              {session.players.map((player) => (
                <div key={player.id} className="flex-shrink-0">
                  <PlayerCard player={player} size="md" />
                </div>
              ))}
            </AnimatePresence>
            {session.players.length < 2 && (
              <motion.div
                animate={{ opacity: [0.5, 1, 0.5] }}
                transition={{ duration: 2, repeat: Infinity }}
                style={FONT_FREDOKA}
                className="text-center text-white/40 text-sm px-4 py-3 border border-white/10 rounded-xl flex-shrink-0"
              >
                En attente d'un autre joueur pour commencer…
              </motion.div>
            )}
          </div>

          {/* Boutons PC */}
          <div className="flex flex-col gap-2 flex-shrink-0">
          {isHost ? (
            <>
              <ReadyButton
                canStart={canStart}
                starting={starting}
                playerCount={session.players.length}
                onClick={handleStart}
                size="xl"
              />
              <motion.button
                whileTap={{ scale: 0.94 }}
                onClick={() => setShowConfirmCancel(true)}
                className="w-full py-3 bg-transparent border-[3px] border-red-500/25 rounded-2xl text-red-400/50 flex items-center justify-center gap-2 hover:border-red-500/50 hover:text-red-400/80 transition-all"
                style={FONT_FREDOKA}
              >
                <X className="w-4 h-4" />
                Annuler la création de partie
              </motion.button>
            </>
          ) : (
            <>
              <GuestReadyButton
                amReady={amReady}
                togglingReady={togglingReady}
                onClick={handleReady}
                size="xl"
              />
              <motion.button
                whileTap={{ scale: 0.94 }}
                onClick={() => setShowConfirmLeave(true)}
                className="w-full py-3 bg-transparent border-[3px] border-white/15 rounded-2xl text-white/40 flex items-center justify-center gap-2 hover:border-white/30 hover:text-white/60 transition-all"
                style={FONT_FREDOKA}
              >
                <Home className="w-4 h-4" />
                Quitter la partie
              </motion.button>
            </>
          )}
          </div>

        </div>{/* /colonne droite */}

      </div>{/* /layout */}

      {/* Footer */}
      <div
        className="w-full bg-[#111] py-1 text-center flex-shrink-0"
        style={{ paddingBottom: "calc(0.25rem + env(safe-area-inset-bottom, 0px))" }}
      >
        <span style={FONT_FREDOKA} className="text-yellow-400/50 text-[0.65rem] tracking-widest">
          © TICKET CRICKET 2026
        </span>
      </div>

      {/* ── Modal ANNULER CRÉATION (host) ── */}
      <AnimatePresence>
        {showConfirmCancel && (
          <ConfirmModal
            title="Annuler la partie ?"
            message="Tous les joueurs seront renvoyés à l'accueil."
            confirmLabel="Oui, annuler"
            confirmColor="#FF3B30"
            onConfirm={handleLeave}
            onCancel={() => setShowConfirmCancel(false)}
          />
        )}
      </AnimatePresence>

      {/* ── Modal QUITTER (invité) ── */}
      <AnimatePresence>
        {showConfirmLeave && (
          <ConfirmModal
            title="Quitter la partie ?"
            message="Vous quitterez la salle d'attente."
            confirmLabel="Oui, quitter"
            confirmColor="#FF3B30"
            onConfirm={handleLeave}
            onCancel={() => setShowConfirmLeave(false)}
          />
        )}
      </AnimatePresence>

    </div>
  );
}

// ── Bouton COMMENCER (host) ──────────────────────────────────────
function ReadyButton({
  canStart,
  starting,
  playerCount,
  onClick,
  size,
}: {
  canStart: boolean;
  starting: boolean;
  playerCount: number;
  onClick: () => void;
  size: "lg" | "xl";
}) {
  const FONT_BANGERS: React.CSSProperties = { fontFamily: "'Bangers', cursive" };
  const py = size === "xl" ? "py-5" : "py-4";
  const fs = size === "xl" ? "1.6rem" : "1.45rem";

  return (
    <motion.button
      whileHover={canStart ? { scale: 1.03, y: -2 } as any : {}}
      whileTap={canStart ? { scale: 0.97 } as any : {}}
      onClick={onClick}
      disabled={!canStart || starting}
      className={`w-full ${py} border-[5px] border-black rounded-2xl text-black relative overflow-hidden transition-all duration-300 ${
        canStart ? "bg-yellow-400 cursor-pointer" : "bg-yellow-400/30 cursor-not-allowed"
      }`}
      style={{
        ...FONT_BANGERS,
        fontSize: fs,
        letterSpacing: "0.08em",
        boxShadow: canStart ? "6px 6px 0px #000" : "3px 3px 0px #000",
      }}
    >
      {canStart && !starting && (
        <motion.div
          className="absolute inset-0 w-1/3 bg-white/20 skew-x-[-20deg] pointer-events-none"
          animate={{ x: ["-100%", "400%"] }}
          transition={{ duration: 2, repeat: Infinity, ease: "easeInOut", repeatDelay: 0.6 }}
        />
      )}
      {starting ? (
        <span className="flex items-center justify-center gap-2">
          <Loader2 className="w-5 h-5 animate-spin" /> DÉMARRAGE…
        </span>
      ) : canStart ? (
        "COMMENCER LE JEU"
      ) : playerCount < 2 ? (
        "ATTENTE DE JOUEURS"
      ) : (
        "ATTENTE DES JOUEURS"
      )}
    </motion.button>
  );
}

// ── Bouton PRÊT (invité) ─────────────────────────────────────────
function GuestReadyButton({
  amReady,
  togglingReady,
  onClick,
  size,
}: {
  amReady: boolean;
  togglingReady: boolean;
  onClick: () => void;
  size: "lg" | "xl";
}) {
  const FONT_BANGERS: React.CSSProperties = { fontFamily: "'Bangers', cursive" };
  const py = size === "xl" ? "py-5" : "py-4";
  const fs = size === "xl" ? "1.6rem" : "1.45rem";

  return (
    <motion.button
      whileHover={!amReady && !togglingReady ? { scale: 1.03, y: -2 } as any : {}}
      whileTap={!amReady && !togglingReady ? { scale: 0.97 } as any : {}}
      onClick={onClick}
      disabled={togglingReady || amReady}
      className={`w-full ${py} border-[5px] border-black rounded-2xl text-white relative overflow-hidden transition-all duration-300`}
      style={{
        ...FONT_BANGERS,
        fontSize: fs,
        letterSpacing: "0.08em",
        background: amReady
          ? "linear-gradient(135deg, #16a34a, #22c55e)"
          : togglingReady
          ? "linear-gradient(135deg, #1565C0aa, #1976D2aa)"
          : "linear-gradient(135deg, #1565C0, #1976D2)",
        boxShadow: amReady ? "4px 4px 0px #15803d" : "6px 6px 0px #000",
        cursor: amReady ? "default" : togglingReady ? "wait" : "pointer",
        opacity: togglingReady ? 0.85 : 1,
      }}
    >
      {/* Shimmer uniquement si pas prêt et pas en chargement */}
      {!amReady && !togglingReady && (
        <motion.div
          className="absolute inset-0 w-1/3 bg-white/20 skew-x-[-20deg] pointer-events-none"
          animate={{ x: ["-100%", "400%"] }}
          transition={{ duration: 2, repeat: Infinity, ease: "easeInOut", repeatDelay: 0.8 }}
        />
      )}
      <AnimatePresence mode="wait">
        {amReady ? (
          <motion.span
            key="ready"
            initial={{ scale: 0.5, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            transition={{ type: "spring", stiffness: 400, damping: 15 }}
            className="flex items-center justify-center gap-2"
          >
            <Check className="w-6 h-6" /> JE SUIS PRÊT !
          </motion.span>
        ) : togglingReady ? (
          <motion.span
            key="loading"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="flex items-center justify-center gap-2"
          >
            <Loader2 className="w-5 h-5 animate-spin" /> CONFIRMATION…
          </motion.span>
        ) : (
          <motion.span key="idle" initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
            PRÊT ?
          </motion.span>
        )}
      </AnimatePresence>
    </motion.button>
  );
}

// ── Modal de confirmation générique ─────────────────────────────
function ConfirmModal({
  title,
  message,
  confirmLabel,
  confirmColor,
  onConfirm,
  onCancel,
}: {
  title: string;
  message: string;
  confirmLabel: string;
  confirmColor: string;
  onConfirm: () => void;
  onCancel: () => void;
}) {
  const FONT_BANGERS: React.CSSProperties = { fontFamily: "'Bangers', cursive" };
  const FONT_FREDOKA: React.CSSProperties = { fontFamily: "'Fredoka One', cursive" };

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      style={{ background: "rgba(0,0,0,0.75)", backdropFilter: "blur(4px)" }}
      onClick={onCancel}
    >
      <motion.div
        initial={{ scale: 0.85, opacity: 0, y: 20 }}
        animate={{ scale: 1, opacity: 1, y: 0 }}
        exit={{ scale: 0.85, opacity: 0, y: 20 }}
        transition={{ type: "spring", stiffness: 300, damping: 25 }}
        className="bg-[#1a1a2e] border-[4px] border-black rounded-2xl p-6 w-full max-w-sm"
        style={{ boxShadow: "8px 8px 0px #000" }}
        onClick={(e) => e.stopPropagation()}
      >
        <h3
          style={{ ...FONT_BANGERS, fontSize: "1.5rem", letterSpacing: "0.06em" }}
          className="text-white text-center mb-2"
        >
          {title}
        </h3>
        <p style={FONT_FREDOKA} className="text-white/60 text-center text-sm mb-5">
          {message}
        </p>
        <div className="flex gap-3">
          <motion.button
            whileTap={{ scale: 0.95 }}
            onClick={onCancel}
            className="flex-1 py-3 bg-white/10 border-[3px] border-white/20 rounded-xl text-white/70"
            style={FONT_FREDOKA}
          >
            Annuler
          </motion.button>
          <motion.button
            whileTap={{ scale: 0.95 }}
            onClick={onConfirm}
            className="flex-1 py-3 border-[3px] border-black rounded-xl text-white font-bold"
            style={{ ...FONT_FREDOKA, background: confirmColor, boxShadow: "3px 3px 0px #000" }}
          >
            {confirmLabel}
          </motion.button>
        </div>
      </motion.div>
    </motion.div>
  );
}

export default LobbyScreen;
