/* eslint-disable */
/* Results screen — show each player's word with checks and voting */

function ResultsScreen({ onNavigate, roomId }) {
  const me = window.GameStore.getMe();
  const [room, setRoom] = useState(window.RoomOps.getRoom(roomId));
  const [revealed, setRevealed] = useState(new Set());
  const verificationStartedRef = useRef(new Set());
  const toast = useToast();
  const submissionFingerprint = JSON.stringify(Object.entries(room?.round?.submissions || {})
    .map(([id, sub]) => [id, sub?.word || "", sub?.verified])
    .sort());

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

  // Stagger-reveal words
  useEffect(() => {
    if (!room) return;
    room.players.forEach((p, i) => {
      setTimeout(() => {
        setRevealed(r => new Set([...r, p.id]));
        if (window.Sound.enabled) window.Sound.reveal();
      }, 400 + i * 600);
    });
  }, [room?.round?.startedAt]);

  // Verify words via Wiktionary (with local dictionary as cache).
  // Any active player may run verification; results are persisted into the room state for everyone.
  useEffect(() => {
    if (!room || !room.round) return;
    const letters = room.round.letters;
    room.players.forEach(async (p) => {
      const sub = room.round.submissions[p.id];
      if (!sub || !sub.word) return;
      if (sub.verified !== undefined && sub.verified !== null) return;
      const key = `${room.round.startedAt}-${p.id}`;
      if (verificationStartedRef.current.has(key)) return;
      verificationStartedRef.current.add(key);

      const fits = window.GameLogic.canBuildFromLetters(sub.word, letters);
      if (!fits) {
        window.RoomOps.verifyWord(roomId, { playerId: p.id, verified: false, source: "letters", reason: "letters" }).catch(() => {});
        return;
      }

      // Wiktionary check (with local dict cache)
      try {
        const result = await window.WordVerifier.verifyWordViaWiktionary(sub.word);
        window.RoomOps.verifyWord(roomId, {
          playerId: p.id,
          verified: result.verified,
          source: result.source,
          reason: result.reason || "",
        }).catch(() => {});
      } catch (e) {
        window.RoomOps.verifyWord(roomId, { playerId: p.id, verified: false, source: "error", reason: "fetch-failed" }).catch(() => {});
      }
    });
  }, [room?.round?.startedAt, room?.players?.length, submissionFingerprint]);

  if (!room || !room.round) return null;
  const round = room.round;
  const isAsync = room.settings?.mode === "async";

  function wordChecks(word, letters) {
    if (!word) return { fits: false, dict: false };
    const fits = window.GameLogic.canBuildFromLetters(word, letters);
    const dict = window.GameLogic.isInDictionary(word);
    return { fits, dict };
  }

  function isAccepted(p) {
    const sub = round.submissions[p.id];
    if (!sub || !sub.word) return false;
    // Word counts only when verified === true (dict hit or AI-confirmed)
    return sub.verified === true;
  }

  // True while at least one submission is still being verified
  const verificationPending = room.players.some(p => {
    const sub = round.submissions[p.id];
    return sub && sub.word && (sub.verified === undefined || sub.verified === null);
  });

  // Compute scores: only the player(s) with the longest valid word (after star penalty) get points.
  // Their score equals (length − stars). Everyone else gets 0.
  const scored = room.players.map(p => {
    const sub = round.submissions[p.id];
    const accepted = isAccepted(p);
    const stars = (sub && sub.word) ? Math.max(0, window.GameLogic.countStarsNeeded(sub.word, round.letters)) : 0;
    const len = accepted && sub.word ? sub.word.length : 0;
    const base = Math.max(0, len - stars);
    const durationMs = Number.isFinite(Number(sub?.durationMs)) ? Number(sub.durationMs) : null;
    return { player: p, sub, accepted, length: len, stars, base, durationMs };
  });
  const maxBase = Math.max(0, ...scored.map(s => s.base));
  const durationValue = s => s.durationMs == null ? Number.MAX_SAFE_INTEGER : s.durationMs;
  const fastestDuration = isAsync && maxBase > 0
    ? Math.min(...scored.filter(s => s.base === maxBase).map(durationValue))
    : Number.MAX_SAFE_INTEGER;
  scored.forEach(s => {
    // Only the winner(s) get points
    s.bonus = 0;
    s.total = isAsync
      ? (s.base > 0 && s.base === maxBase && durationValue(s) === fastestDuration ? s.base : 0)
      : (s.base > 0 && s.base === maxBase ? s.base : 0);
  });
  scored.sort((a, b) => b.total - a.total || b.base - a.base || durationValue(a) - durationValue(b));

  async function finishGame() {
    try {
      await window.RoomOps.finalize(roomId);
      await window.StatStore.refreshStats().catch(() => {});
      window.Sound.fanfare();
    } 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 isHost = room.hostId === me.id;

  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 className="text-center" style={{ marginBottom: 32 }}>
        <div className="label-up">Раунд окончен</div>
        <h2 className="display-2" style={{ marginTop: 8 }}>{isAsync ? "Асинхронные ответы" : "Слова игроков"}</h2>
        <div className="row" style={{ justifyContent: "center", gap: 6, marginTop: 14 }}>
          {round.letters.map((l, i) => {
            const isStar = l === "★";
            return (
              <span key={i} style={{
                display: "inline-flex", alignItems: "center", justifyContent: "center",
                width: 38, height: 38, borderRadius: 8,
                background: isStar ? "var(--tile-star-bg)" : "white",
                color: "var(--ink-1)",
                fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20,
              }}>{isStar ? <StarIcon size={18}/> : l}</span>
            );
          })}
        </div>
      </div>

      <div className="col" style={{ gap: 14, marginBottom: 24 }}>
        {scored.map((s, rank) => {
          const p = s.player;
          const sub = s.sub;
          const isMe = p.id === me.id;
          const isRevealed = revealed.has(p.id);
          const checks = wordChecks(sub?.word, round.letters);
          const word = sub?.word || "";
          const verified = sub?.verified;
          const verifiedSource = sub?.verifiedSource;
          const verifiedReason = sub?.verifiedReason;
          const wordOk = s.accepted;

          return (
            <div key={p.id} className="card-dark" style={{
              padding: 20,
              borderColor: isMe ? "rgba(255,217,61,0.4)" : undefined,
              background: rank === 0 && s.total > 0 ? "linear-gradient(135deg, rgba(255,217,61,0.12), rgba(255,107,107,0.08))" : undefined,
              opacity: isRevealed ? 1 : 0.3,
              transition: "opacity 400ms",
            }}>
              <div className="row wrap" style={{ gap: 16, justifyContent: "space-between" }}>
                <div className="row" style={{ gap: 14, minWidth: 0, flex: "1 1 auto" }}>
                  <div style={{ position: "relative" }}>
                    <Avatar player={p} ring={rank === 0 && s.total > 0}/>
                    {rank === 0 && s.total > 0 && (
                      <div style={{
                        position: "absolute", top: -8, right: -8,
                        background: "var(--gold)", color: "var(--ink-1)",
                        width: 24, height: 24, borderRadius: "50%",
                        display: "flex", alignItems: "center", justifyContent: "center",
                        fontSize: 12, fontWeight: 800,
                      }}>👑</div>
                    )}
                  </div>
                  <div style={{ minWidth: 0 }}>
                    <div className="row" style={{ gap: 8 }}>
                      <strong style={{ fontSize: 16 }}>{p.name}</strong>
                      {isMe && <span className="text-muted" style={{ fontSize: 12 }}>(вы)</span>}
                      {p.isBot && <span className="text-muted" style={{ fontSize: 12 }}>🤖</span>}
                      {!isMe && !p.isBot && <BellButton player={p} onRing={() => ringPlayer(p.id)} />}
                    </div>
                    <div style={{ marginTop: 6, minHeight: 36, display: "flex", alignItems: "center" }}>
                      {!isRevealed ? (
                        <div className="text-muted" style={{ fontSize: 14 }}>раскрывается…</div>
                      ) : !word ? (
                        <div className="text-muted" style={{ fontSize: 14, fontStyle: "italic" }}>не успел(а) ввести слово</div>
                      ) : (
                        <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
                          <div style={{
                            fontFamily: "var(--font-display)", fontWeight: 800,
                            fontSize: 26, letterSpacing: "0.04em",
                            color: wordOk ? "var(--gold)" : checks.fits ? "white" : "var(--coral)",
                            textDecoration: !checks.fits || verified === false ? "line-through" : "none",
                            opacity: verified === false ? 0.7 : 1,
                            display: "inline-flex",
                            alignItems: "center",
                          }}>
                            {(() => {
                              const stars = checks.fits ? window.GameLogic.markStarPositions(word, round.letters) : [];
                              return word.split("").map((ch, i) => {
                                const isStar = stars[i];
                                return (
                                  <span key={i} style={{
                                    position: "relative",
                                    display: "inline-block",
                                    color: isStar ? "var(--gold-deep)" : undefined,
                                    background: isStar ? "linear-gradient(135deg, rgba(255,217,61,0.35), rgba(245,180,0,0.25))" : "transparent",
                                    padding: isStar ? "0 4px" : 0,
                                    borderRadius: isStar ? 6 : 0,
                                    margin: isStar ? "0 1px" : 0,
                                    border: isStar ? "1.5px solid rgba(255,217,61,0.7)" : "none",
                                  }}>
                                    {ch}
                                    {isStar && <StarIcon size={10} style={{
                                      position: "absolute", top: -4, right: -4,
                                      color: "var(--gold-deep)",
                                      filter: "drop-shadow(0 1px 2px rgba(0,0,0,0.4))",
                                    }}/>}
                                  </span>
                                );
                              });
                            })()}
                          </div>
                          {s.stars > 0 && <span style={{ background: "rgba(255,217,61,0.18)", color: "var(--gold)", padding: "3px 10px", borderRadius: "var(--radius-pill)", fontSize: 11, fontWeight: 700, whiteSpace: "nowrap", display: "inline-flex", alignItems: "center", gap: 4 }}><StarIcon size={11}/> −{s.stars}</span>}
                          {isAsync && s.durationMs != null && <span style={{ background: "rgba(78,205,196,0.18)", color: "var(--cyan)", padding: "3px 10px", borderRadius: "var(--radius-pill)", fontSize: 11, fontWeight: 700, whiteSpace: "nowrap" }}>⏱ {formatDuration(s.durationMs)}</span>}
                          {!checks.fits && <span style={{ background: "rgba(255,107,107,0.18)", color: "var(--coral)", padding: "3px 10px", borderRadius: "var(--radius-pill)", fontSize: 11, fontWeight: 700, whiteSpace: "nowrap" }}>не из этих букв</span>}
                          {checks.fits && (verified === undefined || verified === null) && <span style={{ background: "rgba(78,205,196,0.18)", color: "var(--cyan)", padding: "3px 10px", borderRadius: "var(--radius-pill)", fontSize: 11, fontWeight: 700, whiteSpace: "nowrap" }}>⏳ Викисловарь…</span>}
                          {checks.fits && verified === true && verifiedSource === "dict-fallback" && <span style={{ background: "rgba(255,217,61,0.18)", color: "var(--gold)", padding: "3px 10px", borderRadius: "var(--radius-pill)", fontSize: 11, fontWeight: 700, whiteSpace: "nowrap" }} title="Сеть недоступна — проверено по локальному словарю">⚠ локальный словарь</span>}
                          {checks.fits && verified === true && verifiedSource === "wikt" && <span style={{ background: "rgba(94,234,160,0.18)", color: "var(--green)", padding: "3px 10px", borderRadius: "var(--radius-pill)", fontSize: 11, fontWeight: 700, whiteSpace: "nowrap" }}>✓ Викисловарь</span>}
                          {checks.fits && verified === false && verifiedReason === "no-page" && <span style={{ background: "rgba(255,107,107,0.18)", color: "var(--coral)", padding: "3px 10px", borderRadius: "var(--radius-pill)", fontSize: 11, fontWeight: 700, whiteSpace: "nowrap" }}>✕ нет в Викисловаре</span>}
                          {checks.fits && verified === false && verifiedReason === "proper-noun" && <span style={{ background: "rgba(255,107,107,0.18)", color: "var(--coral)", padding: "3px 10px", borderRadius: "var(--radius-pill)", fontSize: 11, fontWeight: 700, whiteSpace: "nowrap" }}>✕ имя собственное</span>}
                          {checks.fits && verified === false && verifiedReason === "not-noun" && <span style={{ background: "rgba(255,107,107,0.18)", color: "var(--coral)", padding: "3px 10px", borderRadius: "var(--radius-pill)", fontSize: 11, fontWeight: 700, whiteSpace: "nowrap" }}>✕ не существительное</span>}
                          {checks.fits && verified === false && verifiedReason === "inflected-form" && <span style={{ background: "rgba(255,107,107,0.18)", color: "var(--coral)", padding: "3px 10px", borderRadius: "var(--radius-pill)", fontSize: 11, fontWeight: 700, whiteSpace: "nowrap" }}>✕ не им.п. ед.ч.</span>}
                          {checks.fits && verified === false && (verifiedReason === "fetch-failed" || verifiedSource === "error") && <span style={{ background: "rgba(255,107,107,0.18)", color: "var(--coral)", padding: "3px 10px", borderRadius: "var(--radius-pill)", fontSize: 11, fontWeight: 700, whiteSpace: "nowrap" }}>✕ ошибка проверки</span>}
                        </div>
                      )}
                    </div>
                  </div>
                </div>

                {/* Right side: score */}
                <div style={{ textAlign: "right", minWidth: 120 }}>
                  {isRevealed && (
                    <>
                      <div style={{ fontSize: 32, fontWeight: 800, color: s.total > 0 ? "var(--gold)" : "var(--ink-on-dark-3)", fontFamily: "var(--font-display)", lineHeight: 1 }}>
                        +{s.total}
                      </div>
                      <div className="text-muted" style={{ fontSize: 11, marginTop: 4, whiteSpace: "nowrap" }}>
                        {s.length > 0 ? (
                          <>
                            {s.length} букв{s.stars > 0 && <span> − {s.stars}★</span>}{s.total === 0 && s.base > 0 && <span style={{ color: "var(--ink-on-dark-3)" }}> · не выиграл</span>}
                            {isAsync && s.durationMs != null && <span> · {formatDuration(s.durationMs)}</span>}
                          </>
                        ) : "—"}
                      </div>
                    </>
                  )}
                </div>
              </div>

              {/* Check actions */}
              {isRevealed && word && checks.fits && (
                <div className="row wrap" style={{ marginTop: 14, gap: 8, paddingTop: 14, borderTop: "1px solid rgba(255,255,255,0.08)" }}>
                  <span className="text-muted" style={{ fontSize: 12 }}>проверить:</span>
                  <a className="btn btn-ghost btn-sm" href={`https://www.google.com/search?q=${encodeURIComponent(word + " существительное")}`} target="_blank" rel="noopener">🔎 Google</a>
                  <a className="btn btn-ghost btn-sm" href={`https://ru.wiktionary.org/wiki/${encodeURIComponent(word.toLowerCase())}`} target="_blank" rel="noopener">📖 Викисловарь</a>
                  <a className="btn btn-ghost btn-sm" href={`https://ru.wikipedia.org/wiki/${encodeURIComponent(word.toLowerCase())}`} target="_blank" rel="noopener">🌐 Википедия</a>
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Chat moved below results */}
      <div style={{ marginBottom: 20 }}>
        <ChatPanel roomId={roomId} me={me} title="Обсуждение"/>
      </div>

      {/* Bottom action */}
      <div className="col" style={{ alignItems: "center", gap: 8 }}>
        <button className="btn btn-primary btn-lg" onClick={finishGame} disabled={verificationPending}>
          {verificationPending ? "⏳ проверяем слова…" : <>Перейти к итогам <StarIcon size={18}/></>}
        </button>
        {verificationPending && (
          <div className="text-muted" style={{ fontSize: 12 }}>
            Запрашиваем Викисловарь… После проверки любой игрок сможет открыть итоги.
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { ResultsScreen });
