// screens-lobby.jsx - 멀티플레이 로비 화면

function LobbyScreen({ user, config, onConfigChange, onGameStart, onBack, onCoopMode, initialRoomId, initialIsHost, breakpoint }) {
  // step: 'select' | 'create' | 'waiting' | 'matching' | 'browse'
  const { isDesktop, isShortScreen } = breakpoint || {};
  const [step, setStep] = React.useState(initialRoomId ? 'waiting' : 'select');
  const [roomTitle, setRoomTitle] = React.useState('');
  const [roomPassword, setRoomPassword] = React.useState('');
  const [roomId, setRoomId] = React.useState(initialRoomId || '');
  const [roomData, setRoomData] = React.useState(null);
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [isHost, setIsHost] = React.useState(initialIsHost || false);
  const [cleanupFn, setCleanupFn] = React.useState(null);
  const [chatMessages, setChatMessages] = React.useState([]);
  const [chatInput, setChatInput] = React.useState('');
  const [chatVisible, setChatVisible] = React.useState(true);
  const [lobbyTab, setLobbyTab] = React.useState('waiting');
  const [allRooms, setAllRooms] = React.useState([]);
  const [passwordPrompt, setPasswordPrompt] = React.useState(null); // { roomId, hostName }
  const [passwordInput, setPasswordInput] = React.useState('');
  const unsubscribeRef = React.useRef(null);
  const chatUnsubRef = React.useRef(null);
  const browseUnsubRef = React.useRef(null);
  const chatBottomRef = React.useRef(null);
  const hasJoinedRef = React.useRef(!!initialRoomId);

  const userId = user ? user.uid : null;
  const displayName = user ? (user.displayName || user.name || '플레이어') : '플레이어';

  // 로비 내부 스텝 전환 (히스토리에 추가)
  const goToStep = (nextStep) => {
    if (nextStep !== 'matching') {
      window.history.pushState({ screen: 'lobby', step: nextStep }, '');
    }
    setStep(nextStep);
  };

  React.useEffect(() => {
    if (initialRoomId) {
      listenToRoom(initialRoomId);
      listenToChat(initialRoomId);
    }

    // 로비 내부 뒤로가기 처리
    const handlePop = (e) => {
      const state = e.state || {};
      if (state.screen === 'lobby' && state.step) {
        if (state.step === 'waiting') {
          // waiting으로 뒤로가기 시 방 나가기
          handleLeave();
        } else {
          setStep(state.step);
          setError('');
        }
      } else if (state.screen !== 'lobby') {
        // 로비 밖으로 나가는 경우 onBack 호출
        onBack();
      }
    };

    window.addEventListener('popstate', handlePop);
    return () => {
      window.removeEventListener('popstate', handlePop);
      if (unsubscribeRef.current) {
        unsubscribeRef.current();
      }
    };
  }, []);

  const listenToChat = (rid) => {
    if (chatUnsubRef.current) chatUnsubRef.current();
    chatUnsubRef.current = window.listenChat(rid, (msgs) => {
      setChatMessages(msgs);
      setTimeout(() => {
        if (chatBottomRef.current) chatBottomRef.current.scrollIntoView({ behavior: 'smooth' });
      }, 50);
    });
  };

  const listenToRoom = (rid) => {
    if (unsubscribeRef.current) {
      unsubscribeRef.current();
    }
    const unsub = window.listenRoom(rid, (data) => {
      if (!data) {
        setError('방이 사라졌습니다.');
        setStep('select');
        return;
      }

      // 강퇴 감지: 이미 방에 입장한 상태에서 내 uid가 사라진 경우
      const players = data.players || {};
      if (hasJoinedRef.current && userId && !players[userId]) {
        if (unsubscribeRef.current) { unsubscribeRef.current(); unsubscribeRef.current = null; }
        if (chatUnsubRef.current) { chatUnsubRef.current(); chatUnsubRef.current = null; }
        hasJoinedRef.current = false;
        setRoomData(null);
        setRoomId('');
        setIsHost(false);
        setChatMessages([]);
        setError('방장에 의해 강퇴되었습니다.');
        setStep('select');
        return;
      }
      if (userId && players[userId]) hasJoinedRef.current = true;

      // 호스트 이양 감지: Firebase의 host 필드가 나로 바뀐 경우
      if (userId && data.host === userId) {
        setIsHost(true);
      }

      setRoomData(data);

      if (data.status === 'playing' && data.boardData) {
        // 게스트는 boardData를 받아서 게임 시작
        const players = data.players || {};
        const meIsHost = data.host === userId;
        if (!meIsHost) {
          if (unsubscribeRef.current) {
            unsubscribeRef.current();
            unsubscribeRef.current = null;
          }
          onGameStart({
            roomId: rid,
            players: players,
            boardData: data.boardData,
            isHost: false,
            userId: userId
          });
        }
      }

      if (data.status === 'finished') {
        if (unsubscribeRef.current) {
          unsubscribeRef.current();
          unsubscribeRef.current = null;
        }
      }
    });
    unsubscribeRef.current = unsub;
  };

  const handleCreateRoom = async () => {
    if (!userId) { setError('로그인 정보가 없습니다. 새로고침 후 다시 시도해주세요.'); return; }
    setLoading(true);
    setError('');
    try {
      const pw = roomPassword.trim();
      const title = roomTitle.trim() || `${displayName}의 방`;
      const isPublic = !pw;
      const { roomId: rid, cleanup } = await window.createRoom(config, isPublic, userId, displayName, null, pw || null, title);
      setRoomId(rid);
      setIsHost(true);
      setCleanupFn(() => cleanup);
      hasJoinedRef.current = true;
      listenToRoom(rid);
      listenToChat(rid);
      goToStep('waiting');
    } catch (e) {
      setError(e.message || '방 생성에 실패했습니다.');
    } finally {
      setLoading(false);
    }
  };

  const handleRandomMatch = async () => {
    if (!userId) { setError('로그인 정보가 없습니다. 새로고침 후 다시 시도해주세요.'); return; }
    setStep('matching');
    setError('');
    try {
      const { roomId: rid, isHost: iAmHost, cleanup } = await window.findOrCreatePublicRoom(config, userId, displayName);
      setRoomId(rid);
      setIsHost(iAmHost);
      setCleanupFn(() => cleanup);
      hasJoinedRef.current = true;
      listenToRoom(rid);
      listenToChat(rid);
      goToStep('waiting');
    } catch (e) {
      setError(e.message || '매칭에 실패했습니다.');
      setStep('select');
    }
  };

  const handleStartGame = async () => {
    if (!isHost || !roomId) return;
    const players = roomData ? (roomData.players || {}) : {};
    if (Object.keys(players).length < 2) {
      setError('2명 이상이어야 게임을 시작할 수 있습니다.');
      return;
    }

    setLoading(true);
    setError('');
    try {
      let boardData;
      if (config.seedType === 'perfect') {
        boardData = SeedGenerator.perfectGen(config.rows, config.cols);
      } else {
        boardData = SeedGenerator.randomGen(config.rows, config.cols);
      }

      // 3초 카운트다운 (모든 플레이어에게 broadcast)
      await window.setRoomCountdown(roomId, 3);
      await new Promise(resolve => {
        let count = 3;
        const iv = setInterval(async () => {
          count--;
          if (count > 0) {
            await window.setRoomCountdown(roomId, count);
          } else {
            clearInterval(iv);
            await window.setRoomCountdown(roomId, null);
            resolve();
          }
        }, 1000);
      });

      await window.startMultiGame(roomId, boardData);

      if (unsubscribeRef.current) {
        unsubscribeRef.current();
        unsubscribeRef.current = null;
      }

      onGameStart({
        roomId: roomId,
        players: players,
        boardData: boardData,
        isHost: true,
        userId: userId
      });
    } catch (e) {
      setError(e.message || '게임 시작에 실패했습니다.');
      setLoading(false);
    }
  };

  const handleLeave = async () => {
    hasJoinedRef.current = false;
    if (roomId && userId) {
      try {
        await window.leaveRoom(roomId, userId, isHost);
      } catch (e) {
        console.error('leaveRoom error:', e);
      }
    }
    if (unsubscribeRef.current) {
      unsubscribeRef.current();
      unsubscribeRef.current = null;
    }
    if (chatUnsubRef.current) {
      chatUnsubRef.current();
      chatUnsubRef.current = null;
    }
    if (browseUnsubRef.current) {
      browseUnsubRef.current();
      browseUnsubRef.current = null;
    }
    if (cleanupFn) cleanupFn();
    setRoomId('');
    setRoomData(null);
    setIsHost(false);
    setChatMessages([]);
    setChatInput('');
    setRoomTitle('');
    setRoomPassword('');
    setPasswordPrompt(null);
    setStep('select');
  };

  const copyRoomCode = () => {
    if (navigator.clipboard) {
      navigator.clipboard.writeText(roomId);
    }
  };

  const cardStyle = {
    width: '100%', maxWidth: 480,
    background: 'var(--paper-warm)',
    borderRadius: 24, padding: 36,
    border: '1.5px solid var(--ink)',
    boxShadow: '6px 6px 0 var(--ink)',
    display: 'flex', flexDirection: 'column', gap: 20
  };

  const sectionTitle = {
    fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 700,
    color: 'var(--ink)', marginBottom: 4
  };

  const labelStyle = {
    fontSize: 13, fontWeight: 600, color: 'var(--ink-soft)',
    letterSpacing: '0.04em', marginBottom: 6, display: 'block'
  };

  const inputStyle = {
    width: '100%', padding: '14px 16px',
    borderRadius: 12, border: '1.5px solid var(--hairline)',
    fontFamily: 'var(--font-body)', fontSize: 16,
    background: 'var(--paper)', color: 'var(--ink)',
    outline: 'none', boxSizing: 'border-box'
  };

  const segmentBase = {
    flex: 1, padding: '12px 0', borderRadius: 10,
    border: '1.5px solid var(--hairline)',
    cursor: 'pointer', fontFamily: 'var(--font-body)',
    fontSize: 14, fontWeight: 600, transition: 'all 0.15s'
  };

  if (step === 'select') {
    return (
      <div style={{
        width: '100%', height: '100%', display: 'flex',
        alignItems: 'center', justifyContent: 'center',
        background: 'var(--paper)', fontFamily: 'var(--font-body)',
        flexDirection: 'column', gap: 16
      }}>
        <div style={cardStyle}>
          <div>
            <div style={sectionTitle}>👥 같이 따기</div>
            <div style={{ fontSize: 14, color: 'var(--ink-mute)', lineHeight: 1.6 }}>
              친구와 함께, 또는 낯선 사람과 경쟁하세요!
            </div>
          </div>

          {error && (
            <div style={{
              padding: '12px 16px', background: '#fff0f0', borderRadius: 10,
              border: '1px solid #ffcccc', color: '#cc0000', fontSize: 14
            }}>{error}</div>
          )}

          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <window.PrimaryButton
              variant="primary"
              icon={<span style={{ fontSize: 20 }}>🏠</span>}
              onClick={() => goToStep('create')}
            >
              방 만들기
            </window.PrimaryButton>
            <window.PrimaryButton
              variant="secondary"
              icon={<span style={{ fontSize: 20 }}>🔍</span>}
              onClick={() => {
                if (browseUnsubRef.current) browseUnsubRef.current();
                browseUnsubRef.current = window.listenRooms(setAllRooms);
                goToStep('browse');
              }}
            >
              방 목록 보기
            </window.PrimaryButton>
            <window.PrimaryButton
              variant="dark"
              icon={<span style={{ fontSize: 20 }}>🎲</span>}
              onClick={handleRandomMatch}
            >
              랜덤 매칭
            </window.PrimaryButton>
            {onCoopMode && (
              <window.PrimaryButton
                variant="secondary"
                icon={<span style={{ fontSize: 20 }}>🤝</span>}
                onClick={onCoopMode}
              >
                협력 모드
              </window.PrimaryButton>
            )}
          </div>

          <button onClick={onBack} style={{
            background: 'transparent', border: 'none',
            color: 'var(--ink-mute)', fontSize: 14, cursor: 'pointer',
            textDecoration: 'underline', padding: '4px 0'
          }}>← 메인으로</button>
        </div>
      </div>
    );
  }

  if (step === 'create') {
    return (
      <div style={{
        width: '100%', height: '100%', display: 'flex',
        alignItems: 'center', justifyContent: 'center',
        background: 'var(--paper)', fontFamily: 'var(--font-body)',
        overflowY: 'auto', padding: '20px 0'
      }}>
        <div style={cardStyle}>
          <div style={sectionTitle}>🏠 방 만들기</div>

          {error && (
            <div style={{
              padding: '12px 16px', background: '#fff0f0', borderRadius: 10,
              border: '1px solid #ffcccc', color: '#cc0000', fontSize: 14
            }}>{error}</div>
          )}

          {/* 시간 모드 */}
          <div>
            <span style={labelStyle}>시간 모드</span>
            <div style={{ display: 'flex', gap: 8 }}>
              {[['120', '2분'], ['infinite', '무한']].map(([val, label]) => (
                <button
                  key={val}
                  onClick={() => onConfigChange('timeMode', val)}
                  style={{
                    ...segmentBase,
                    background: config.timeMode === val ? 'var(--ink)' : 'var(--paper)',
                    color: config.timeMode === val ? '#fff' : 'var(--ink)'
                  }}
                >{label}</button>
              ))}
            </div>
          </div>

          {/* 보드 크기 */}
          <div>
            <span style={labelStyle}>보드 크기</span>
            <div style={{ display: 'flex', gap: 8 }}>
              {[
                { cols: 17, rows: 10, label: '17×10' },
                { cols: 14, rows: 8, label: '14×8' },
                { cols: 10, rows: 6, label: '10×6' }
              ].map(({ cols, rows, label }) => (
                <button
                  key={label}
                  onClick={() => { onConfigChange('cols', cols); onConfigChange('rows', rows); }}
                  style={{
                    ...segmentBase,
                    background: config.cols === cols && config.rows === rows ? 'var(--ink)' : 'var(--paper)',
                    color: config.cols === cols && config.rows === rows ? '#fff' : 'var(--ink)'
                  }}
                >{label}</button>
              ))}
            </div>
          </div>

          {/* 씨앗 타입 */}
          <div>
            <span style={labelStyle}>보드 타입</span>
            <div style={{ display: 'flex', gap: 8 }}>
              {[['random', '랜덤'], ['perfect', '퍼펙트']].map(([val, label]) => (
                <button
                  key={val}
                  onClick={() => onConfigChange('seedType', val)}
                  style={{
                    ...segmentBase,
                    background: config.seedType === val ? 'var(--ink)' : 'var(--paper)',
                    color: config.seedType === val ? '#fff' : 'var(--ink)'
                  }}
                >{label}</button>
              ))}
            </div>
          </div>

          {/* 클리어 타입 */}
          <div>
            <span style={labelStyle}>클리어 조건</span>
            <div style={{ display: 'flex', gap: 8 }}>
              {[['original', '오리지널(10)'], ['multiples', '10의 배수']].map(([val, label]) => (
                <button
                  key={val}
                  onClick={() => onConfigChange('clearType', val)}
                  style={{
                    ...segmentBase,
                    background: config.clearType === val ? 'var(--ink)' : 'var(--paper)',
                    color: config.clearType === val ? '#fff' : 'var(--ink)',
                    fontSize: 13
                  }}
                >{label}</button>
              ))}
            </div>
          </div>

          {/* 방 제목 */}
          <div>
            <span style={labelStyle}>방 제목</span>
            <input
              style={inputStyle}
              type="text"
              maxLength={30}
              placeholder={`${displayName}의 방`}
              value={roomTitle}
              onChange={(e) => setRoomTitle(e.target.value)}
            />
          </div>

          {/* 비밀번호 */}
          <div>
            <span style={labelStyle}>비밀번호 (선택) — 입력하면 🔒 비밀방</span>
            <input
              style={inputStyle}
              type="text"
              maxLength={20}
              placeholder="비워두면 공개방"
              value={roomPassword}
              onChange={(e) => setRoomPassword(e.target.value)}
            />
          </div>

          <window.PrimaryButton
            variant="primary"
            onClick={handleCreateRoom}
            disabled={loading}
          >
            {loading ? '생성 중...' : '방 만들기'}
          </window.PrimaryButton>

          <button onClick={() => { setError(''); goToStep('select'); }} style={{
            background: 'transparent', border: 'none',
            color: 'var(--ink-mute)', fontSize: 14, cursor: 'pointer',
            textDecoration: 'underline', padding: '4px 0'
          }}>← 뒤로</button>
        </div>
      </div>
    );
  }

  if (step === 'browse') {
    const handleJoinPublicRoom = async (rid, pw) => {
      if (!userId) return;
      setLoading(true);
      setError('');
      try {
        const { config: roomConfig, cleanup } = await window.joinRoom(rid, userId, displayName, pw || null);
        if (onConfigChange) Object.entries(roomConfig).forEach(([k, v]) => onConfigChange(k, v));
        setRoomId(rid);
        setIsHost(false);
        setCleanupFn(() => cleanup);
        hasJoinedRef.current = true;
        listenToRoom(rid);
        listenToChat(rid);
        if (browseUnsubRef.current) { browseUnsubRef.current(); browseUnsubRef.current = null; }
        setPasswordPrompt(null);
        goToStep('waiting');
      } catch (e) {
        setError(e.message || '입장에 실패했습니다.');
      } finally {
        setLoading(false);
      }
    };

    const modeLabel = { '120': '2분', '60': '1분', 'infinite': '무한' };

    return (
      <div style={{
        width: '100%', height: '100%', display: 'flex',
        alignItems: 'center', justifyContent: 'center',
        background: 'var(--paper)', fontFamily: 'var(--font-body)',
        padding: '20px', boxSizing: 'border-box'
      }}>
        <div style={{ ...cardStyle, maxWidth: 560, width: '100%', maxHeight: '90vh', overflow: 'auto' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={sectionTitle}>🔍 공개 방 목록</div>
            <button
              onClick={() => {
                if (browseUnsubRef.current) browseUnsubRef.current();
                browseUnsubRef.current = window.listenRooms(setAllRooms);
              }}
              style={{ background: 'none', border: '1.5px solid var(--hairline)', borderRadius: 8, padding: '6px 12px', cursor: 'pointer', fontSize: 13, color: 'var(--ink-mute)' }}
            >↺ 새로고침</button>
          </div>

          {error && (
            <div style={{ padding: '12px 16px', background: '#fff0f0', borderRadius: 10, border: '1px solid #ffcccc', color: '#cc0000', fontSize: 14 }}>{error}</div>
          )}

          {allRooms.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '40px 0', color: 'var(--ink-mute)', fontSize: 15 }}>
              <div style={{ fontSize: 40, marginBottom: 12 }}>🍎</div>
              현재 대기 중인 방이 없어요
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {allRooms.map(room => (
                <div key={room.roomId} style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  padding: '16px 18px', borderRadius: 14,
                  background: 'var(--paper)', border: '1.5px solid var(--hairline)',
                  gap: 12
                }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                      <span style={{ fontSize: 16 }}>{room.hasPassword ? '🔒' : '🌐'}</span>
                      <span style={{ fontWeight: 700, fontSize: 15, color: 'var(--ink)' }}>
                        {room.title || `${room.hostName}의 방`}
                      </span>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                      <span style={{ fontFamily: 'var(--font-num)', fontSize: 13, color: 'var(--ink-mute)', letterSpacing: '0.06em' }}>{room.roomId}</span>
                      <span style={{ fontSize: 12, color: 'var(--ink-mute)', background: 'var(--paper-dark)', borderRadius: 6, padding: '2px 7px' }}>
                        👑 {room.hostName}
                      </span>
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--ink-mute)', display: 'flex', gap: 8 }}>
                      <span>⏱ {modeLabel[room.config.timeMode] || room.config.timeMode}</span>
                      <span>📐 {room.config.cols}×{room.config.rows}</span>
                      <span>🎯 {room.config.clearType === 'original' ? '오리지널' : '10배수'}</span>
                      <span>👥 {room.playerCount}/10</span>
                    </div>
                  </div>
                  <button
                    onClick={() => {
                      if (room.playerCount >= 10) return;
                      if (room.hasPassword) {
                        setPasswordPrompt({ roomId: room.roomId, hostName: room.hostName });
                        setPasswordInput('');
                        setError('');
                      } else {
                        handleJoinPublicRoom(room.roomId);
                      }
                    }}
                    disabled={loading || room.playerCount >= 10}
                    style={{
                      padding: '10px 18px', borderRadius: 10, border: 'none',
                      background: room.playerCount >= 10 ? 'var(--hairline)' : room.hasPassword ? 'var(--gold)' : 'var(--leaf)',
                      color: room.hasPassword && room.playerCount < 10 ? 'var(--ink)' : '#fff',
                      fontWeight: 700, fontSize: 14,
                      cursor: room.playerCount >= 10 ? 'default' : 'pointer',
                      flexShrink: 0
                    }}
                  >{room.playerCount >= 10 ? '꽉 참' : room.hasPassword ? '🔑 입장' : '입장'}</button>
                </div>
              ))}
            </div>
          )}

          <button onClick={() => {
            if (browseUnsubRef.current) { browseUnsubRef.current(); browseUnsubRef.current = null; }
            goToStep('select');
          }} style={{
            background: 'transparent', border: 'none',
            color: 'var(--ink-mute)', fontSize: 14, cursor: 'pointer',
            textDecoration: 'underline', padding: '4px 0'
          }}>← 뒤로</button>
        </div>

        {/* 비밀번호 모달 */}
        {passwordPrompt && (
          <div style={{
            position: 'fixed', inset: 0, zIndex: 1000,
            background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center',
            backdropFilter: 'blur(4px)'
          }}>
            <div style={{
              background: 'var(--paper-warm)', borderRadius: 20, padding: 28,
              border: '1.5px solid var(--ink)', boxShadow: '6px 6px 0 var(--ink)',
              width: 320, display: 'flex', flexDirection: 'column', gap: 16
            }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 700 }}>
                🔒 비밀방 입장
              </div>
              <div style={{ fontSize: 13, color: 'var(--ink-mute)' }}>
                👑 {passwordPrompt.hostName}의 방 · {passwordPrompt.roomId}
              </div>
              {error && <div style={{ padding: '10px 14px', background: '#fff0f0', borderRadius: 10, border: '1px solid #ffcccc', color: '#cc0000', fontSize: 13 }}>{error}</div>}
              <input
                style={inputStyle}
                type="text"
                placeholder="비밀번호 입력"
                value={passwordInput}
                onChange={(e) => setPasswordInput(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter') handleJoinPublicRoom(passwordPrompt.roomId, passwordInput); }}
                autoFocus
              />
              <div style={{ display: 'flex', gap: 10 }}>
                <button
                  onClick={() => handleJoinPublicRoom(passwordPrompt.roomId, passwordInput)}
                  disabled={loading || !passwordInput.trim()}
                  style={{
                    flex: 1, padding: '12px', borderRadius: 12, border: 'none',
                    background: passwordInput.trim() ? 'var(--leaf)' : 'var(--hairline)',
                    color: '#fff', fontWeight: 700, fontSize: 15, cursor: passwordInput.trim() ? 'pointer' : 'default'
                  }}
                >{loading ? '입장 중...' : '입장'}</button>
                <button
                  onClick={() => { setPasswordPrompt(null); setPasswordInput(''); setError(''); }}
                  style={{ flex: 1, padding: '12px', borderRadius: 12, border: '1.5px solid var(--hairline)', background: 'var(--paper)', fontWeight: 700, fontSize: 15, cursor: 'pointer', color: 'var(--ink-soft)' }}
                >취소</button>
              </div>
            </div>
          </div>
        )}
      </div>
    );
  }

  if (step === 'matching') {
    return (
      <div style={{
        width: '100%', height: '100%', display: 'flex',
        alignItems: 'center', justifyContent: 'center',
        background: 'var(--paper)', fontFamily: 'var(--font-body)',
        flexDirection: 'column', gap: 24
      }}>
        <div style={{ fontSize: 48 }}>🎲</div>
        <div style={{
          fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 700,
          color: 'var(--ink)', animation: 'pulse 1.5s ease-in-out infinite'
        }}>매칭 중...</div>
        <div style={{ fontSize: 14, color: 'var(--ink-mute)' }}>공개 방을 탐색하고 있습니다</div>
        {error && (
          <div style={{
            padding: '12px 16px', background: '#fff0f0', borderRadius: 10,
            border: '1px solid #ffcccc', color: '#cc0000', fontSize: 14
          }}>{error}</div>
        )}
      </div>
    );
  }

  if (step === 'waiting') {
    const players = roomData ? (roomData.players || {}) : {};
    const playerList = Object.entries(players).sort((a, b) => a[1].joinedAt - b[1].joinedAt);
    const hostId = roomData ? roomData.host : null;
    const nonHostPlayers = playerList.filter(([uid]) => uid !== hostId);
    const allReady = nonHostPlayers.length > 0 && nonHostPlayers.every(([, p]) => p.ready === true);
    const canStart = isHost && playerList.length >= 2 && allReady;

    const handleKick = async (targetUid) => {
      if (!isHost || !roomId) return;
      try {
        await window.kickPlayer(roomId, targetUid);
      } catch (e) {
        console.error('kick error:', e);
      }
    };

    const handleReadyToggle = async () => {
      const myReady = players[userId]?.ready || false;
      try {
        await window.setPlayerReady(roomId, userId, !myReady);
      } catch (e) {
        console.error('ready error:', e);
      }
    };

    const handleSendChat = async () => {
      if (!chatInput.trim() || !roomId) return;
      const text = chatInput;
      setChatInput('');
      await window.sendChatMessage(roomId, userId, displayName, text);
    };

    const handleChatKey = (e) => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        handleSendChat();
      }
    };

    const formatTime = (ts) => {
      const d = new Date(ts);
      return `${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;
    };

    const countdown = roomData ? roomData.countdown : null;

    return (
      <div style={{
        width: '100%', height: '100%', display: 'flex', flexDirection: 'column',
        background: 'var(--paper)', fontFamily: 'var(--font-body)',
        position: 'relative', boxSizing: 'border-box'
      }}>

        {/* 카운트다운 오버레이 */}
        {countdown > 0 && (
          <div style={{
            position: 'absolute', inset: 0, zIndex: 300,
            background: 'rgba(27,36,16,0.85)',
            display: 'flex', flexDirection: 'column',
            alignItems: 'center', justifyContent: 'center',
            backdropFilter: 'blur(6px)'
          }}>
            <div style={{
              fontSize: 13, fontFamily: 'var(--font-mono)', color: 'rgba(255,255,255,0.65)',
              letterSpacing: '0.25em', textTransform: 'uppercase', marginBottom: 20
            }}>
              게임 시작까지
            </div>
            <div key={countdown} style={{
              fontFamily: 'var(--font-num)', fontSize: 140, fontWeight: 900,
              color: '#fff', lineHeight: 1,
              animation: 'countdownPop 0.95s ease-out forwards'
            }}>
              {countdown}
            </div>
          </div>
        )}

        {isDesktop && !isShortScreen ? (
          /* 데스크탑: 기존 2열 레이아웃 */
          <div style={{
            flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
            gap: 20, padding: '20px', overflow: 'hidden'
          }}>
            {/* 왼쪽: 대기실 패널 */}
            <div style={{ ...cardStyle, maxWidth: 460, flex: '0 0 auto', alignSelf: 'center' }}>
              <div>
                <div style={sectionTitle}>🏡 대기실</div>
                <div style={{ fontSize: 13, color: 'var(--ink-mute)' }}>
                  {isHost ? '게스트를 기다리는 중...' : '호스트가 게임을 시작할 때까지 대기하세요.'}
                </div>
              </div>

              {/* 방 코드 */}
              <div style={{
                background: 'var(--paper)', borderRadius: 16,
                border: '2px dashed var(--hairline)', padding: '20px 24px',
                display: 'flex', alignItems: 'center', justifyContent: 'space-between'
              }}>
                <div>
                  <div style={{ fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '0.08em', marginBottom: 4 }}>방 코드</div>
                  <div style={{
                    fontFamily: 'var(--font-num)', fontSize: 36, fontWeight: 800,
                    color: 'var(--ink)', letterSpacing: '0.1em'
                  }}>{roomId}</div>
                </div>
                <button onClick={copyRoomCode} style={{
                  padding: '10px 18px', borderRadius: 10,
                  background: 'var(--leaf)', color: '#fff',
                  border: 'none', cursor: 'pointer', fontWeight: 700, fontSize: 13
                }}>복사</button>
              </div>

              {error && (
                <div style={{
                  padding: '12px 16px', background: '#fff0f0', borderRadius: 10,
                  border: '1px solid #ffcccc', color: '#cc0000', fontSize: 14
                }}>{error}</div>
              )}

              {/* 참가자 목록 */}
              <div>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-soft)', marginBottom: 10 }}>
                  참가자 ({playerList.length}/10)
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {playerList.map(([uid, p]) => (
                    <div key={uid} style={{
                      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                      padding: '12px 16px', borderRadius: 12,
                      background: uid === userId ? 'rgba(27,67,50,0.08)' : 'var(--paper)',
                      border: '1px solid var(--hairline)'
                    }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <span style={{ fontSize: 18 }}>{uid === hostId ? '👑' : '🍎'}</span>
                        <div>
                          <span style={{
                            fontWeight: uid === userId ? 700 : 500,
                            color: uid === userId ? 'var(--leaf)' : 'var(--ink)',
                            fontSize: 15
                          }}>
                            {p.displayName}
                            {uid === userId && <span style={{ fontSize: 11, color: 'var(--ink-mute)', marginLeft: 6 }}>(나)</span>}
                          </span>
                          {(p.roundsPlayed > 0) && (
                            <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 1 }}>
                              {p.wins || 0}승 · {p.roundsPlayed}회
                            </div>
                          )}
                        </div>
                      </div>
                      {/* 레디 상태 표시 (호스트 제외) */}
                      {uid !== hostId && (
                        <span style={{
                          fontSize: 11, fontWeight: 700, padding: '3px 8px', borderRadius: 6,
                          background: p.ready ? '#e8f5e9' : '#fff3e0',
                          color: p.ready ? '#2e7d32' : '#e65100',
                          marginRight: 4, flexShrink: 0
                        }}>
                          {p.ready ? '✓ 레디' : '대기 중'}
                        </span>
                      )}
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span style={{
                          fontSize: 11, color: 'var(--ink-mute)',
                          background: 'var(--paper-dark)', borderRadius: 6, padding: '2px 8px'
                        }}>
                          {uid === hostId ? '호스트' : '게스트'}
                        </span>
                        {isHost && uid !== userId && (
                          <button
                            onClick={() => handleKick(uid)}
                            title="강퇴"
                            style={{
                              padding: '2px 10px', borderRadius: 6, border: '1px solid #ffcccc',
                              background: '#fff0f0', color: '#cc0000',
                              fontWeight: 700, fontSize: 11, cursor: 'pointer', lineHeight: 1.6
                            }}
                          >강퇴</button>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {isHost && (
                <window.PrimaryButton
                  variant="primary"
                  onClick={handleStartGame}
                  disabled={loading || !canStart}
                  icon={<span style={{ fontSize: 20 }}>🍎</span>}
                >
                  {loading ? '시작 중...' : playerList.length < 2 ? '2명 이상 필요' : !allReady ? '모두 레디 대기 중...' : '게임 시작!'}
                </window.PrimaryButton>
              )}

              {!isHost && (
                <button
                  onClick={handleReadyToggle}
                  style={{
                    padding: '14px', borderRadius: 12, border: 'none', cursor: 'pointer',
                    background: players[userId]?.ready ? '#e8f5e9' : 'var(--leaf)',
                    color: players[userId]?.ready ? '#2e7d32' : '#fff',
                    fontWeight: 700, fontSize: 16, width: '100%',
                    border: players[userId]?.ready ? '2px solid #a5d6a7' : '2px solid transparent',
                    transition: 'all 0.15s'
                  }}
                >
                  {players[userId]?.ready ? '✓ 레디 완료 (취소하려면 클릭)' : '레디하기'}
                </button>
              )}

              <button onClick={handleLeave} style={{
                background: 'transparent', border: 'none',
                color: 'var(--ink-mute)', fontSize: 14, cursor: 'pointer',
                textDecoration: 'underline', padding: '4px 0'
              }}>← 나가기</button>
            </div>

            {/* 오른쪽: 채팅 패널 */}
            <div style={{
              width: chatVisible ? 300 : 52, height: chatVisible ? 520 : 52,
              flexShrink: 0,
              background: 'var(--paper-warm)',
              borderRadius: 24, border: '1.5px solid var(--ink)',
              boxShadow: '6px 6px 0 var(--ink)',
              display: 'flex', flexDirection: 'column',
              overflow: 'hidden', transition: 'width 0.25s, height 0.25s',
              alignSelf: 'center'
            }}>
              {/* 채팅 헤더 */}
              <div style={{
                padding: chatVisible ? '16px 20px' : '14px',
                borderBottom: chatVisible ? '1px solid var(--hairline)' : 'none',
                fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16,
                color: 'var(--ink)', display: 'flex', alignItems: 'center',
                justifyContent: 'space-between', gap: 8, flexShrink: 0
              }}>
                {chatVisible && <span>💬 채팅</span>}
                <button
                  onClick={() => setChatVisible(v => !v)}
                  style={{
                    background: 'none', border: 'none', cursor: 'pointer',
                    fontSize: 18, color: 'var(--ink-mute)', padding: 0,
                    lineHeight: 1, marginLeft: chatVisible ? 'auto' : 0
                  }}
                  title={chatVisible ? '채팅 숨기기' : '채팅 열기'}
                >
                  {chatVisible ? '✕' : '💬'}
                </button>
              </div>

              {/* 메시지 목록 */}
              {chatVisible && <div style={{
                flex: 1, overflowY: 'auto', padding: '12px 16px',
                display: 'flex', flexDirection: 'column', gap: 10
              }}>
                {chatMessages.length === 0 && (
                  <div style={{ color: 'var(--ink-mute)', fontSize: 13, textAlign: 'center', marginTop: 20 }}>
                    아직 메시지가 없어요 👋
                  </div>
                )}
                {chatMessages.map((msg) => {
                  const isMe = msg.userId === userId;
                  return (
                    <div key={msg.id} style={{
                      display: 'flex', flexDirection: 'column',
                      alignItems: isMe ? 'flex-end' : 'flex-start'
                    }}>
                      {!isMe && (
                        <span style={{ fontSize: 11, color: 'var(--ink-mute)', marginBottom: 3, paddingLeft: 4 }}>
                          {msg.displayName}
                        </span>
                      )}
                      <div style={{
                        maxWidth: '85%', padding: '8px 12px', borderRadius: 14,
                        background: isMe ? 'var(--leaf)' : 'var(--paper)',
                        color: isMe ? '#fff' : 'var(--ink)',
                        fontSize: 14, lineHeight: 1.4, wordBreak: 'break-word',
                        border: isMe ? 'none' : '1px solid var(--hairline)',
                        borderBottomRightRadius: isMe ? 4 : 14,
                        borderBottomLeftRadius: isMe ? 14 : 4
                      }}>
                        {msg.text}
                      </div>
                      <span style={{ fontSize: 10, color: 'var(--ink-mute)', marginTop: 3, paddingLeft: 4, paddingRight: 4 }}>
                        {formatTime(msg.timestamp)}
                      </span>
                    </div>
                  );
                })}
                <div ref={chatBottomRef} />
              </div>}

              {/* 입력창 */}
              {chatVisible && <div style={{
                padding: '12px 14px', borderTop: '1px solid var(--hairline)',
                display: 'flex', gap: 8, flexShrink: 0
              }}>
                <input
                  style={{
                    flex: 1, padding: '10px 12px', borderRadius: 10,
                    border: '1.5px solid var(--hairline)',
                    fontFamily: 'var(--font-body)', fontSize: 14,
                    background: 'var(--paper)', color: 'var(--ink)',
                    outline: 'none', boxSizing: 'border-box'
                  }}
                  type="text"
                  maxLength={120}
                  placeholder="메시지 입력..."
                  value={chatInput}
                  onChange={(e) => setChatInput(e.target.value)}
                  onKeyDown={handleChatKey}
                />
                <button
                  onClick={handleSendChat}
                  disabled={!chatInput.trim()}
                  style={{
                    padding: '10px 14px', borderRadius: 10,
                    background: chatInput.trim() ? 'var(--leaf)' : 'var(--hairline)',
                    color: '#fff', border: 'none', cursor: chatInput.trim() ? 'pointer' : 'default',
                    fontWeight: 700, fontSize: 16, transition: 'background 0.15s'
                  }}
                >↑</button>
              </div>}
            </div>
          </div>
        ) : (
          /* 모바일·태블릿: 탭 전환 레이아웃 */
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
            {/* 탭 바 */}
            <div style={{
              display: 'flex', borderBottom: '2px solid var(--hairline)',
              background: 'var(--paper)', flexShrink: 0
            }}>
              <button
                onClick={() => setLobbyTab('waiting')}
                style={{
                  flex: 1, padding: '14px 0', border: 'none', background: 'none', cursor: 'pointer',
                  fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 15,
                  color: lobbyTab === 'waiting' ? 'var(--leaf)' : 'var(--ink-mute)',
                  borderBottom: lobbyTab === 'waiting' ? '2px solid var(--leaf)' : '2px solid transparent',
                  marginBottom: -2
                }}
              >🏡 대기실</button>
              <button
                onClick={() => setLobbyTab('chat')}
                style={{
                  flex: 1, padding: '14px 0', border: 'none', background: 'none', cursor: 'pointer',
                  fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 15,
                  color: lobbyTab === 'chat' ? 'var(--leaf)' : 'var(--ink-mute)',
                  borderBottom: lobbyTab === 'chat' ? '2px solid var(--leaf)' : '2px solid transparent',
                  marginBottom: -2
                }}
              >💬 채팅</button>
            </div>

            {/* 탭 콘텐츠 */}
            <div style={{ flex: 1, overflow: 'auto', padding: '16px' }}>
              {lobbyTab === 'waiting' ? (
                /* 대기실 탭 */
                <div style={{ display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 480, margin: '0 auto' }}>
                  <div>
                    <div style={sectionTitle}>🏡 대기실</div>
                    <div style={{ fontSize: 13, color: 'var(--ink-mute)' }}>
                      {isHost ? '게스트를 기다리는 중...' : '호스트가 게임을 시작할 때까지 대기하세요.'}
                    </div>
                  </div>

                  {/* 방 코드 */}
                  <div style={{
                    background: 'var(--paper-warm)', borderRadius: 16,
                    border: '2px dashed var(--hairline)', padding: '20px 24px',
                    display: 'flex', alignItems: 'center', justifyContent: 'space-between'
                  }}>
                    <div>
                      <div style={{ fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '0.08em', marginBottom: 4 }}>방 코드</div>
                      <div style={{
                        fontFamily: 'var(--font-num)', fontSize: 36, fontWeight: 800,
                        color: 'var(--ink)', letterSpacing: '0.1em'
                      }}>{roomId}</div>
                    </div>
                    <button onClick={copyRoomCode} style={{
                      padding: '10px 18px', borderRadius: 10,
                      background: 'var(--leaf)', color: '#fff',
                      border: 'none', cursor: 'pointer', fontWeight: 700, fontSize: 13
                    }}>복사</button>
                  </div>

                  {error && (
                    <div style={{
                      padding: '12px 16px', background: '#fff0f0', borderRadius: 10,
                      border: '1px solid #ffcccc', color: '#cc0000', fontSize: 14
                    }}>{error}</div>
                  )}

                  {/* 참가자 목록 */}
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-soft)', marginBottom: 10 }}>
                      참가자 ({playerList.length}/10)
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                      {playerList.map(([uid, p]) => (
                        <div key={uid} style={{
                          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                          padding: '12px 16px', borderRadius: 12,
                          background: uid === userId ? 'rgba(27,67,50,0.08)' : 'var(--paper)',
                          border: '1px solid var(--hairline)'
                        }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                            <span style={{ fontSize: 18 }}>{uid === hostId ? '👑' : '🍎'}</span>
                            <div>
                              <span style={{
                                fontWeight: uid === userId ? 700 : 500,
                                color: uid === userId ? 'var(--leaf)' : 'var(--ink)',
                                fontSize: 15
                              }}>
                                {p.displayName}
                                {uid === userId && <span style={{ fontSize: 11, color: 'var(--ink-mute)', marginLeft: 6 }}>(나)</span>}
                              </span>
                              {(p.roundsPlayed > 0) && (
                                <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginTop: 1 }}>
                                  {p.wins || 0}승 · {p.roundsPlayed}회
                                </div>
                              )}
                            </div>
                          </div>
                          {/* 레디 상태 표시 (호스트 제외) */}
                          {uid !== hostId && (
                            <span style={{
                              fontSize: 11, fontWeight: 700, padding: '3px 8px', borderRadius: 6,
                              background: p.ready ? '#e8f5e9' : '#fff3e0',
                              color: p.ready ? '#2e7d32' : '#e65100',
                              marginRight: 4, flexShrink: 0
                            }}>
                              {p.ready ? '✓ 레디' : '대기 중'}
                            </span>
                          )}
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            <span style={{
                              fontSize: 11, color: 'var(--ink-mute)',
                              background: 'var(--paper-dark)', borderRadius: 6, padding: '2px 8px'
                            }}>
                              {uid === hostId ? '호스트' : '게스트'}
                            </span>
                            {isHost && uid !== userId && (
                              <button
                                onClick={() => handleKick(uid)}
                                title="강퇴"
                                style={{
                                  padding: '2px 10px', borderRadius: 6, border: '1px solid #ffcccc',
                                  background: '#fff0f0', color: '#cc0000',
                                  fontWeight: 700, fontSize: 11, cursor: 'pointer', lineHeight: 1.6
                                }}
                              >강퇴</button>
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>

                  {isHost && (
                    <window.PrimaryButton
                      variant="primary"
                      onClick={handleStartGame}
                      disabled={loading || !canStart}
                      icon={<span style={{ fontSize: 20 }}>🍎</span>}
                    >
                      {loading ? '시작 중...' : playerList.length < 2 ? '2명 이상 필요' : !allReady ? '모두 레디 대기 중...' : '게임 시작!'}
                    </window.PrimaryButton>
                  )}

                  {!isHost && (
                    <button
                      onClick={handleReadyToggle}
                      style={{
                        padding: '14px', borderRadius: 12, border: 'none', cursor: 'pointer',
                        background: players[userId]?.ready ? '#e8f5e9' : 'var(--leaf)',
                        color: players[userId]?.ready ? '#2e7d32' : '#fff',
                        fontWeight: 700, fontSize: 16, width: '100%',
                        border: players[userId]?.ready ? '2px solid #a5d6a7' : '2px solid transparent',
                        transition: 'all 0.15s'
                      }}
                    >
                      {players[userId]?.ready ? '✓ 레디 완료 (취소하려면 클릭)' : '레디하기'}
                    </button>
                  )}

                  <button onClick={handleLeave} style={{
                    background: 'transparent', border: 'none',
                    color: 'var(--ink-mute)', fontSize: 14, cursor: 'pointer',
                    textDecoration: 'underline', padding: '4px 0'
                  }}>← 나가기</button>
                </div>
              ) : (
                /* 채팅 탭 */
                <div style={{ display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0 }}>
                  <div style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 10, paddingBottom: 8 }}>
                    {chatMessages.length === 0 && (
                      <div style={{ color: 'var(--ink-mute)', fontSize: 13, textAlign: 'center', marginTop: 32 }}>
                        대기 중 채팅 가능! 👋
                      </div>
                    )}
                    {chatMessages.map((msg) => {
                      const isMe = msg.userId === userId;
                      return (
                        <div key={msg.id} style={{ display: 'flex', flexDirection: 'column', alignItems: isMe ? 'flex-end' : 'flex-start' }}>
                          {!isMe && <span style={{ fontSize: 11, color: 'var(--ink-mute)', marginBottom: 2, paddingLeft: 3 }}>{msg.displayName}</span>}
                          <div style={{
                            maxWidth: '85%', padding: '8px 12px', borderRadius: 14,
                            background: isMe ? 'var(--leaf)' : 'var(--paper-warm)',
                            color: isMe ? '#fff' : 'var(--ink)', fontSize: 14, lineHeight: 1.4,
                            wordBreak: 'break-word',
                            border: isMe ? 'none' : '1px solid var(--hairline)',
                            borderBottomRightRadius: isMe ? 3 : 14, borderBottomLeftRadius: isMe ? 14 : 3
                          }}>{msg.text}</div>
                        </div>
                      );
                    })}
                    <div ref={chatBottomRef} />
                  </div>
                  <div style={{ display: 'flex', gap: 8, paddingTop: 8, borderTop: '1px solid var(--hairline)', flexShrink: 0 }}>
                    <input
                      style={{ flex: 1, padding: '10px 14px', borderRadius: 10, border: '1.5px solid var(--hairline)', fontSize: 14, background: 'var(--paper)', color: 'var(--ink)', outline: 'none', fontFamily: 'var(--font-body)' }}
                      type="text" maxLength={120} placeholder="메시지..."
                      value={chatInput}
                      onChange={(e) => setChatInput(e.target.value)}
                      onKeyDown={handleChatKey}
                    />
                    <button onClick={handleSendChat} disabled={!chatInput.trim()} style={{ padding: '10px 16px', borderRadius: 10, border: 'none', background: chatInput.trim() ? 'var(--leaf)' : 'var(--hairline)', color: '#fff', fontWeight: 700, fontSize: 16, cursor: chatInput.trim() ? 'pointer' : 'default' }}>↑</button>
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    );
  }

  return null;
}

Object.assign(window, { LobbyScreen });
