/* eslint-disable */
/* Final screen — winner ceremony + share + play again */

function FinalScreen({ onNavigate, roomId }) {
  const me = window.GameStore.getMe();
  const [room, setRoom] = useState(window.RoomOps.getRoom(roomId));
  const [showConfetti, setShowConfetti] = useState(true);
  const toast = useToast();

  useEffect(() => {
    const unsubscribe = window.RoomOps.subscribe(roomId, r => {
      if (!r) { onNavigate("home"); return; }
      setRoom(r);
      if (r.phase === "lobby") onNavigate(`room/${roomId}`);
    });
    return unsubscribe;
  }, [roomId]);

  useEffect(() => {
    const t = setTimeout(() => setShowConfetti(false), 5000);
    return () => clearTimeout(t);
  }, []);

  if (!room || !room.finalScored) return null;

  const scored = room.finalScored;
  const winner = scored[0];
  const iWon = winner && winner.id === me.id && winner.total > 0;
  const meScored = scored.find(s => s.id === me.id);

  async function playAgain() {
    await window.RoomOps.playAgain(roomId).catch(error => toast(error.message));
  }

  function shareResult() {
    const text = `Игра в слова: ${meScored?.word ? `мое слово «${meScored.word}» (+${meScored.total})` : "сыграл партию"}. Победил${iWon ? " я!" : winner ? `(а): ${winner.name}` : ""} Попробуй и ты: ${location.origin}${location.pathname}`;
    if (navigator.share) {
      navigator.share({ title: "Игра в слова", text }).catch(() => {});
    } else {
      navigator.clipboard.writeText(text);
      toast("Скопировано в буфер!");
    }
  }

  function copyResult() {
    const lines = [`⭐ ИГРА В СЛОВА ⭐`, ""];
    scored.forEach((s, i) => {
      const medal = i === 0 ? "🥇" : i === 1 ? "🥈" : i === 2 ? "🥉" : "  ";
      const duration = s.durationMs != null ? ` за ${formatDuration(s.durationMs)}` : "";
      lines.push(`${medal} ${s.name}: ${s.word || "—"} (+${s.total})${duration}`);
    });
    lines.push("", `Сыграй и ты: ${location.origin}${location.pathname}`);
    navigator.clipboard.writeText(lines.join("\n"));
    toast("Результаты скопированы!");
  }

  async function leaveRoom() {
    if (!confirm("Выйти из комнаты? Она исчезнет из ваших комнат.")) return;
    try {
      await window.RoomOps.leaveRoom(roomId);
      onNavigate("home");
    } catch (error) {
      toast(error.message);
    }
  }

  async function deleteRoom() {
    if (!confirm("Удалить комнату целиком? Игроки, чат и раунды этой комнаты будут удалены.")) return;
    try {
      await window.RoomOps.deleteRoom(roomId);
      onNavigate("home");
    } catch (error) {
      toast(error.message);
    }
  }

  const isHost = room.hostId === me.id;

  return (
    <div className="shell">
      {showConfetti && winner && winner.total > 0 && <Confetti count={120}/>}
      <Topbar onHome={() => onNavigate("home")} />

      {/* Winner block */}
      {winner && winner.total > 0 ? (
        <div className="text-center" style={{ marginBottom: 36, marginTop: 12 }}>
          <div className="label-up" style={{ marginBottom: 12 }}>{iWon ? "Вы победили!" : "Победитель"}</div>
          <div style={{ display: "inline-flex", flexDirection: "column", alignItems: "center" }} className="pop-in">
            <div style={{ position: "relative" }}>
              <Avatar player={winner} size="lg" ring />
              <div style={{
                position: "absolute", top: -16, left: "50%", transform: "translateX(-50%)",
                fontSize: 32, filter: "drop-shadow(0 4px 12px rgba(255,217,61,0.6))",
              }}>👑</div>
            </div>
            <h1 className="display-1" style={{ fontSize: "clamp(36px, 6vw, 64px)", marginTop: 18, marginBottom: 8 }}>{winner.name}</h1>
            <div style={{
              fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 36,
              color: "var(--gold)",
              padding: "8px 28px",
              background: "rgba(255,217,61,0.12)",
              borderRadius: "var(--radius-pill)",
              border: "2px solid rgba(255,217,61,0.4)",
            }}>«{winner.word}» · +{winner.total}{winner.durationMs != null ? ` · ${formatDuration(winner.durationMs)}` : ""}</div>
          </div>
        </div>
      ) : (
        <div className="text-center" style={{ marginBottom: 36, marginTop: 12 }}>
          <h2 className="display-2">Никто не набрал очков</h2>
          <p className="text-muted">Бывает! Попробуем ещё раз?</p>
        </div>
      )}

      {/* Leaderboard for this round */}
      <div className="card-dark" style={{ marginBottom: 20 }}>
        <h3 className="h-section" style={{ marginBottom: 16 }}>Итоги раунда</h3>
        <div className="col" style={{ gap: 10 }}>
          {scored.map((s, i) => (
            <div key={s.id} className="row pop-in" style={{
              gap: 14, padding: "12px 16px",
              background: s.id === me.id ? "rgba(255,217,61,0.08)" : "rgba(255,255,255,0.03)",
              border: `1.5px solid ${s.id === me.id ? "rgba(255,217,61,0.3)" : "rgba(255,255,255,0.08)"}`,
              borderRadius: "var(--radius-md)",
              animationDelay: `${i * 80}ms`,
            }}>
              <div style={{ fontSize: 22, width: 40, textAlign: "center" }}>
                {i === 0 ? "🥇" : i === 1 ? "🥈" : i === 2 ? "🥉" : i + 1}
              </div>
              <Avatar player={s} size="sm"/>
              <div className="grow" style={{ minWidth: 0 }}>
                <div style={{ fontSize: 15, fontWeight: 600 }}>{s.name} {s.isBot && <span className="text-muted">🤖</span>} {s.id === me.id && <span className="text-muted" style={{ fontSize: 12 }}>(вы)</span>}</div>
                <div style={{
                  fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16, marginTop: 2,
                  color: s.accepted ? "var(--gold)" : "var(--ink-on-dark-3)",
                  textDecoration: !s.accepted && s.word ? "line-through" : "none",
                }}>{s.word || "—"}</div>
                {s.durationMs != null && (
                  <div className="text-muted" style={{ fontSize: 11, marginTop: 2 }}>
                    время: {formatDuration(s.durationMs)}
                  </div>
                )}
              </div>
              <div style={{ textAlign: "right" }}>
                <div style={{ fontSize: 22, fontWeight: 800, fontFamily: "var(--font-display)", color: s.total > 0 ? "var(--gold)" : "var(--ink-on-dark-3)" }}>
                  {s.total}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Tournament cumulative scoreboard */}
      {room.tournament && room.tournament.roundsPlayed >= 1 && (() => {
        const totals = room.tournament.totals || {};
        const standings = room.players.map(p => ({
          ...p,
          total: totals[p.id] || 0,
        })).sort((a, b) => b.total - a.total);
        const seriesLeader = standings[0];
        const meTotal = totals[me.id] || 0;
        return (
          <div className="card-dark" style={{ marginBottom: 20, borderColor: "rgba(255,217,61,0.3)", background: "rgba(255,217,61,0.04)" }}>
            <div className="between" style={{ marginBottom: 16 }}>
              <h3 className="h-section">🏆 Турнир в этой комнате</h3>
              <span className="text-muted" style={{ fontSize: 13 }}>раунд {room.tournament.roundsPlayed}</span>
            </div>
            {room.tournament.roundsPlayed > 1 && seriesLeader && seriesLeader.total > 0 && (
              <div className="row" style={{ gap: 12, marginBottom: 16, padding: "12px 16px", background: "rgba(255,217,61,0.1)", borderRadius: 12 }}>
                <Avatar player={seriesLeader} size="sm" ring/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, color: "var(--ink-on-dark-2)" }}>Лидер серии</div>
                  <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18 }}>{seriesLeader.name}</div>
                </div>
                <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 28, color: "var(--gold)" }}>{seriesLeader.total}</div>
              </div>
            )}
            <div className="col" style={{ gap: 8 }}>
              {standings.map((p, i) => (
                <div key={p.id} className="row" style={{
                  gap: 12, padding: "10px 14px",
                  background: p.id === me.id ? "rgba(255,217,61,0.08)" : "rgba(255,255,255,0.03)",
                  border: `1.5px solid ${p.id === me.id ? "rgba(255,217,61,0.25)" : "rgba(255,255,255,0.06)"}`,
                  borderRadius: 12,
                }}>
                  <div style={{ width: 28, textAlign: "center", fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 16, color: i === 0 ? "var(--gold)" : "var(--ink-on-dark-3)" }}>
                    {i + 1}
                  </div>
                  <Avatar player={p} size="sm"/>
                  <div className="grow" style={{ fontSize: 14, fontWeight: 600 }}>
                    {p.name} {p.isBot && <span className="text-muted">🤖</span>} {p.id === me.id && <span className="text-muted" style={{ fontSize: 12 }}>(вы)</span>}
                  </div>
                  <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 20, color: p.total > 0 ? "var(--gold)" : "var(--ink-on-dark-3)", minWidth: 40, textAlign: "right" }}>
                    {p.total}
                  </div>
                </div>
              ))}
            </div>
          </div>
        );
      })()}

      {/* Actions */}
      <div className="row wrap" style={{ gap: 12, justifyContent: "center", marginBottom: 16 }}>
        <button className="btn btn-ghost" onClick={shareResult}>📤 Поделиться</button>
        <button className="btn btn-ghost" onClick={copyResult}>📋 Скопировать</button>
        {isHost && <button className="btn btn-primary btn-lg" onClick={playAgain}>Сыграть ещё раз <StarIcon size={18}/></button>}
        <button className="btn btn-ghost" onClick={isHost ? deleteRoom : leaveRoom}>
          {isHost ? "Удалить комнату" : "Выйти из комнаты"}
        </button>
      </div>
      {!isHost && (
        <div className="text-center text-muted" style={{ fontSize: 13 }}>
          Создатель комнаты решит, играть ли ещё раз.
        </div>
      )}
    </div>
  );
}

