/* eslint-disable */
/* Screens for Игра в слова - Home, Create, Join */

function AuthScreen({ onNavigate, afterAuth, initialMode = "login" }) {
  const [mode, setMode] = useState(initialMode);
  const [username, setUsername] = useState("");
  const [displayName, setDisplayName] = useState("");
  const [password, setPassword] = useState("");
  const [remembered, setRemembered] = useState(null);
  const [busy, setBusy] = useState(false);
  const [telegramBusy, setTelegramBusy] = useState(false);
  const toast = useToast();
  const inTelegram = window.Auth.isTelegram && window.Auth.isTelegram();
  const telegramUser = window.Auth.telegramUser ? window.Auth.telegramUser() : null;

  useEffect(() => {
    let alive = true;
    window.Auth.rememberedDevice()
      .then(user => { if (alive) setRemembered(user); })
      .catch(() => {});
    return () => { alive = false; };
  }, []);

  async function submit(e) {
    e.preventDefault();
    setBusy(true);
    try {
      if (mode === "register") {
        await window.Auth.register({ username, password, displayName: displayName || username });
      } else {
        await window.Auth.login({ username, password });
      }
      window.Sound.submit();
      if (onNavigate) onNavigate(afterAuth || "home");
    } catch (error) {
      toast(error.message);
      window.Sound.error();
    } finally {
      setBusy(false);
    }
  }

  async function loginWithDevice() {
    setBusy(true);
    try {
      await window.Auth.loginWithDevice();
      window.Sound.submit();
      if (onNavigate) onNavigate(afterAuth || "home");
    } catch (error) {
      setRemembered(null);
      toast(error.message);
      window.Sound.error();
    } finally {
      setBusy(false);
    }
  }

  async function loginWithTelegram() {
    setTelegramBusy(true);
    try {
      await window.Auth.loginWithTelegram();
      window.Sound.submit();
      if (onNavigate) onNavigate(afterAuth || "home");
    } catch (error) {
      toast(error.message);
      window.Sound.error();
    } finally {
      setTelegramBusy(false);
    }
  }

  return (
    <div className="shell">
      <Topbar onHome={() => { if (onNavigate) onNavigate("home"); }} right={
        onNavigate ? <button className="btn btn-ghost btn-sm" onClick={() => onNavigate("home")}>На главную</button> : null
      } />
      <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center" }}>
        <form className="card-dark" onSubmit={submit} style={{ width: "100%", maxWidth: 440, display: "flex", flexDirection: "column", gap: 18 }}>
          <div>
            <div className="label-up">{mode === "register" ? "Новый игрок" : "Вход игрока"}</div>
            <h1 className="display-2" style={{ marginTop: 8 }}>Игра в слова</h1>
          </div>
          {inTelegram && (
            <div className="card-dark" style={{ background: "rgba(61,174,255,0.08)", borderColor: "rgba(61,174,255,0.3)", padding: 14 }}>
              <div className="text-muted" style={{ fontSize: 13, marginBottom: 10 }}>
                {telegramUser?.first_name ? `Telegram: ${telegramUser.first_name}` : "Вы открыли игру внутри Telegram"}
              </div>
              <button type="button" className="btn btn-primary btn-block" onClick={loginWithTelegram} disabled={telegramBusy || busy}>
                {telegramBusy ? "Входим…" : "Войти через Telegram"}
              </button>
            </div>
          )}
          {mode === "login" && remembered && (
            <div className="card-dark" style={{ background: "rgba(94,234,160,0.08)", borderColor: "rgba(94,234,160,0.3)", padding: 14 }}>
              <div className="row" style={{ gap: 10, marginBottom: 10 }}>
                <Avatar player={remembered} size="sm"/>
                <div className="grow">
                  <div style={{ fontWeight: 800 }}>{remembered.name}</div>
                  <div className="text-muted" style={{ fontSize: 12 }}>это устройство запомнено</div>
                </div>
              </div>
              <button type="button" className="btn btn-primary btn-block" onClick={loginWithDevice} disabled={busy}>
                Войти без пароля
              </button>
            </div>
          )}
          <div>
            <label className="field-label">Логин</label>
            <input className="field" value={username} onChange={e => setUsername(e.target.value)} placeholder="например, anna" autoComplete="username"/>
          </div>
          {mode === "register" && (
            <div>
              <label className="field-label">Имя в игре</label>
              <input className="field" value={displayName} onChange={e => setDisplayName(e.target.value)} placeholder="как вас зовут?" maxLength={24}/>
            </div>
          )}
          <div>
            <label className="field-label">Пароль</label>
            <input className="field" type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="минимум 6 символов" autoComplete={mode === "register" ? "new-password" : "current-password"}/>
          </div>
          <button className="btn btn-primary btn-block btn-lg" disabled={busy || !username.trim() || !password}>
            {busy ? "Подождите…" : mode === "register" ? "Зарегистрироваться" : "Войти"}
          </button>
          <button type="button" className="btn btn-ghost btn-block" onClick={() => setMode(mode === "register" ? "login" : "register")}>
            {mode === "register" ? "У меня уже есть аккаунт" : "Создать аккаунт"}
          </button>
        </form>
      </div>
    </div>
  );
}

