/* eslint-disable */
/* Game screen — the main word-building interaction */

function GameScreen({ onNavigate, roomId }) {
  const me = window.GameStore.getMe();
  const [room, setRoom] = useState(window.RoomOps.getRoom(roomId));
  const [slots, setSlots] = useState([]); // array of {idx, asLetter?}
  const [starPickerIdx, setStarPickerIdx] = useState(null); // letter-index waiting for alphabet choice
  const [secondsLeft, setSecondsLeft] = useState(60);
  const [elapsedSeconds, setElapsedSeconds] = useState(0);
  const [submitted, setSubmitted] = useState(false);
  const [errorShake, setErrorShake] = useState(false);
  const tickedAtRef = useRef(new Set());
  const toast = useToast();
  const isAsync = room?.settings?.mode === "async";
  const mySubmission = room?.round?.submissions?.[me.id];

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

  useEffect(() => {
    setSlots([]);
    setSubmitted(false);
    setStarPickerIdx(null);
    tickedAtRef.current = new Set();
  }, [room?.round?.id]);

  useEffect(() => {
    if (mySubmission?.word && Array.isArray(mySubmission.slots)) {
      setSlots(mySubmission.slots);
      setSubmitted(true);
    }
  }, [mySubmission?.word]);

  // Timer
  useEffect(() => {
    if (!room?.round) return;
    if (isAsync) {
      if (!mySubmission?.startedAt) {
        setElapsedSeconds(0);
        return;
      }
      if (mySubmission.word) {
        setElapsedSeconds(Math.round((mySubmission.durationMs || 0) / 1000));
        return;
      }
      function tickAsync() {
        setElapsedSeconds(Math.max(0, Math.floor((Date.now() - mySubmission.startedAt) / 1000)));
      }
      tickAsync();
      const interval = setInterval(tickAsync, 250);
      return () => clearInterval(interval);
    }
    function tick() {
      const elapsed = (Date.now() - room.round.startedAt) / 1000;
      const remaining = Math.max(0, Math.ceil(room.round.roundTime - elapsed));
      setSecondsLeft(remaining);
      if (remaining <= 5 && remaining > 0 && !tickedAtRef.current.has(remaining)) {
        tickedAtRef.current.add(remaining);
        window.Sound.tickHi();
      } else if (remaining > 5 && remaining <= 10 && remaining % 1 === 0 && !tickedAtRef.current.has(remaining)) {
        tickedAtRef.current.add(remaining);
        window.Sound.tick();
      }
      if (remaining === 0) {
        finishRound();
      }
    }
    tick();
    const interval = setInterval(tick, 250);
    return () => clearInterval(interval);
  }, [room?.round?.startedAt, isAsync, mySubmission?.startedAt, mySubmission?.word, mySubmission?.durationMs]);

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

  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);
    }
  }

  if (!room) return null;
  const isHost = room.hostId === me.id;
  const roomExitButton = (
    <button className="btn btn-ghost btn-sm" onClick={isHost ? deleteRoom : leaveRoom} title={isHost ? "Удалить комнату" : "Выйти из комнаты"}>
      {isHost ? "Удалить" : "Выйти"}
    </button>
  );

  if (!room.round || (isAsync && !mySubmission?.startedAt)) {
    return (
      <div className="shell" style={{ paddingBottom: 16 }}>
        <Topbar onHome={() => onNavigate("home")} right={roomExitButton} />
        <div style={{ maxWidth: 760, margin: "40px auto 24px", width: "100%" }}>
          <div className="card-dark text-center" style={{ padding: 28 }}>
            <div className="label-up">{isAsync ? "Без ожидания" : "Раунд ещё не начался"}</div>
            <h2 className="display-2" style={{ marginTop: 8, marginBottom: 12 }}>
              {isAsync ? "Начните свою попытку" : "Ждём старт раунда"}
            </h2>
            <p className="text-muted" style={{ margin: "0 auto 20px", maxWidth: 480, lineHeight: 1.5 }}>
              {isAsync
                ? "Буквы откроются после старта, а время будет считаться только для вашей попытки."
                : "Вернитесь в комнату и нажмите готовность вместе с остальными игроками."}
            </p>
            {isAsync ? (
              <button className="btn btn-primary btn-lg" onClick={startAttempt}>
                Начать попытку <StarIcon size={18}/>
              </button>
            ) : (
              <button className="btn btn-ghost" onClick={() => onNavigate(`room/${roomId}`)}>В комнату</button>
            )}
          </div>
        </div>
        <ChatPanel roomId={roomId} me={me} title="Чат" style={{ maxWidth: 760, margin: "0 auto", width: "100%" }} />
      </div>
    );
  }

  const round = room.round;
  const letters = round.letters;
  const effectiveSubmitted = submitted || Boolean(mySubmission?.word);

  // Build current word from slots; star slots use asLetter
  const usedIdx = slots.map(s => s.idx);
  const currentWord = slots.map(s => s.asLetter || letters[s.idx]).join("");
  const starCount = slots.filter(s => letters[s.idx] === "★").length;
  const wordValid = slots.length >= 2 && slots.every(s => letters[s.idx] !== "★" || s.asLetter);

  function pickLetter(i) {
    if (effectiveSubmitted) return;
    if (usedIdx.includes(i)) return;
    if (letters[i] === "★") {
      // Open alphabet picker, slot is added once user chooses a letter
      setStarPickerIdx(i);
      return;
    }
    setSlots([...slots, { idx: i }]);
    window.Sound.pick();
  }
  function chooseStarLetter(letter) {
    if (starPickerIdx == null) return;
    setSlots([...slots, { idx: starPickerIdx, asLetter: letter }]);
    setStarPickerIdx(null);
    window.Sound.pick();
  }
  function popLetter() {
    if (effectiveSubmitted) return;
    if (!slots.length) return;
    setSlots(slots.slice(0, -1));
    window.Sound.unpick();
  }
  function clearWord() {
    if (effectiveSubmitted) return;
    setSlots([]);
    window.Sound.unpick();
  }
  function popAt(pos) {
    if (effectiveSubmitted) return;
    setSlots(slots.slice(0, pos));
    window.Sound.unpick();
  }

  async function submit() {
    if (!wordValid) {
      setErrorShake(true);
      setTimeout(() => setErrorShake(false), 400);
      window.Sound.error();
      toast("Слово должно быть не короче 2 букв");
      return;
    }
    try {
      await window.RoomOps.submitWord(roomId, {
        word: currentWord.toUpperCase(),
        slots: [...slots],
        starCount,
      });
      setSubmitted(true);
      window.Sound.submit();
    } catch (error) {
      toast(error.message);
      window.Sound.error();
    }
  }

  function finishRound() {
    if (!isAsync && room?.phase === "playing") window.RoomOps.finishRound(roomId).catch(() => {});
  }

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

  // How many already submitted
  const submittedCount = Object.values(round.submissions).filter(s => s && s.word).length;
  const totalCount = room.players.length;

  return (
    <div className="shell game-shell" style={{ paddingBottom: 16 }}>
      {/* Top bar */}
      <div className="between game-topbar" style={{ marginBottom: 20 }}>
        <Brand onClick={() => {}}/>
        <div className="row game-status-row" style={{ gap: 12 }}>
          <HeaderProfileBadge />
          {roomExitButton}
          <div className="card-dark game-mini-card" style={{ padding: "8px 16px", display: "flex", gap: 10, alignItems: "center" }}>
            <span className="text-muted" style={{ fontSize: 12 }}>{isAsync ? "Ответов:" : "Сдали:"}</span>
            <strong style={{ color: "var(--green)" }}>{submittedCount}/{totalCount}</strong>
          </div>
          {isAsync ? (
            <div className="card-dark game-mini-card" style={{ padding: "8px 16px", minWidth: 104, textAlign: "center" }}>
              <div className="text-muted" style={{ fontSize: 11 }}>Время</div>
              <strong style={{ fontFamily: "var(--font-display)", fontSize: 22, color: "var(--cyan)" }}>
                {mySubmission?.word ? formatDuration(mySubmission.durationMs) : formatDuration(elapsedSeconds * 1000)}
              </strong>
            </div>
          ) : (
            <TimerRing secondsLeft={secondsLeft} total={round.roundTime}/>
          )}
        </div>
      </div>

      {isAsync && effectiveSubmitted && room.phase === "playing" && (
        <div className="card-dark" style={{ marginBottom: 20, background: "rgba(94,234,160,0.08)", borderColor: "rgba(94,234,160,0.35)" }}>
          <div className="between" style={{ gap: 12 }}>
            <div>
              <div className="label-up">Ответ сохранён</div>
              <div style={{ marginTop: 6, fontSize: 15 }}>
                Результаты откроются после второго сданного слова.
              </div>
            </div>
            <strong style={{ color: "var(--green)", fontFamily: "var(--font-display)", fontSize: 24 }}>{formatDuration(mySubmission?.durationMs)}</strong>
          </div>
        </div>
      )}

      {/* Word builder slot strip */}
      <div className={"card-dark " + (errorShake ? "shake" : "")} style={{
        marginBottom: 24,
        padding: "20px 24px",
        minHeight: 110,
        display: "flex",
        flexDirection: "column",
        gap: 10,
        background: effectiveSubmitted ? "rgba(94,234,160,0.08)" : "rgba(255,255,255,0.04)",
        borderColor: effectiveSubmitted ? "rgba(94,234,160,0.4)" : undefined,
      }}>
        <div className="between">
          <div className="label-up">{effectiveSubmitted ? "Слово отправлено" : "Ваше слово"}</div>
          <div className="text-muted" style={{ fontSize: 13 }}>
            {slots.length} букв
            {starCount > 0 && <span> · ★ −{starCount}</span>}
            {" · "}<strong style={{ color: "var(--gold)" }}>{Math.max(0, slots.length - starCount)} очков</strong>
          </div>
        </div>
        <div className="row wrap" style={{ gap: 8, minHeight: 56, alignItems: "center" }}>
          {slots.length === 0 && effectiveSubmitted && mySubmission?.word && (
            <div style={{
              fontFamily: "var(--font-display)",
              fontWeight: 800,
              fontSize: 28,
              color: "var(--gold)",
              letterSpacing: "0.04em",
            }}>
              {mySubmission.word}
            </div>
          )}
          {slots.length === 0 && !effectiveSubmitted && (
            <div className="text-muted" style={{ fontStyle: "italic", fontSize: 15 }}>
              нажимайте на буквы внизу, чтобы составить слово…
            </div>
          )}
          {slots.map((s, pos) => {
            const isStar = letters[s.idx] === "★";
            return (
              <button key={pos} className="pop-in" onClick={() => popAt(pos)} disabled={effectiveSubmitted} style={{
                width: 48, height: 48, borderRadius: 12, border: "none",
                cursor: effectiveSubmitted ? "default" : "pointer",
                background: isStar ? "var(--tile-star-bg)" : "linear-gradient(135deg, var(--gold), var(--gold-deep))",
                color: "var(--ink-1)",
                fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 24,
                display: "flex", alignItems: "center", justifyContent: "center",
                boxShadow: "0 4px 0 var(--gold-deep)",
                position: "relative",
              }}>
                {s.asLetter || (isStar ? <StarIcon size={22}/> : letters[s.idx])}
                {isStar && s.asLetter && (
                  <span style={{
                    position: "absolute", top: -6, right: -6,
                    width: 18, height: 18, borderRadius: "50%",
                    background: "white", color: "var(--gold-deep)",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontSize: 10,
                  }}><StarIcon size={10}/></span>
                )}
              </button>
            );
          })}
        </div>
      </div>

      {/* Letter tiles pool */}
      <div className="card-dark" style={{ padding: 24, marginBottom: 20, opacity: effectiveSubmitted ? 0.5 : 1, transition: "opacity 200ms" }}>
        <div className="between" style={{ marginBottom: 16 }}>
          <div className="label-up">Доступные буквы</div>
        </div>
        <div className="row wrap letter-pool" style={{ gap: 12, justifyContent: "center" }}>
          {letters.map((l, i) => (
            <LetterTile
              key={i}
              letter={l}
              used={usedIdx.includes(i)}
              onClick={() => pickLetter(i)}
              animateDrop
              dropDelay={i * 80}
            />
          ))}
        </div>
      </div>

      {/* Controls */}
      <div className="row wrap game-controls" style={{ gap: 10, justifyContent: "center", marginBottom: 18 }}>
        <button className="btn btn-ghost" onClick={popLetter} disabled={effectiveSubmitted || slots.length === 0}>← Стереть</button>
        <button className="btn btn-ghost" onClick={clearWord} disabled={effectiveSubmitted || slots.length === 0}>Очистить</button>
        <button className="btn btn-primary btn-lg" onClick={submit} disabled={effectiveSubmitted || !wordValid}>
          {effectiveSubmitted ? "✓ Отправлено" : "Отправить"}
        </button>
      </div>

      {/* Other players progress */}
      <div className="card-dark">
        <div className="label-up" style={{ marginBottom: 12 }}>Игроки</div>
        <div className="row wrap" style={{ gap: 10 }}>
          {room.players.filter(p => p.id !== me.id).map(p => {
            const sub = round.submissions[p.id];
            const hasSubmitted = !!sub?.word;
            const hasStarted = !!sub?.startedAt;
            return (
              <div key={p.id} className="row" style={{
                gap: 10, padding: "8px 14px 8px 8px",
                background: hasSubmitted ? "rgba(94,234,160,0.12)" : "rgba(255,255,255,0.04)",
                border: `1.5px solid ${hasSubmitted ? "rgba(94,234,160,0.4)" : "rgba(255,255,255,0.1)"}`,
                borderRadius: "var(--radius-pill)",
                transition: "all 200ms",
              }}>
                <Avatar player={p} size="sm"/>
                <div style={{ fontSize: 14 }}>
                  <strong>{p.name}</strong>{p.isBot && <span className="text-muted" style={{ marginLeft: 4 }}>🤖</span>}
                  <span className="text-muted" style={{ fontSize: 12, marginLeft: 8 }}>
                    {hasSubmitted ? `✓ сдал ${isAsync ? formatDuration(sub.durationMs) : ""}` : isAsync && !hasStarted ? "не начинал" : "думает…"}
                  </span>
                </div>
                {!p.isBot && <BellButton player={p} onRing={() => ringPlayer(p.id)} />}
              </div>
            );
          })}
        </div>
      </div>

      {/* Star letter picker modal */}
      <Modal open={starPickerIdx !== null} onClose={() => setStarPickerIdx(null)} title="Какую букву заменит звезда?" width={560}>
        <p className="text-muted" style={{ fontSize: 13, marginBottom: 16 }}>
          ⭐ Звезда заменит выбранную букву в слове. <strong style={{ color: "var(--coral)" }}>−1 очко</strong> за каждую звезду.
        </p>
        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(8, 1fr)",
          gap: 8,
        }}>
          {"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ".split("").map(letter => (
            <button key={letter} onClick={() => chooseStarLetter(letter)} style={{
              aspectRatio: "1", border: "none",
              background: "white", color: "var(--ink-1)",
              fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 22,
              borderRadius: 10, cursor: "pointer",
              boxShadow: "0 3px 0 rgba(0,0,0,0.15)",
              transition: "transform 80ms",
            }} onMouseDown={e => e.currentTarget.style.transform = "translateY(2px)"}
               onMouseUp={e => e.currentTarget.style.transform = ""}
               onMouseLeave={e => e.currentTarget.style.transform = ""}>
              {letter}
            </button>
          ))}
        </div>
        <div className="row" style={{ justifyContent: "flex-end", marginTop: 16 }}>
          <button className="btn btn-ghost btn-sm" onClick={() => setStarPickerIdx(null)}>Отмена</button>
        </div>
      </Modal>
    </div>
  );
}

Object.assign(window, { GameScreen });