// ===== ProfileScreen =====
function ProfileScreen({ onNavigate }) {
  const me = window.GameStore.getMe();
  const [profile, setProfile] = useState(window.ProfileStore.loadProfile ? window.ProfileStore.loadProfile() : null);
  const [displayName, setDisplayName] = useState(me.name || "");
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [friendQuery, setFriendQuery] = useState("");
  const [friendResults, setFriendResults] = useState([]);
  const [messageDrafts, setMessageDrafts] = useState({});
  const [busy, setBusy] = useState(false);
  const toast = useToast();

  useEffect(() => {
    window.ProfileStore.refreshProfile().then(next => {
      setProfile(next);
      if (next?.user?.name) setDisplayName(next.user.name);
    }).catch(error => toast(error.message));
  }, []);

  function phaseText(phase, mode = "classic") {
    if (mode === "async" && phase === "playing") return "Без ожидания";
    if (phase === "playing") return "Идёт раунд";
    if (phase === "results") return "Проверка";
    if (phase === "finished") return "Итоги";
    return "Ожидание";
  }

  function roomTarget(room) {
    if (!room.isMember) return `join/${room.id}`;
    if (room.phase === "playing") return `game/${room.id}`;
    if (room.phase === "results") return `results/${room.id}`;
    if (room.phase === "finished") return `final/${room.id}`;
    return `room/${room.id}`;
  }

  function deviceName(agent) {
    const text = String(agent || "Unknown device");
    if (/iPhone|Android|Mobile/i.test(text)) return "Телефон";
    if (/Macintosh|Mac OS/i.test(text)) return "Mac";
    if (/Windows/i.test(text)) return "Windows";
    if (/Linux/i.test(text)) return "Linux";
    return text.slice(0, 48);
  }

  async function changePassword(e) {
    e.preventDefault();
    setBusy(true);
    try {
      await window.ProfileStore.changePassword({ currentPassword, newPassword });
      setCurrentPassword("");
      setNewPassword("");
      toast("Пароль изменён");
    } catch (error) {
      toast(error.message);
    } finally {
      setBusy(false);
    }
  }

  async function changeName(e) {
    e.preventDefault();
    setBusy(true);
    try {
      const next = await window.ProfileStore.updateName(displayName);
      setNextProfile(next);
      if (next?.user?.name) setDisplayName(next.user.name);
      toast("Имя изменено");
    } catch (error) {
      toast(error.message);
    } finally {
      setBusy(false);
    }
  }

  function setNextProfile(next) {
    if (next) setProfile(next);
  }

  async function searchFriends(e) {
    e && e.preventDefault();
    if (friendQuery.trim().length < 2) {
      toast("Введите минимум 2 символа");
      return;
    }
    try {
      const users = await window.ProfileStore.searchUsers(friendQuery);
      setFriendResults(users);
    } catch (error) {
      toast(error.message);
    }
  }

  async function requestFriend(userId) {
    try {
      setNextProfile(await window.ProfileStore.requestFriend(userId));
      setFriendResults([]);
      setFriendQuery("");
      toast("Заявка отправлена");
    } catch (error) {
      toast(error.message);
    }
  }

  async function respondFriend(friendshipId, accept) {
    try {
      setNextProfile(await window.ProfileStore.respondFriend(friendshipId, accept));
      toast(accept ? "Заявка принята" : "Заявка отклонена");
    } catch (error) {
      toast(error.message);
    }
  }

  async function removeFriend(userId) {
    if (!confirm("Удалить игрока из друзей?")) return;
    try {
      setNextProfile(await window.ProfileStore.removeFriend(userId));
      toast("Друг удалён");
    } catch (error) {
      toast(error.message);
    }
  }

  async function sendMessage(friend) {
    const text = String(messageDrafts[friend.userId] || "").trim();
    if (!text) return;
    try {
      setNextProfile(await window.ProfileStore.sendMessage(friend.userId, text));
      setMessageDrafts(drafts => ({ ...drafts, [friend.userId]: "" }));
      toast("Сообщение отправлено");
    } catch (error) {
      toast(error.message);
    }
  }

  if (!profile) {
    return (
      <div className="shell">
        <Topbar onHome={() => onNavigate("home")} />
        <div className="card-dark text-center" style={{ maxWidth: 520, margin: "40px auto" }}>Загружаем профиль…</div>
      </div>
    );
  }

  const user = profile.user || me;
  const stats = profile.stats || { games: 0, wins: 0, totalScore: 0, history: [] };
  const rooms = profile.rooms || [];
  const friends = profile.friends || [];
  const incomingRequests = profile.incomingRequests || [];
  const outgoingRequests = profile.outgoingRequests || [];
  const messages = profile.messages || [];
  const activeSessions = profile.activeSessions || [];
  const sessionHistory = profile.sessionHistory || [];

  return (
    <div className="shell">
      <Topbar onHome={() => onNavigate("home")} right={
        <button className="btn btn-ghost btn-sm" onClick={() => onNavigate("home")}>← На главную</button>
      } />

      <div style={{ maxWidth: 1040, margin: "0 auto", width: "100%" }}>
        <div className="card-dark" style={{ marginBottom: 20 }}>
          <div className="row wrap" style={{ gap: 18, justifyContent: "space-between" }}>
            <div className="row" style={{ gap: 16 }}>
              <Avatar player={user} size="lg" ring/>
              <div>
                <div className="label-up">Профиль игрока</div>
                <h1 className="display-2" style={{ marginTop: 6 }}>{user.name}</h1>
                <div className="text-muted" style={{ marginTop: 6 }}>
                  @{user.username} · зарегистрирован {user.createdAt ? new Date(user.createdAt).toLocaleDateString("ru") : "—"}
                </div>
              </div>
            </div>
            <div className="row wrap" style={{ gap: 10 }}>
              <button className="btn btn-secondary btn-sm" onClick={() => onNavigate("stats")}>Лидеры сайта</button>
            </div>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(170px, 1fr))", gap: 12, marginBottom: 20 }}>
          {[
            ["Игр", stats.games],
            ["Побед", stats.wins],
            ["Очков", stats.totalScore || 0],
            ["Лучшее слово", stats.bestWord || "—"],
          ].map(([label, value]) => (
            <div key={label} className="card-dark text-center">
              <div className="text-muted" style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: "0.1em" }}>{label}</div>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 30, color: "var(--gold)", marginTop: 6, overflow: "hidden", textOverflow: "ellipsis" }}>{value}</div>
            </div>
          ))}
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.4fr) minmax(300px, 0.8fr)", gap: 20 }} className="profile-grid">
          <style>{`
            @media (max-width: 900px) {
              .profile-grid { grid-template-columns: 1fr !important; }
            }
          `}</style>

          <div className="col" style={{ gap: 20 }}>
            <div className="card-dark">
              <div className="between" style={{ marginBottom: 12 }}>
                <h3 className="h-section">Мои комнаты</h3>
                <span className="text-muted" style={{ fontSize: 12 }}>{rooms.length}</span>
              </div>
              {rooms.length === 0 ? (
                <div className="text-muted text-center" style={{ padding: 18 }}>Вы пока не играете ни в одной комнате.</div>
              ) : (
                <div className="col" style={{ gap: 10 }}>
                  {rooms.slice(0, 12).map(room => (
                    <button key={room.id} className="row" onClick={() => onNavigate(roomTarget(room))} style={{
                      width: "100%", textAlign: "left", cursor: "pointer",
                      gap: 12, padding: 12, borderRadius: 12,
                      border: "1px solid rgba(255,255,255,0.08)",
                      background: "rgba(255,255,255,0.04)", color: "white",
                    }}>
                      <code className="mono" style={{ color: "var(--gold)", letterSpacing: "0.12em" }}>{room.id}</code>
                      <div className="grow" style={{ minWidth: 0 }}>
                        <div style={{ fontWeight: 800, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{room.name}</div>
                        <div className="text-muted" style={{ fontSize: 12, marginTop: 2 }}>
                          {phaseText(room.phase, room.mode)} · {room.playerCount}/6 · раундов: {room.roundsPlayed}
                        </div>
                      </div>
                      {room.isHost && <span style={{ color: "var(--gold)", fontSize: 12 }}>создатель</span>}
                    </button>
                  ))}
                </div>
              )}
            </div>

            <div className="card-dark">
              <h3 className="h-section" style={{ marginBottom: 12 }}>История игр</h3>
              {stats.history.length === 0 ? (
                <div className="text-muted text-center" style={{ padding: 18 }}>Пока нет сыгранных партий.</div>
              ) : (
                <div className="col" style={{ gap: 10 }}>
                  {stats.history.map((h, i) => (
                    <div key={i} className="row" style={{ gap: 12, padding: 12, borderRadius: 12, background: "rgba(255,255,255,0.04)" }}>
                      <div style={{ width: 30, textAlign: "center" }}>{h.won ? "🥇" : "·"}</div>
                      <div className="grow">
                        <div><strong style={{ color: "var(--gold)" }}>{h.myWord || "—"}</strong>{h.bestWord && h.bestWord !== h.myWord && <span className="text-muted"> · лучшее: {h.bestWord}</span>}</div>
                        <div className="text-muted" style={{ fontSize: 11, marginTop: 2 }}>{new Date(h.at).toLocaleString("ru")} · буквы: <span className="mono">{h.letters}</span></div>
                      </div>
                      <strong>{h.total}</strong>
                    </div>
                  ))}
                </div>
              )}
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: 20 }}>
              <div className="card-dark">
                <h3 className="h-section" style={{ marginBottom: 12 }}>Друзья</h3>
                <form className="row" onSubmit={searchFriends} style={{ gap: 8, marginBottom: 12 }}>
                  <input className="field" placeholder="найти игрока" value={friendQuery} onChange={e => setFriendQuery(e.target.value)} style={{ padding: "11px 12px", fontSize: 13 }}/>
                  <button className="btn btn-secondary btn-sm" type="submit">Найти</button>
                </form>
                {friendResults.length > 0 && (
                  <div className="col" style={{ gap: 8, marginBottom: 14 }}>
                    {friendResults.map(result => (
                      <div key={result.id} className="row" style={{ gap: 10, padding: 8, borderRadius: 10, background: "rgba(255,255,255,0.04)" }}>
                        <Avatar player={result} size="sm"/>
                        <OnlineDot online={result.online}/>
                        <div className="grow" style={{ minWidth: 0 }}>
                          <div style={{ fontWeight: 700, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{result.name}</div>
                          <div className="text-muted" style={{ fontSize: 11 }}>@{result.username}</div>
                        </div>
                        {result.friendshipStatus === "accepted" ? (
                          <span style={{ color: "var(--green)", fontSize: 12 }}>друг</span>
                        ) : result.requestDirection === "outgoing" ? (
                          <span className="text-muted" style={{ fontSize: 12 }}>заявка</span>
                        ) : result.requestDirection === "incoming" ? (
                          <button className="btn btn-primary btn-sm" onClick={() => requestFriend(result.id)} type="button">Принять</button>
                        ) : (
                          <button className="btn btn-primary btn-sm" onClick={() => requestFriend(result.id)} type="button">Добавить</button>
                        )}
                      </div>
                    ))}
                  </div>
                )}
                {incomingRequests.length > 0 && (
                  <div style={{ marginBottom: 14 }}>
                    <div className="label-up" style={{ marginBottom: 8 }}>Заявки</div>
                    <div className="col" style={{ gap: 8 }}>
                      {incomingRequests.map(request => (
                        <div key={request.id} className="row" style={{ gap: 10, padding: 8, borderRadius: 10, background: "rgba(255,217,61,0.08)" }}>
                          <Avatar player={request.user} size="sm"/>
                          <OnlineDot online={request.user.online}/>
                          <div className="grow" style={{ fontWeight: 700 }}>{request.user.name}</div>
                          <button className="btn btn-primary btn-sm" onClick={() => respondFriend(request.id, true)}>Принять</button>
                          <button className="btn btn-ghost btn-sm" onClick={() => respondFriend(request.id, false)}>Отклонить</button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
                {outgoingRequests.length > 0 && (
                  <div className="text-muted" style={{ fontSize: 12, marginBottom: 12 }}>
                    Ожидают ответа: {outgoingRequests.map(r => r.user.name).join(", ")}
                  </div>
                )}
                {friends.length === 0 ? (
                  <div className="text-muted" style={{ padding: "12px 0" }}>Список друзей пока пуст.</div>
                ) : (
                  <div className="col" style={{ gap: 8 }}>
                    {friends.map(friend => (
                      <div key={friend.id} style={{ padding: 8, borderRadius: 10, background: "rgba(255,255,255,0.04)" }}>
                        <div className="row" style={{ gap: 10 }}>
                          <Avatar player={friend} size="sm"/>
                          <OnlineDot online={friend.online}/>
                          <div className="grow" style={{ minWidth: 0 }}>
                            <div style={{ fontWeight: 700 }}>{friend.name}</div>
                            <div className="text-muted" style={{ fontSize: 11 }}>@{friend.username} · {friend.online ? "онлайн" : "офлайн"}</div>
                          </div>
                          <button className="btn btn-ghost btn-sm" onClick={() => removeFriend(friend.userId)}>Удалить</button>
                        </div>
                        <div className="row" style={{ gap: 6, marginTop: 8 }}>
                          <input
                            className="field"
                            placeholder="личное сообщение"
                            value={messageDrafts[friend.userId] || ""}
                            onChange={e => setMessageDrafts(drafts => ({ ...drafts, [friend.userId]: e.target.value }))}
                            style={{ padding: "10px 12px", fontSize: 13 }}
                            maxLength={1000}
                          />
                          <button className="btn btn-primary btn-sm" onClick={() => sendMessage(friend)} disabled={!String(messageDrafts[friend.userId] || "").trim()}>↑</button>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
              <div className="card-dark">
                <h3 className="h-section" style={{ marginBottom: 12 }}>Личные сообщения</h3>
                {messages.length === 0 ? (
                  <div className="text-muted" style={{ padding: "12px 0" }}>Сообщений пока нет.</div>
                ) : (
                  <div className="col" style={{ gap: 8, maxHeight: 260, overflow: "auto" }}>
                    {messages.map(message => (
                      <div key={message.id} style={{ padding: 10, borderRadius: 10, background: message.unread ? "rgba(94,234,160,0.08)" : "rgba(255,255,255,0.04)" }}>
                        <div className="between" style={{ gap: 8 }}>
                          <strong style={{ fontSize: 13 }}>{message.fromName}</strong>
                          <span className="text-muted" style={{ fontSize: 11 }}>{new Date(message.createdAt).toLocaleString("ru")}</span>
                        </div>
                        <div className="text-muted" style={{ fontSize: 12, marginTop: 4 }}>{message.text}</div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>

          <div className="col" style={{ gap: 20 }}>
            <form className="card-dark" onSubmit={changeName}>
              <h3 className="h-section" style={{ marginBottom: 14 }}>Имя в игре</h3>
              <div className="row" style={{ gap: 8 }}>
                <input
                  className="field"
                  placeholder="имя профиля"
                  value={displayName}
                  onChange={e => setDisplayName(e.target.value)}
                  maxLength={24}
                />
                <button className="btn btn-primary btn-sm" disabled={busy || displayName.trim().length < 2 || displayName.trim() === user.name}>
                  Сохранить
                </button>
              </div>
            </form>

            <form className="card-dark" onSubmit={changePassword}>
              <h3 className="h-section" style={{ marginBottom: 14 }}>Изменить пароль</h3>
              <div className="col" style={{ gap: 10 }}>
                <input className="field" type="password" placeholder="текущий пароль" value={currentPassword} onChange={e => setCurrentPassword(e.target.value)} autoComplete="current-password"/>
                <input className="field" type="password" placeholder="новый пароль" value={newPassword} onChange={e => setNewPassword(e.target.value)} autoComplete="new-password"/>
                <button className="btn btn-primary btn-block" disabled={busy || !currentPassword || newPassword.length < 6}>
                  {busy ? "Сохраняем…" : "Сменить пароль"}
                </button>
              </div>
            </form>

            <div className="card-dark">
              <h3 className="h-section" style={{ marginBottom: 12 }}>Активные сессии</h3>
              <div className="col" style={{ gap: 10 }}>
                {activeSessions.map(s => (
                  <div key={s.id} style={{ padding: 12, borderRadius: 12, background: s.current ? "rgba(94,234,160,0.08)" : "rgba(255,255,255,0.04)", border: "1px solid rgba(255,255,255,0.08)" }}>
                    <div className="between" style={{ gap: 8 }}>
                      <strong>{deviceName(s.userAgent)}</strong>
                      {s.current && <span style={{ color: "var(--green)", fontSize: 12 }}>текущая</span>}
                    </div>
                    <div className="text-muted" style={{ fontSize: 12, marginTop: 4 }}>IP: {s.ipAddress || "—"}</div>
                    <div className="text-muted" style={{ fontSize: 12, marginTop: 2 }}>Последняя активность: {new Date(s.lastSeenAt).toLocaleString("ru")}</div>
                  </div>
                ))}
              </div>
            </div>

            <div className="card-dark">
              <h3 className="h-section" style={{ marginBottom: 12 }}>История входов</h3>
              <div className="col" style={{ gap: 8, maxHeight: 420, overflow: "auto" }}>
                {sessionHistory.length === 0 ? (
                  <div className="text-muted">История пока пуста.</div>
                ) : sessionHistory.map((s, i) => (
                  <div key={i} style={{ padding: 10, borderRadius: 10, background: "rgba(255,255,255,0.04)" }}>
                    <div className="between" style={{ gap: 8 }}>
                      <strong style={{ fontSize: 13 }}>{s.kind === "logout" ? "Выход" : s.kind === "password" ? "Пароль" : "Вход"} · {s.method}</strong>
                      <span className="text-muted" style={{ fontSize: 11 }}>{new Date(s.createdAt).toLocaleString("ru")}</span>
                    </div>
                    <div className="text-muted" style={{ fontSize: 11, marginTop: 4 }}>{deviceName(s.userAgent)} · IP: {s.ipAddress || "—"}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ===== StatsScreen =====
function StatsScreen({ onNavigate }) {
  const user = window.Auth.getUser();
  const [stats, setStats] = useState(window.StatStore.loadStats());
  const [siteStats, setSiteStats] = useState(window.StatStore.loadSiteStats ? window.StatStore.loadSiteStats() : {});
  const [leaders, setLeaders] = useState(window.StatStore.loadLeaderboard ? window.StatStore.loadLeaderboard() : []);

  useEffect(() => {
    if (user) window.StatStore.refreshStats().then(setStats).catch(() => {});
    if (window.StatStore.refreshSiteStats) {
      window.StatStore.refreshSiteStats().then(setSiteStats).catch(() => {});
    }
    if (window.StatStore.refreshLeaderboard) {
      window.StatStore.refreshLeaderboard().then(setLeaders).catch(() => {});
    }
  }, [user?.id]);

  async function clearStats() {
    if (!confirm("Очистить всю историю игр?")) return;
    const next = await window.StatStore.clearStats().catch(() => ({ games: 0, wins: 0, history: [] }));
    setStats(next);
    onNavigate("home");
  }

  return (
    <div className="shell">
      <Topbar onHome={() => onNavigate("home")} right={
        <button className="btn btn-ghost btn-sm" onClick={() => onNavigate("home")}>← Назад</button>
      } />
      <div style={{ maxWidth: 720, margin: "0 auto", width: "100%" }}>
        <div className="text-center" style={{ marginBottom: 32 }}>
          <div className="label-up">Статистика</div>
          <h2 className="display-2" style={{ marginTop: 8 }}>{user ? "Ваша история игр" : "Живая статистика сайта"}</h2>
        </div>

        <div className="row wrap" style={{ gap: 14, marginBottom: 28, justifyContent: "center" }}>
          {!user && [
            ["Игроков", siteStats.players || 0, "var(--gold)"],
            ["Онлайн", siteStats.onlinePlayers || 0, "var(--green)"],
            ["Комнат", siteStats.activeRooms || 0, "var(--cyan)"],
            ["Раундов", siteStats.roundsPlayed || 0, "var(--magenta)"],
            ["Слов", siteStats.wordsSubmitted || 0, "var(--gold)"],
          ].map(([label, value, color]) => (
            <div key={label} className="card-dark text-center" style={{ minWidth: 140 }}>
              <div className="text-muted" style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: "0.1em" }}>{label}</div>
              <div style={{ fontSize: 48, fontWeight: 800, fontFamily: "var(--font-display)", color, lineHeight: 1, marginTop: 6 }}>{value}</div>
            </div>
          ))}
          {user && (
            <>
          <div className="card-dark text-center" style={{ minWidth: 140 }}>
            <div className="text-muted" style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: "0.1em" }}>Сыграно</div>
            <div style={{ fontSize: 48, fontWeight: 800, fontFamily: "var(--font-display)", color: "var(--gold)", lineHeight: 1, marginTop: 6 }}>{stats.games}</div>
          </div>
          <div className="card-dark text-center" style={{ minWidth: 140 }}>
            <div className="text-muted" style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: "0.1em" }}>Очки</div>
            <div style={{ fontSize: 48, fontWeight: 800, fontFamily: "var(--font-display)", color: "var(--magenta)", lineHeight: 1, marginTop: 6 }}>{stats.totalScore || 0}</div>
          </div>
          <div className="card-dark text-center" style={{ minWidth: 140 }}>
            <div className="text-muted" style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: "0.1em" }}>Побед</div>
            <div style={{ fontSize: 48, fontWeight: 800, fontFamily: "var(--font-display)", color: "var(--green)", lineHeight: 1, marginTop: 6 }}>{stats.wins}</div>
          </div>
          <div className="card-dark text-center" style={{ minWidth: 140 }}>
            <div className="text-muted" style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: "0.1em" }}>% побед</div>
            <div style={{ fontSize: 48, fontWeight: 800, fontFamily: "var(--font-display)", color: "var(--cyan)", lineHeight: 1, marginTop: 6 }}>
              {stats.games > 0 ? Math.round(stats.wins / stats.games * 100) : 0}<span style={{ fontSize: 24 }}>%</span>
            </div>
          </div>
            </>
          )}
        </div>

        {user ? <div className="card-dark">
          <h3 className="h-section" style={{ marginBottom: 12 }}>Последние партии</h3>
          {stats.history.length === 0 ? (
            <div className="text-muted text-center" style={{ padding: 20, fontStyle: "italic" }}>Истории пока нет</div>
          ) : (
            <div className="col" style={{ gap: 10 }}>
              {stats.history.map((h, i) => (
                <div key={i} className="row" style={{ gap: 12, padding: 12, background: "rgba(255,255,255,0.04)", borderRadius: 12 }}>
                  <div style={{ width: 36, textAlign: "center", fontSize: 20 }}>{h.won ? "🥇" : "·"}</div>
                  <div className="grow">
                    <div style={{ fontSize: 14 }}>
                      <strong style={{ color: "var(--gold)" }}>{h.myWord || "—"}</strong>
                      {h.bestWord && h.bestWord !== h.myWord && <span className="text-muted"> · лучшее: {h.bestWord}</span>}
                    </div>
                    <div className="text-muted" style={{ fontSize: 11, marginTop: 2 }}>
                      буквы: <span className="mono">{h.letters}</span> · {new Date(h.at).toLocaleString("ru")}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
          {stats.history.length > 0 && (
            <div className="row" style={{ justifyContent: "center", marginTop: 16 }}>
              <button className="btn btn-ghost btn-sm" onClick={clearStats}>Очистить</button>
            </div>
          )}
        </div> : (
          <div className="card-dark">
            <h3 className="h-section" style={{ marginBottom: 12 }}>Сайт сейчас</h3>
            <div className="text-muted" style={{ lineHeight: 1.7 }}>
              Лучшее слово: <strong style={{ color: "var(--gold)" }}>{siteStats.bestWord?.word || "пока нет"}</strong>
              {siteStats.bestWord ? ` · ${siteStats.bestWord.score} очков · ${siteStats.bestWord.playerName}` : ""}<br/>
              Публичных комнат: <strong style={{ color: "var(--cyan)" }}>{siteStats.publicRooms || 0}</strong>
            </div>
          </div>
        )}

        <div className="card-dark" style={{ marginTop: 20 }}>
          <h3 className="h-section" style={{ marginBottom: 12 }}>Лидеры сайта</h3>
          {leaders.length === 0 ? (
            <div className="text-muted text-center" style={{ padding: 20, fontStyle: "italic" }}>Турнирная таблица пока пустая</div>
          ) : (
            <div className="col" style={{ gap: 10 }}>
              {leaders.map((p, i) => (
                <div key={p.username || i} className="row" style={{
                  gap: 12,
                  padding: "10px 12px",
                  background: "rgba(255,255,255,0.04)",
                  borderRadius: 12,
                }}>
                  <div style={{ width: 34, textAlign: "center", fontSize: 20 }}>
                    {i === 0 ? "🥇" : i === 1 ? "🥈" : i === 2 ? "🥉" : p.rank}
                  </div>
                  <Avatar player={{ name: p.name, color: p.color }} size="sm"/>
                  <div className="grow" style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 700 }}>{p.name}</div>
                    <div className="text-muted" style={{ fontSize: 11, marginTop: 2 }}>
                      игр: {p.games} · побед: {p.wins} · лучшее: {p.bestWord || "—"}
                    </div>
                  </div>
                  <div style={{ textAlign: "right", minWidth: 64 }}>
                    <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 22, color: "var(--gold)" }}>{p.totalScore || 0}</div>
                    <div className="text-muted" style={{ fontSize: 11 }}>очков</div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { FinalScreen, ProfileScreen, StatsScreen });