// ===== HomeScreen =====
function HomeScreen({ onNavigate }) {
  const user = window.Auth.getUser();
  const me = window.GameStore.getMe();
  const [stats, setStats] = useState(window.StatStore.loadStats());
  const [siteStats, setSiteStats] = useState(window.StatStore.loadSiteStats ? window.StatStore.loadSiteStats() : {});
  const [myRooms, setMyRooms] = useState(window.RoomOps.loadMyRooms ? window.RoomOps.loadMyRooms() : []);
  const [joinCode, setJoinCode] = useState("");
  const [loggingOut, setLoggingOut] = useState(false);
  const toast = useToast();

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

  function tryJoin(e) {
    e && e.preventDefault();
    if (!joinCode.trim()) return;
    onNavigate(`join/${joinCode.trim().toUpperCase()}`);
  }

  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 roomPhaseText(phase, mode = "classic") {
    if (mode === "async" && phase === "playing") return "Без ожидания";
    if (phase === "playing") return "Идёт раунд";
    if (phase === "results") return "Проверка слов";
    if (phase === "finished") return "Итоги";
    return "Ожидание";
  }

  function roomPhaseColor(phase) {
    if (phase === "playing") return "var(--green)";
    if (phase === "results") return "var(--cyan)";
    if (phase === "finished") return "var(--gold)";
    return "var(--ink-on-dark-2)";
  }

  async function logout() {
    if (!confirm("Выйти из аккаунта?")) return;
    setLoggingOut(true);
    try {
      await window.Auth.logout();
      onNavigate("home");
    } catch (error) {
      toast(error.message);
    } finally {
      setLoggingOut(false);
    }
  }

  const topbarRight = user ? (
    <button className="btn btn-ghost btn-sm" onClick={logout} disabled={loggingOut}>
      {loggingOut ? "Выходим…" : "Выйти"}
    </button>
  ) : (
    <div className="row" style={{ gap: 8 }}>
      <button className="btn btn-ghost btn-sm" onClick={() => onNavigate("auth")}>Войти</button>
      <button className="btn btn-primary btn-sm" onClick={() => onNavigate("auth/register")}>Регистрация</button>
    </div>
  );

  return (
    <div className="shell">
      <Topbar onHome={() => onNavigate("home")} right={topbarRight} />
      <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", padding: "20px 0" }}>
        <div style={{ maxWidth: 920, width: "100%" }}>
          <div className="text-center" style={{ marginBottom: 48 }}>
            <div className="label-up" style={{ marginBottom: 16 }}>Игра для друзей</div>
            <h1 className="display-1" style={{ marginBottom: 16 }}>
              Сложи самое<br/>
              <span style={{ background: "linear-gradient(135deg, var(--gold), #FFA500)", WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent", backgroundClip: "text" }}>длинное слово</span>
            </h1>
            <p style={{ fontSize: 20, color: "var(--ink-on-dark-2)", maxWidth: 560, margin: "0 auto" }}>
              9 случайных букв, одна звезда и минута на размышление.<br/>
              Совсем как в телешоу 90-х. Только в браузере.
            </p>
            {!user && (
              <div className="row wrap" style={{ justifyContent: "center", gap: 12, marginTop: 24 }}>
                <button className="btn btn-primary btn-lg" onClick={() => onNavigate("auth/register")}>
                  Начать играть <StarIcon size={18}/>
                </button>
              </div>
            )}
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: 12, marginBottom: 28 }}>
            {[
              ["Игроков", siteStats.players || 0, "var(--gold)"],
              ["Онлайн", siteStats.onlinePlayers || 0, "var(--green)"],
              ["Комнат", siteStats.activeRooms || 0, "var(--cyan)"],
              ["Раундов", siteStats.roundsPlayed || 0, "var(--magenta)"],
            ].map(([label, value, color]) => (
              <div key={label} className="card-dark text-center" style={{ padding: "16px 14px" }}>
                <div className="text-muted" style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: "0.1em" }}>{label}</div>
                <div style={{ marginTop: 6, fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 34, lineHeight: 1, color }}>{value}</div>
              </div>
            ))}
          </div>

          <div className="row wrap" style={{ justifyContent: "center", gap: 10, marginBottom: 28 }}>
            <a className="btn btn-ghost btn-sm" href="/pravila">Правила</a>
            <a className="btn btn-ghost btn-sm" href="/rezhimy">Режимы</a>
            <a className="btn btn-ghost btn-sm" href="/ob-igre">Об игре</a>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))", gap: 20, maxWidth: 760, margin: "0 auto" }}>
            {/* Create room card */}
            <div className="card-dark" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <div className="row" style={{ gap: 14 }}>
                <div style={{
                  width: 52, height: 52, borderRadius: 14,
                  background: "linear-gradient(135deg, var(--gold), var(--gold-deep))",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  color: "var(--ink-1)", fontSize: 26, fontWeight: 800,
                }}>+</div>
                <div>
                  <h3 className="display-2" style={{ fontSize: 24, marginBottom: 4 }}>Создать комнату</h3>
                  <p style={{ color: "var(--ink-on-dark-2)", fontSize: 14, margin: 0 }}>Пригласите друзей по ссылке</p>
                </div>
              </div>
              <button className="btn btn-primary btn-block btn-lg" onClick={() => onNavigate(user ? "create" : "auth")}>
                {user ? "Создать" : "Войти и создать"} <StarIcon size={18}/>
              </button>
            </div>

            {/* Join room card */}
            <form className="card-dark" onSubmit={tryJoin} style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <div className="row" style={{ gap: 14 }}>
                <div style={{
                  width: 52, height: 52, borderRadius: 14,
                  background: "linear-gradient(135deg, var(--magenta), var(--magenta-deep))",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  color: "white", fontSize: 26, fontWeight: 800,
                }}>→</div>
                <div>
                  <h3 className="display-2" style={{ fontSize: 24, marginBottom: 4 }}>Войти по коду</h3>
                  <p style={{ color: "var(--ink-on-dark-2)", fontSize: 14, margin: 0 }}>Если у вас есть ссылка или код</p>
                </div>
              </div>
              <div className="row join-code-row">
                <input
                  className="field mono"
                  placeholder="ABCDE"
                  value={joinCode}
                  onChange={e => setJoinCode(e.target.value.toUpperCase().slice(0, 5))}
                  style={{ textAlign: "center", letterSpacing: "0.3em", fontWeight: 700, fontSize: 22 }}
                />
                <button className="btn btn-secondary btn-lg" type="submit" disabled={!joinCode.trim()} style={{ whiteSpace: "nowrap" }}>
                  Войти
                </button>
              </div>
            </form>

          </div>

          {myRooms.length > 0 && (
            <div style={{ marginTop: 34 }}>
              <div className="between" style={{ marginBottom: 12 }}>
                <h3 className="h-section">Мои комнаты</h3>
                <span className="text-muted" style={{ fontSize: 12 }}>последние {myRooms.length}</span>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 12 }}>
                {myRooms.slice(0, 6).map(room => (
                  <button
                    key={room.id}
                    className="card-dark"
                    onClick={() => onNavigate(roomTarget(room))}
                    style={{
                      textAlign: "left",
                      cursor: "pointer",
                      padding: 16,
                      borderColor: room.phase === "playing" ? "rgba(94,234,160,0.35)" : "rgba(255,255,255,0.1)",
                      background: room.phase === "playing" ? "rgba(94,234,160,0.06)" : "rgba(255,255,255,0.04)",
                    }}
                  >
                    <div className="between" style={{ gap: 10, marginBottom: 10 }}>
                      <strong style={{ fontSize: 16, color: "white", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{room.name}</strong>
                      <code className="mono" style={{ fontSize: 12, color: "var(--gold)", letterSpacing: "0.12em" }}>{room.id}</code>
                    </div>
                    <div className="row wrap" style={{ gap: 8, fontSize: 12 }}>
                      <span style={{ color: roomPhaseColor(room.phase), fontWeight: 700 }}>{roomPhaseText(room.phase, room.mode)}</span>
                      {room.mode === "async" && <span style={{ color: "var(--cyan)" }}>без ожидания</span>}
                      <span className="text-muted">{room.playerCount}/6</span>
                      {room.password && <span className="text-muted">🔒</span>}
                      {room.isHost && <span style={{ color: "var(--gold)" }}>создатель</span>}
                      {!room.isMember && <span style={{ color: "var(--magenta)" }}>войти снова</span>}
                    </div>
                    <div className="text-muted" style={{ fontSize: 11, marginTop: 8 }}>
                      {room.roundsPlayed > 0 ? `раундов: ${room.roundsPlayed}` : "раундов ещё не было"}
                    </div>
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Stats */}
          <div className="row wrap" style={{ justifyContent: "center", marginTop: 36, gap: 12 }}>
            {user && stats.games > 0 && (
              <>
              <div className="card-dark" style={{ padding: "14px 22px", display: "flex", gap: 16, alignItems: "center" }}>
                <span className="text-muted">Игр сыграно</span>
                <strong style={{ fontSize: 24, color: "var(--gold)" }}>{stats.games}</strong>
              </div>
              <div className="card-dark" style={{ padding: "14px 22px", display: "flex", gap: 16, alignItems: "center" }}>
                <span className="text-muted">Очков</span>
                <strong style={{ fontSize: 24, color: "var(--magenta)" }}>{stats.totalScore || 0}</strong>
              </div>
              <div className="card-dark" style={{ padding: "14px 22px", display: "flex", gap: 16, alignItems: "center" }}>
                <span className="text-muted">Побед</span>
                <strong style={{ fontSize: 24, color: "var(--green)" }}>{stats.wins}</strong>
              </div>
              </>
            )}
          </div>

          {/* Rules */}
          <details className="card-dark" style={{ marginTop: 36, maxWidth: 760, marginInline: "auto" }}>
            <summary style={{ cursor: "pointer", fontWeight: 700, fontSize: 16 }}>Правила игры</summary>
            <ol style={{ paddingLeft: 22, marginTop: 14, color: "var(--ink-on-dark-2)", lineHeight: 1.7 }}>
              <li>Один игрок создаёт комнату и делится ссылкой с друзьями (до 6 человек).</li>
              <li>Когда все нажали <strong>«ГОТОВ»</strong> — на экране выпадают 9 случайных букв и звезда.</li>
              <li>За 60 секунд нужно нажатиями составить самое длинное существительное в единственном числе.</li>
              <li>Звезда заменяет любую букву (выберите из алфавита) — но <strong>−1 очко</strong> за каждую.</li>
              <li>После раунда — слова друг друга, проверка через Google или Викисловарь, голосование за спорные слова.</li>
              <li>Очки получает только тот, чьё слово оказалось длиннее всех. Очки = <strong>длина − количество звёзд</strong>. Остальные — 0.</li>
            </ol>
          </details>
        </div>
      </div>
    </div>
  );
}

// ===== PublicRoomsScreen =====
function PublicRoomsScreen({ onNavigate }) {
  const user = window.Auth.getUser();
  const [rooms, setRooms] = useState(window.RoomOps.loadPublicRooms ? window.RoomOps.loadPublicRooms() : []);
  const [siteStats, setSiteStats] = useState(window.StatStore.loadSiteStats ? window.StatStore.loadSiteStats() : {});
  const [refreshing, setRefreshing] = useState(false);

  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 roomPhaseColor(phase) {
    if (phase === "playing") return "var(--green)";
    if (phase === "results") return "var(--cyan)";
    if (phase === "finished") return "var(--gold)";
    return "var(--ink-on-dark-2)";
  }

  function roomModeText(mode) {
    return mode === "async" ? "Без ожидания" : "Классика";
  }

  function publicRoomNote(room) {
    if (!room.hasSeats && !room.isMember) return "мест нет";
    if (room.phase === "playing" && room.mode !== "async") return "идёт игра";
    if (room.phase === "results") return "проверка слов";
    if (room.phase === "finished") return "итоги";
    if (room.onlineCount > 0) return "есть онлайн";
    return "ожидание";
  }

  async function refresh() {
    setRefreshing(true);
    try {
      const [nextRooms, nextStats] = await Promise.all([
        window.RoomOps.refreshPublicRooms ? window.RoomOps.refreshPublicRooms() : Promise.resolve([]),
        window.StatStore.refreshSiteStats ? window.StatStore.refreshSiteStats() : Promise.resolve({}),
      ]);
      setRooms(nextRooms || []);
      setSiteStats(nextStats || {});
    } finally {
      setRefreshing(false);
    }
  }

  useEffect(() => {
    refresh();
    const interval = setInterval(refresh, 20000);
    return () => clearInterval(interval);
  }, [user?.id]);

  const topbarRight = user ? (
    <button className="btn btn-primary btn-sm" onClick={() => onNavigate("create")}>Создать</button>
  ) : (
    <div className="row" style={{ gap: 8 }}>
      <button className="btn btn-ghost btn-sm" onClick={() => onNavigate("auth")}>Войти</button>
      <button className="btn btn-primary btn-sm" onClick={() => onNavigate("auth/register")}>Регистрация</button>
    </div>
  );

  return (
    <div className="shell">
      <Topbar onHome={() => onNavigate("home")} right={topbarRight} />
      <div style={{ maxWidth: 1040, width: "100%", margin: "0 auto" }}>
        <div className="between" style={{ gap: 18, alignItems: "flex-end", marginBottom: 24 }}>
          <div>
            <div className="label-up" style={{ marginBottom: 10 }}>Открытые партии</div>
            <h1 className="display-2" style={{ marginBottom: 8 }}>Публичные комнаты</h1>
            <p className="text-muted" style={{ fontSize: 16, maxWidth: 620, lineHeight: 1.5 }}>
              Сверху комнаты с онлайн игроками и свободными местами. Закрытые и заполненные комнаты опускаются ниже.
            </p>
          </div>
          <button className="btn btn-ghost btn-sm" onClick={refresh} disabled={refreshing}>
            {refreshing ? "Обновляем…" : "Обновить"}
          </button>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 12, marginBottom: 20 }}>
          {[
            ["Публичных", siteStats.publicRooms || rooms.length || 0, "var(--cyan)"],
            ["Онлайн", siteStats.onlinePlayers || 0, "var(--green)"],
            ["Всего комнат", siteStats.activeRooms || 0, "var(--gold)"],
            ["Раундов", siteStats.roundsPlayed || 0, "var(--magenta)"],
          ].map(([label, value, color]) => (
            <div key={label} className="card-dark text-center" style={{ padding: "14px 12px" }}>
              <div className="text-muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.1em" }}>{label}</div>
              <div style={{ marginTop: 6, fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 30, lineHeight: 1, color }}>{value}</div>
            </div>
          ))}
        </div>

        {rooms.length === 0 ? (
          <div className="card-dark text-center" style={{ padding: 28 }}>
            <h3 className="h-section" style={{ marginBottom: 10 }}>Публичных комнат пока нет</h3>
            <p className="text-muted" style={{ margin: "0 auto 18px", maxWidth: 520 }}>
              Создайте публичную комнату, и она появится здесь для всех игроков сайта.
            </p>
            <button className="btn btn-primary" onClick={() => onNavigate(user ? "create" : "auth/register")}>
              {user ? "Создать комнату" : "Зарегистрироваться"}
            </button>
          </div>
        ) : (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 14 }}>
            {rooms.map(room => {
              const canOpen = room.isMember || room.hasSeats;
              return (
                <button
                  key={room.id}
                  className="card-dark"
                  onClick={() => canOpen && onNavigate(roomTarget(room))}
                  disabled={!canOpen}
                  style={{
                    textAlign: "left",
                    cursor: canOpen ? "pointer" : "not-allowed",
                    padding: 16,
                    opacity: canOpen ? 1 : 0.62,
                    borderColor: room.onlineCount > 0 && room.hasSeats ? "rgba(94,234,160,0.35)" : "rgba(255,255,255,0.1)",
                    background: room.onlineCount > 0 && room.hasSeats ? "rgba(94,234,160,0.06)" : "rgba(255,255,255,0.04)",
                  }}
                >
                  <div className="between" style={{ gap: 10, marginBottom: 12 }}>
                    <strong style={{ fontSize: 17, color: "white", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{room.name}</strong>
                    <code className="mono" style={{ fontSize: 12, color: "var(--gold)", letterSpacing: "0.12em" }}>{room.id}</code>
                  </div>
                  <div className="row wrap" style={{ gap: 8, fontSize: 12, marginBottom: 8 }}>
                    <span style={{ color: roomPhaseColor(room.phase), fontWeight: 700 }}>{publicRoomNote(room)}</span>
                    <span className="text-muted">{room.playerCount}/{room.maxPlayers}</span>
                    <span style={{ color: "var(--green)" }}>онлайн {room.onlineCount}</span>
                    <span className="text-muted">офлайн {room.offlineCount}</span>
                  </div>
                  <div className="row wrap" style={{ gap: 8, fontSize: 12 }}>
                    <span style={{ color: room.mode === "async" ? "var(--cyan)" : "var(--gold)" }}>{roomModeText(room.mode)}</span>
                    <span className="text-muted">раунд {room.roundNumber || 1}</span>
                    {room.isMember && <span style={{ color: "var(--magenta)" }}>вы внутри</span>}
                    {!user && canOpen && <span className="text-muted">вход после регистрации</span>}
                  </div>
                </button>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

// ===== CreateRoomScreen =====
function CreateRoomScreen({ onNavigate, tweaks }) {
  const me = window.GameStore.getMe();
  const [roomName, setRoomName] = useState("");
  const [password, setPassword] = useState("");
  const [mode, setMode] = useState("classic");
  const [visibility, setVisibility] = useState("private");
  const [busy, setBusy] = useState(false);
  const toast = useToast();

  async function submit(e) {
    e.preventDefault();
    if (!roomName.trim()) {
      toast("Заполните название комнаты");
      return;
    }
    setBusy(true);
    try {
      const room = await window.RoomOps.createRoom({
        name: roomName.trim(),
        password: visibility === "public" ? "" : password.trim(),
        settings: {
          mode,
          visibility,
          roundTime: tweaks.roundTime,
          letterCount: tweaks.letterCount,
        },
      });
      window.Sound.submit();
      onNavigate(`room/${room.id}`);
    } catch (error) {
      toast(error.message);
      window.Sound.error();
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="shell">
      <Topbar onHome={() => onNavigate("home")} right={
        <button className="btn btn-ghost btn-sm" onClick={() => onNavigate("home")}>← Назад</button>
      } />
      <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center" }}>
        <form className="card-dark" onSubmit={submit} style={{ width: "100%", maxWidth: 480, display: "flex", flexDirection: "column", gap: 20 }}>
          <div>
            <div className="label-up">Шаг 1 из 1</div>
            <h2 className="display-2" style={{ marginTop: 8 }}>Новая комната</h2>
          </div>

          <div>
            <label className="field-label">Название комнаты</label>
            <input className="field" placeholder="например, Семья и буквы" value={roomName} onChange={e => setRoomName(e.target.value)} maxLength={40}/>
          </div>

          <div>
            <label className="field-label">Пароль (необязательно)</label>
            <input
              className="field"
              type="text"
              placeholder={visibility === "public" ? "публичная комната без пароля" : "оставьте пустым для комнаты по ссылке"}
              value={visibility === "public" ? "" : password}
              onChange={e => setPassword(e.target.value)}
              maxLength={20}
              disabled={visibility === "public"}
            />
          </div>

          <div>
            <label className="field-label">Доступ</label>
            <div className="row option-row" style={{ gap: 8 }}>
              <button
                type="button"
                className={"btn grow " + (visibility === "private" ? "btn-primary" : "btn-ghost")}
                onClick={() => setVisibility("private")}
              >
                Приватная
              </button>
              <button
                type="button"
                className={"btn grow " + (visibility === "public" ? "btn-primary" : "btn-ghost")}
                onClick={() => setVisibility("public")}
              >
                Публичная
              </button>
            </div>
          </div>

          <div>
            <label className="field-label">Режим игры</label>
            <div className="row option-row" style={{ gap: 8 }}>
              <button
                type="button"
                className={"btn grow " + (mode === "classic" ? "btn-primary" : "btn-ghost")}
                onClick={() => setMode("classic")}
              >
                Классика
              </button>
              <button
                type="button"
                className={"btn grow " + (mode === "async" ? "btn-primary" : "btn-ghost")}
                onClick={() => setMode("async")}
              >
                Без ожидания
              </button>
            </div>
          </div>

          <div className="card-dark" style={{ background: "rgba(255,217,61,0.06)", borderColor: "rgba(255,217,61,0.25)", padding: 16 }}>
            <div className="row" style={{ justifyContent: "space-between", fontSize: 13, whiteSpace: "nowrap" }}>
              <span className="text-muted">Игрок</span>
              <strong>{me.name}</strong>
            </div>
            <div className="row" style={{ justifyContent: "space-between", fontSize: 13, whiteSpace: "nowrap" }}>
              <span className="text-muted">Доступ</span>
              <strong>{visibility === "public" ? "Публичная" : "Приватная"}</strong>
            </div>
            <div className="row" style={{ justifyContent: "space-between", fontSize: 13, whiteSpace: "nowrap" }}>
              <span className="text-muted">Режим</span>
              <strong>{mode === "async" ? "Без ожидания" : "Классика"}</strong>
            </div>
            <div className="row" style={{ justifyContent: "space-between", fontSize: 13, whiteSpace: "nowrap" }}>
              <span className="text-muted">Время раунда</span>
              <strong>{tweaks.roundTime} сек</strong>
            </div>
            <div className="row" style={{ justifyContent: "space-between", fontSize: 13, marginTop: 6, whiteSpace: "nowrap" }}>
              <span className="text-muted">Букв в раунде</span>
              <strong>{tweaks.letterCount} + звезда</strong>
            </div>
            <div className="text-muted" style={{ fontSize: 11, marginTop: 8 }}>
              Изменить можно в панели <em>Tweaks</em> справа внизу.
            </div>
          </div>

          <button className="btn btn-primary btn-block btn-lg" type="submit" disabled={busy}>
            {busy ? "Создаём…" : <>Создать комнату <StarIcon size={18}/></>}
          </button>
        </form>
      </div>
    </div>
  );
}

// ===== JoinRoomScreen =====
function JoinRoomScreen({ onNavigate, roomId }) {
  const me = window.GameStore.getMe();
  const [room, setRoom] = useState(null);
  const [password, setPassword] = useState("");
  const toast = useToast();

  useEffect(() => {
    let alive = true;
    window.RoomOps.fetchRoom(roomId)
      .then(r => { if (alive) setRoom(r); })
      .catch(error => {
        if (!alive) return;
        toast(error.message || "Комната не найдена");
        onNavigate("home");
      });
    return () => { alive = false; };
  }, [roomId]);

  if (!room) return null;

  async function submit(e) {
    e.preventDefault();
    const result = await window.RoomOps.joinRoom(roomId, password.trim()).catch(error => ({ error: error.message }));
    if (result.error) { toast(result.error); return; }
    window.Sound.submit();
    onNavigate(`room/${roomId}`);
  }

  return (
    <div className="shell">
      <Topbar onHome={() => onNavigate("home")} right={
        <button className="btn btn-ghost btn-sm" onClick={() => onNavigate("home")}>← Назад</button>
      } />
      <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center" }}>
        <form className="card-dark" onSubmit={submit} style={{ width: "100%", maxWidth: 460, display: "flex", flexDirection: "column", gap: 20 }}>
          <div>
            <div className="label-up">Вход в комнату</div>
            <h2 className="display-2" style={{ marginTop: 8 }}>{room.name}</h2>
            <div className="row" style={{ marginTop: 12, gap: 8 }}>
              {room.players.slice(0, 6).map(p => <Avatar key={p.id} player={p} size="sm"/>)}
              <span className="text-muted" style={{ fontSize: 13 }}>
                {room.players.length} {room.players.length === 1 ? "игрок" : room.players.length < 5 ? "игрока" : "игроков"}
              </span>
            </div>
          </div>

          <div className="card-dark" style={{ background: "rgba(255,255,255,0.04)", padding: 14 }}>
            <div className="row" style={{ justifyContent: "space-between", gap: 12 }}>
              <span className="text-muted" style={{ fontSize: 13 }}>Вы войдёте как</span>
              <strong>{me.name}</strong>
            </div>
          </div>

          {room.password && (
            <div>
              <label className="field-label">Пароль</label>
              <input className="field" type="text" placeholder="пароль комнаты" value={password} onChange={e => setPassword(e.target.value)}/>
            </div>
          )}

          <button className="btn btn-primary btn-block btn-lg" type="submit">
            Войти <StarIcon size={18}/>
          </button>
        </form>
      </div>
    </div>
  );
}

Object.assign(window, { AuthScreen, HomeScreen, PublicRoomsScreen, CreateRoomScreen, JoinRoomScreen });
