/* eslint-disable */
/* Lobby screen for Игра в слова */

function LobbyScreen({ onNavigate, roomId, tweaks }) {
  const me = window.GameStore.getMe();
  const [room, setRoom] = useState(window.RoomOps.getRoom(roomId));
  const [showInvite, setShowInvite] = useState(false);
  const toast = useToast();

  useEffect(() => {
    const unsubscribe = window.RoomOps.subscribe(roomId, r => {
      if (!r) { onNavigate("home"); return; }
      setRoom(r);
      if (r.phase === "playing") {
        onNavigate(`game/${roomId}`);
      } else if (r.phase === "results") {
        onNavigate(`results/${roomId}`);
      } else if (r.phase === "finished") {
        onNavigate(`final/${roomId}`);
      }
    });
    return unsubscribe;
  }, [roomId]);

  // Show invite modal automatically for host on first visit
  useEffect(() => {
    if (room && room.hostId === me.id && room.players.length === 1) {
      setShowInvite(true);
    }
  }, []);

  if (!room) return null;

  const meInRoom = room.players.find(p => p.id === me.id);
  const isHost = room.hostId === me.id;
  const isAsync = room.settings?.mode === "async";
  const submissions = room.round?.submissions || {};
  const mySubmission = submissions[me.id];
  const submittedCount = Object.values(submissions).filter(s => s && s.word).length;
  const allReady = room.players.length >= 2 && room.players.every(p => p.ready);

  async function toggleReady() {
    try {
      await window.RoomOps.toggleReady(roomId);
      window.Sound.pick();
    } catch (error) {
      toast(error.message);
    }
  }

  async function addBot() {
    try {
      await window.RoomOps.addBot(roomId);
      window.Sound.pick();
    } catch (error) {
      toast(error.message);
    }
  }

  async function startAttempt() {
    try {
      await window.RoomOps.startAttempt(roomId);
      window.Sound.pick();
      onNavigate(`game/${roomId}`);
    } catch (error) {
      toast(error.message);
    }
  }

  async function kickBot(playerId) {
    try {
      await window.RoomOps.kickBot(roomId, playerId);
    } catch (error) {
      toast(error.message);
    }
  }

  async function ringPlayer(playerId) {
    try {
      await window.RoomOps.ringPlayer(roomId, playerId);
      window.Sound.pick();
      toast("Позвали игрока");
    } catch (error) {
      toast(error.message);
    }
  }

  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 inviteUrl = `${location.origin}${location.pathname}#join/${roomId}`;
  const telegramInviteUrl = `https://t.me/igravslovaru_bot?startapp=join_${roomId}`;
  const inviteText = `Игра в слова: присоединяйся к комнате «${room.name}» (${roomId}). Веб-ссылка: ${inviteUrl}`;

  async function copyInvite(value = inviteUrl, message = "Скопировано") {
    try {
      await navigator.clipboard.writeText(value);
      toast(message);
    } catch {
      toast("Не удалось скопировать");
    }
  }

  function openTelegramInvite() {
    const shareUrl = `https://t.me/share/url?url=${encodeURIComponent(telegramInviteUrl)}&text=${encodeURIComponent(inviteText)}`;
    if (window.Telegram?.WebApp?.openTelegramLink) {
      window.Telegram.WebApp.openTelegramLink(shareUrl);
      return;
    }
    window.open(shareUrl, "_blank", "noopener,noreferrer");
  }

  async function shareInvite() {
    if (navigator.share) {
      await navigator.share({ title: "Игра в слова", text: inviteText, url: telegramInviteUrl }).catch(() => {});
      return;
    }
    openTelegramInvite();
  }

  return (
    <div className="shell">
      <Topbar onHome={() => onNavigate("home")} right={
        <button className="btn btn-ghost btn-sm" onClick={isHost ? deleteRoom : leaveRoom} title={isHost ? "Удалить комнату" : "Выйти из комнаты"}>
          {isHost ? "Удалить" : "Выйти"}
        </button>
      } />

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) minmax(0,360px)", gap: 24, flex: 1 }} className="lobby-grid">
        <style>{`
          @media (max-width: 880px) {
            .lobby-grid { grid-template-columns: 1fr !important; }
          }
        `}</style>

        {/* Left column: room info + players + ready */}
        <div className="col" style={{ gap: 20 }}>
          <div className="card-dark">
            <div className="between">
              <div>
                <div className="label-up">Комната</div>
                <h2 className="display-2" style={{ marginTop: 6 }}>{room.name}</h2>
                <div className="row" style={{ marginTop: 8, gap: 8 }}>
                  <span className="text-muted" style={{ fontSize: 13 }}>Код:</span>
                  <code className="mono" style={{ background: "rgba(255,255,255,0.08)", padding: "4px 10px", borderRadius: 8, letterSpacing: "0.2em", fontWeight: 700 }}>{roomId}</code>
          {room.password && <span className="text-muted" style={{ fontSize: 13 }}>🔒 защищена паролем</span>}
                </div>
              </div>
              <button className="btn btn-secondary btn-sm" onClick={() => setShowInvite(true)}>
                Пригласить
              </button>
            </div>
          </div>

          <div className="card-dark">
            <div className="between" style={{ marginBottom: 16 }}>
              <h3 className="h-section">Игроки <span className="text-muted" style={{ fontWeight: 400 }}>({room.players.length}/6)</span></h3>
              {isHost && !isAsync && room.players.length < 6 && (
                <button className="btn btn-ghost btn-sm" onClick={addBot}>+ Бот</button>
              )}
            </div>
            <div className="col" style={{ gap: 10 }}>
              {room.players.map(p => (
                <div key={p.id} className="row pop-in" style={{ gap: 12 }}>
                  <div className="grow">
                    <PlayerChip
                      player={p}
                      isMe={p.id === me.id}
                      onRing={!p.isBot && p.id !== me.id ? () => ringPlayer(p.id) : null}
                      statusText={isAsync ? (() => {
                        const sub = submissions[p.id];
                        if (sub?.word) return `Сдал за ${formatDuration(sub.durationMs)}`;
                        if (sub?.startedAt) return "Думает";
                        return "Не начинал";
                      })() : undefined}
                      statusColor={isAsync ? (() => {
                        const sub = submissions[p.id];
                        if (sub?.word) return "var(--green)";
                        if (sub?.startedAt) return "var(--cyan)";
                        return "var(--ink-on-dark-3)";
                      })() : undefined}
                    />
                  </div>
                  {isHost && p.isBot && (
                    <button className="btn btn-ghost btn-sm" onClick={() => kickBot(p.id)} style={{ padding: "6px 10px" }}>✕</button>
                  )}
                </div>
              ))}
              {room.players.length < 2 && (
                <div className="text-muted text-center" style={{ fontSize: 13, padding: 12, fontStyle: "italic" }}>
                  {isAsync ? "Можно начинать попытку уже сейчас." : "Ждём остальных игроков… или добавьте бота для пробной игры."}
                </div>
              )}
            </div>
          </div>

          <div className="card-dark" style={{ background: "rgba(255,217,61,0.06)", borderColor: "rgba(255,217,61,0.25)" }}>
            <div className="row wrap" style={{ justifyContent: "space-between", gap: 12 }}>
              <div>
                <div className="label-up">Настройки раунда</div>
                <div style={{ marginTop: 6, fontSize: 15 }}>
                  <strong>{isAsync ? "Без ожидания" : "Классика"}</strong> · <strong>{room.settings.letterCount} букв + звезда</strong> · <strong>{room.settings.roundTime} сек.</strong>
                </div>
              </div>
              {isAsync ? (
                <div className="row" style={{ gap: 8 }}>
                  <button className={"btn " + (mySubmission?.word ? "btn-ghost" : "btn-primary")} onClick={startAttempt} disabled={Boolean(mySubmission?.word)}>
                    {mySubmission?.word ? "✓ Слово сдано" : mySubmission?.startedAt ? "Продолжить" : "Начать"}
                  </button>
                  <div className="text-muted" style={{ fontSize: 13, maxWidth: 260, lineHeight: 1.35 }}>
                    {mySubmission?.word
                      ? submittedCount >= 2 ? "Есть два ответа, открываем результаты…" : "Ответ сохранён. Результаты откроются после второго слова."
                      : "Каждый игрок проходит попытку в своё время."}
                  </div>
                </div>
              ) : (
                <div className="row" style={{ gap: 8 }}>
                  <button className={"btn " + (meInRoom?.ready ? "btn-ghost" : "btn-primary")} onClick={toggleReady}>
                    {meInRoom?.ready ? "✓ Готов" : "ГОТОВ"}
                  </button>
                  <div className="text-muted" style={{ fontSize: 13, maxWidth: 240, lineHeight: 1.35 }}>
                    {allReady ? "Все готовы. Раунд запускается автоматически…" : "Раунд начнётся сам, когда все игроки будут готовы."}
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Tournament standings (visible between rounds) */}
          {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);
            return (
              <div className="card-dark">
                <div className="between" style={{ marginBottom: 12 }}>
                  <h3 className="h-section">🏆 Турнир</h3>
                  <span className="text-muted" style={{ fontSize: 12 }}>раундов сыграно: {room.tournament.roundsPlayed}</span>
                </div>
                <div className="col" style={{ gap: 8 }}>
                  {standings.map((p, i) => (
                    <div key={p.id} className="row" style={{
                      gap: 10, padding: "8px 12px",
                      background: p.id === me.id ? "rgba(255,217,61,0.08)" : "transparent",
                      borderRadius: 10,
                    }}>
                      <div style={{ width: 22, textAlign: "center", fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 14, color: i === 0 ? "var(--gold)" : "var(--ink-on-dark-3)" }}>{i + 1}</div>
                      <Avatar player={p} size="sm"/>
                      <div className="grow" style={{ fontSize: 13, fontWeight: 600 }}>
                        {p.name} {p.isBot && <span className="text-muted">🤖</span>}
                      </div>
                      {!p.isBot && p.id !== me.id && <BellButton player={p} onRing={() => ringPlayer(p.id)} />}
                      <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 18, color: p.total > 0 ? "var(--gold)" : "var(--ink-on-dark-3)", minWidth: 30, textAlign: "right" }}>
                        {p.total}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            );
          })()}
        </div>

        {/* Right column: chat */}
        <ChatPanel roomId={roomId} me={me} title="Чат" style={{ minHeight: 400, maxHeight: 600 }} />
      </div>

      {/* Invite modal */}
      <Modal open={showInvite} onClose={() => setShowInvite(false)} title="Пригласите друзей">
        <div className="row wrap" style={{ gap: 10, marginBottom: 14 }}>
          <button className="btn btn-primary grow" onClick={openTelegramInvite}>Отправить в Telegram</button>
          <button className="btn btn-ghost" onClick={shareInvite}>Поделиться</button>
        </div>
        <div className="card" style={{ background: "rgba(255,255,255,0.04)", border: "1.5px solid rgba(255,255,255,0.1)", color: "white", padding: 14, marginBottom: 12 }}>
          <div className="text-muted" style={{ fontSize: 11, marginBottom: 6, textTransform: "uppercase", letterSpacing: "0.1em" }}>Ссылка</div>
          <div className="row" style={{ gap: 8 }}>
            <code className="grow mono" style={{ fontSize: 13, wordBreak: "break-all" }}>{inviteUrl}</code>
            <button className="btn btn-primary btn-sm" onClick={() => copyInvite(inviteUrl, "Ссылка скопирована")}>Копировать</button>
          </div>
        </div>
        <div className="card" style={{ background: "rgba(255,255,255,0.04)", border: "1.5px solid rgba(255,255,255,0.1)", color: "white", padding: 14, marginBottom: 16 }}>
          <div className="text-muted" style={{ fontSize: 11, marginBottom: 6, textTransform: "uppercase", letterSpacing: "0.1em" }}>Код</div>
          <div className="row" style={{ gap: 8, justifyContent: "space-between" }}>
            <code className="mono" style={{ fontSize: 26, letterSpacing: "0.3em", fontWeight: 800, color: "var(--gold)" }}>{roomId}</code>
            <button className="btn btn-ghost btn-sm" onClick={() => copyInvite(roomId, "Код скопирован")}>Копировать</button>
          </div>
          {room.password && <div style={{ marginTop: 10, fontSize: 13, color: "var(--ink-on-dark-2)" }}>Пароль знают только приглашённые игроки.</div>}
        </div>
        <p className="text-muted" style={{ fontSize: 12, lineHeight: 1.5 }}>
          Комната синхронизируется через сервер и WebSocket. Ссылку можно отправить другу на другое устройство.
        </p>
        <button className="btn btn-primary btn-block" onClick={() => setShowInvite(false)} style={{ marginTop: 16 }}>Понятно</button>
      </Modal>
    </div>
  );
}

Object.assign(window, { LobbyScreen });
