// Game scene components

function HUD({ score, time, warn, mode, onStyleToggle, onQuit, musicEnabled, onMusicToggle, breakpoint }) {
  const { isMobile, isTablet, isShortScreen } = breakpoint || {};
  const hudPadding = (isMobile || isShortScreen) ? '6px 12px' : isTablet ? '10px 16px' : '12px 20px';
  const scoreFontSize = (isMobile || isShortScreen) ? 22 : isTablet ? 30 : 40;
  const btnPadding = (isMobile || isShortScreen) ? '6px 10px' : isTablet ? '8px 14px' : '10px 18px';
  const btnFontSize = (isMobile || isShortScreen) ? 13 : 15;
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      padding: hudPadding, color: 'var(--ink)', zIndex: 10
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: (isMobile || isShortScreen) ? 12 : 20 }}>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <span style={{ fontSize: 12, color: 'var(--ink-mute)' }}>점수</span>
          <span style={{ fontSize: scoreFontSize, fontFamily: 'var(--font-num)', fontWeight: 800, lineHeight: 1 }}>{score}</span>
        </div>
        <div style={{ width: 1, height: 32, background: 'var(--hairline)' }}/>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <span style={{ fontSize: 12, color: 'var(--ink-mute)' }}>남은 시간</span>
          <span style={{
            fontSize: scoreFontSize, fontFamily: 'var(--font-num)', fontWeight: 800, lineHeight: 1,
            color: warn ? 'var(--apple)' : 'var(--ink)'
          }}>{time}</span>
        </div>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: (isMobile || isShortScreen) ? 12 : 20 }}>
         <button onClick={onMusicToggle} style={{
           padding: btnPadding, borderRadius: 12, border: '1px solid var(--hairline)',
           background: 'var(--paper-warm)', color: 'var(--ink)', cursor: 'pointer',
           fontSize: btnFontSize, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 8
         }}>
           {musicEnabled ? '음악 끄기' : '음악 켜기'}
         </button>
         <button onClick={onStyleToggle} style={{
           padding: btnPadding, borderRadius: 12, border: '1px solid var(--hairline)',
           background: 'var(--paper-warm)', color: 'var(--ink)', cursor: 'pointer',
           fontSize: btnFontSize, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 8
         }}>
           사과 색
         </button>
      </div>
    </div>
  );
}

function GameGrid({ board, cellSize, selection, appleShape }) {
  const GAP = 2;
  const rows = board.length;
  const cols = board[0].length;

  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: `repeat(${cols}, ${cellSize}px)`,
      gridTemplateRows: `repeat(${rows}, ${cellSize}px)`,
      gap: GAP,
      padding: 4,
      background: '#fbfdf7',
      borderRadius: 12,
    }}>
      {board.map((row, r) => row.map((apple, c) => {
        const isSelected = selection && 
          r >= selection.r1 && r <= selection.r2 && 
          c >= selection.c1 && c <= selection.c2;
        
        return (
          <div key={`${r}-${c}`} style={{ position: 'relative' }}>
            {apple > 0 ? (
              <AppleCell 
                n={apple} 
                size={cellSize} 
                shape={appleShape || "realistic"} 
                selected={isSelected} 
              />
            ) : (
              <div style={{ width: cellSize, height: cellSize }} />
            )}
          </div>
        );
      }))}
    </div>
  );
}

function GameScreen({ engine, config, theme, onThemeToggle, customColor, onCustomColorChange,
  appleShape, onAppleShapeChange, onQuit, onFinish, onRestart, musicEnabled, onMusicToggle,
  multiState, breakpoint }) {
  const { isMobile, isTablet, isShortScreen, isUltrawide } = breakpoint || {};
  const [board, setBoard] = React.useState([]);
  const [score, setScore] = React.useState(0);
  const [timeLeft, setTimeLeft] = React.useState(0);
  const [isDragging, setIsDragging] = React.useState(false);
  const [dragStart, setDragStart] = React.useState({ x: 0, y: 0 });
  const [dragEnd, setDragEnd] = React.useState({ x: 0, y: 0 });
  const [selection, setSelection] = React.useState(null);
  const [currentSum, setCurrentSum] = React.useState(0);
  const [floatingTexts, setFloatingTexts] = React.useState([]);
  const [appleSize, setAppleSize] = React.useState(40);
  const [styleModalOpen, setStyleModalOpen] = React.useState(false);
  const [showRestartConfirm, setShowRestartConfirm] = React.useState(false);
  const [multiPlayers, setMultiPlayers] = React.useState(null);
  const multiPlayersRef = React.useRef(null);
  const [chatMessages, setChatMessages] = React.useState([]);
  const [chatInput, setChatInput] = React.useState('');
  const [chatVisible, setChatVisible] = React.useState(!isMobile);
  const chatUnsubRef = React.useRef(null);
  const chatBottomRef = React.useRef(null);
  const containerRef = React.useRef(null);

  React.useEffect(() => {
    if (!multiState) return;
    const unsubPlayers = window.listenPlayers(multiState.roomId, (players) => {
      setMultiPlayers(players);
      multiPlayersRef.current = players;
    });
    const unsubRoom = window.listenRoom(multiState.roomId, (data) => {
      if (data && data.status === 'finished') {
        onFinish(engine ? engine.getScore() : 0, 'timeover', data.players || {});
      }
    });
    if (window.listenChat) {
      chatUnsubRef.current = window.listenChat(multiState.roomId, (msgs) => {
        setChatMessages(msgs);
        setTimeout(() => {
          if (chatBottomRef.current) chatBottomRef.current.scrollIntoView({ behavior: 'smooth' });
        }, 50);
      });
    }
    return () => {
      unsubPlayers();
      unsubRoom();
      if (chatUnsubRef.current) { chatUnsubRef.current(); chatUnsubRef.current = null; }
    };
  }, [multiState]);

  const GAP = 2;
  const PADDING = 4;

  React.useEffect(() => {
    const updateSize = () => {
      if (!containerRef.current) return;
      const parent = containerRef.current.parentElement;
      if (!parent) return;
      const rect = parent.getBoundingClientRect();
      const maxW = rect.width - PADDING * 2;
      const maxH = rect.height - PADDING * 2;
      
      let newSize = Math.min(
        (maxW - (config.cols - 1) * GAP) / config.cols,
        (maxH - (config.rows - 1) * GAP) / config.rows
      );
      
      newSize = Math.max(16, Math.min(newSize, 70));
      setAppleSize(Math.floor(newSize));
    };

    updateSize();
    window.addEventListener('resize', updateSize);
    const timer = setTimeout(updateSize, 50);
    return () => {
      window.removeEventListener('resize', updateSize);
      clearTimeout(timer);
    };
  }, [config.cols, config.rows, chatVisible]);

  React.useEffect(() => {
     if (engine) {
       setBoard([...engine.getBoard().map(r => [...r])]);
       setScore(engine.getScore());
       if (config.timeMode !== 'infinite') {
         setTimeLeft(parseInt(config.timeMode));
       }
     }
  }, [engine]);

  React.useEffect(() => {
    if (config.timeMode === 'infinite') return;
    const timer = setInterval(() => {
      setTimeLeft(prev => {
        if (prev <= 1) {
          clearInterval(timer);
          onFinish(engine.getScore(), 'timeover', multiPlayersRef.current || {});
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
    return () => clearInterval(timer);
  }, [config.timeMode, engine]);

  const updateSelection = (start, end) => {
    const left = Math.min(start.x, end.x);
    const top = Math.min(start.y, end.y);
    const right = Math.max(start.x, end.x);
    const bottom = Math.max(start.y, end.y);

    let r1 = 1000, c1 = 1000, r2 = -1, c2 = -1;
    let found = false;

    const HIT = appleSize * 0.28; // ~56% 히트박스
    for (let r = 0; r < config.rows; r++) {
      for (let c = 0; c < config.cols; c++) {
        const centerX = PADDING + c * (appleSize + GAP) + appleSize / 2;
        const centerY = PADDING + r * (appleSize + GAP) + appleSize / 2;

        if (centerX >= left - HIT && centerX <= right + HIT && centerY >= top - HIT && centerY <= bottom + HIT) {
          r1 = Math.min(r1, r);
          c1 = Math.min(c1, c);
          r2 = Math.max(r2, r);
          c2 = Math.max(c2, c);
          found = true;
        }
      }
    }

    if (found) {
      const sum = engine.getAreaSum(r1, c1, r2, c2);
      setSelection({ r1, c1, r2, c2 });
      setCurrentSum(sum);
    } else {
      setSelection(null);
      setCurrentSum(0);
    }
  };

  const handlePointerDown = (e) => {
    e.currentTarget.setPointerCapture(e.pointerId);
    const rect = containerRef.current.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    setIsDragging(true);
    setDragStart({ x, y });
    setDragEnd({ x, y });
    updateSelection({ x, y }, { x, y });
  };

  const handlePointerMove = (e) => {
    if (!isDragging) return;
    const rect = containerRef.current.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    setDragEnd({ x, y });
    updateSelection(dragStart, { x, y });
  };

  const handlePointerUp = () => {
    if (!isDragging) return;
    setIsDragging(false);

    if (selection) {
      const beforeApples = engine.getRemainingApples();
      if (engine.evaluateSelection(selection.r1, selection.c1, selection.r2, selection.c2, config.clearType)) {
        const removed = beforeApples - engine.getRemainingApples();
        setBoard([...engine.getBoard().map(r => [...r])]);
        setScore(engine.getScore());

        if (multiState && window.updateMultiScore) {
          window.updateMultiScore(multiState.roomId, multiState.userId, engine.getScore());
        }

        // 콤보 메시지 로직 (사용자 요청: 2개 good, 3개 great, 4개 excellent)
        let comboMsg = '';
        if (removed >= 4) comboMsg = 'Excellent!!';
        else if (removed === 3) comboMsg = 'Great!';
        else if (removed === 2) comboMsg = 'Good!';
        
        if (comboMsg) {
          const cW = containerRef.current ? containerRef.current.offsetWidth : 9999;
          const cH = containerRef.current ? containerRef.current.offsetHeight : 9999;
          const newEffect = {
            id: Date.now(),
            text: `${comboMsg} +${removed}`,
            x: Math.max(0, Math.min(dragEnd.x, cW - 120)),
            y: Math.max(30, Math.min(dragEnd.y, cH - 30))
          };
          setFloatingTexts(prev => [...prev, newEffect]);
          setTimeout(() => {
            setFloatingTexts(prev => prev.filter(t => t.id !== newEffect.id));
          }, 800);
        }

        if (engine.getRemainingApples() === 0) {
          if (multiState && config.timeMode === 'infinite' && window.finishMultiGame) {
            window.finishMultiGame(multiState.roomId, multiState.userId);
          }
          onFinish(engine.getScore(), 'clear', multiPlayersRef.current || {});
        } else if (!multiState && !engine.hasAvailableMoves(config.clearType)) {
           const endEffect = {
             id: Date.now() + 1,
             text: `No More Moves!`,
             x: containerRef.current.getBoundingClientRect().width / 2 - 50,
             y: containerRef.current.getBoundingClientRect().height / 2
           };
           setFloatingTexts(prev => [...prev, endEffect]);
           setTimeout(() => onFinish(engine.getScore(), 'nomoves', multiPlayersRef.current || {}), 1500);
        }
      }
    }
    setSelection(null);
    setCurrentSum(0);
  };

  const formatTime = (seconds) => {
    if (config.timeMode === 'infinite') return '∞';
    const m = Math.floor(seconds / 60);
    const s = seconds % 60;
    return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  };

  return (
    <div style={{
      width: '100%', height: '100%',
      background: 'var(--paper)',
      padding: '24px 32px', display: 'flex', flexDirection: 'column', gap: 12,
      fontFamily: 'var(--font-body)', position: 'relative', overflow: 'hidden',
      userSelect: 'none', WebkitUserSelect: 'none', MozUserSelect: 'none', msUserSelect: 'none',
      maxWidth: isUltrawide ? 1600 : '100%',
      margin: isUltrawide ? '0 auto' : undefined,
    }} onPointerUp={handlePointerUp} onPointerLeave={handlePointerUp}>
      
      <HUD
        score={score}
        time={formatTime(timeLeft)}
        warn={timeLeft <= 10 && config.timeMode !== 'infinite'}
        mode={`${config.cols}×${config.rows}`}
        onStyleToggle={() => setStyleModalOpen(!styleModalOpen)}
        onQuit={onQuit}
        musicEnabled={musicEnabled}
        onMusicToggle={onMusicToggle}
        breakpoint={breakpoint}
      />

      {styleModalOpen && (
        <div style={{
          position: 'absolute', top: 90, right: 32, background: 'var(--paper-warm)', padding: 20, 
          borderRadius: 16, border: '1px solid var(--hairline)', boxShadow: '0 10px 30px rgba(0,0,0,0.12)', 
          zIndex: 1000, display: 'flex', flexDirection: 'column', gap: 20, minWidth: 260
        }}>
          
          {/* Shape Selection */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <div style={{ fontWeight: 700, color: 'var(--ink)', fontSize: 14 }}>사과 모양</div>
            <div style={{ display: 'flex', gap: 10 }}>
              <button 
                onClick={() => onAppleShapeChange('realistic')}
                style={{
                  flex: 1, padding: '12px 0', borderRadius: 12, 
                  border: `2px solid ${appleShape === 'realistic' ? 'var(--apple)' : 'var(--hairline)'}`,
                  background: 'var(--paper)', cursor: 'pointer',
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
                  boxShadow: appleShape === 'realistic' ? '0 4px 12px rgba(0,0,0,0.1)' : 'none'
                }}
              >
                <AppleCell n={1} size={36} shape="realistic" leaf={true} />
                <span style={{ fontSize: 13, fontWeight: appleShape === 'realistic' ? 700 : 500, color: 'var(--ink)' }}>사과</span>
              </button>
              <button 
                onClick={() => onAppleShapeChange('round')}
                style={{
                  flex: 1, padding: '12px 0', borderRadius: 12, 
                  border: `2px solid ${appleShape === 'round' ? 'var(--apple)' : 'var(--hairline)'}`,
                  background: 'var(--paper)', cursor: 'pointer',
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
                  boxShadow: appleShape === 'round' ? '0 4px 12px rgba(0,0,0,0.1)' : 'none'
                }}
              >
                <AppleCell n={1} size={36} shape="round" />
                <span style={{ fontSize: 13, fontWeight: appleShape === 'round' ? 700 : 500, color: 'var(--ink)' }}>동그라미</span>
              </button>
            </div>
          </div>

          {/* Color Selection */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <div style={{ fontWeight: 700, color: 'var(--ink)', fontSize: 14 }}>사과 색</div>
            <div style={{ display: 'flex', gap: 10 }}>
              <button 
                onClick={() => onThemeToggle('original')}
                style={{
                  flex: '0 0 auto', padding: '0 12px', height: 44, borderRadius: 12, 
                  border: `2px solid ${theme === 'original' ? '#e8575d' : 'var(--hairline)'}`,
                  background: 'var(--paper)', cursor: 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center'
                }}
              >
                <div style={{ width: 22, height: 22, borderRadius: '50%', background: '#e8575d' }}></div>
              </button>
              <button 
                onClick={() => onThemeToggle('warm')}
                style={{
                  flex: '0 0 auto', padding: '0 12px', height: 44, borderRadius: 12, 
                  border: `2px solid ${theme === 'warm' ? '#d97757' : 'var(--hairline)'}`,
                  background: 'var(--paper)', cursor: 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center'
                }}
              >
                <div style={{ width: 22, height: 22, borderRadius: '50%', background: '#d97757' }}></div>
              </button>
              <div 
                style={{
                  flex: '0 0 auto', padding: '0 12px', height: 44, borderRadius: 12, 
                  border: `2px solid ${theme === 'custom' ? customColor : 'var(--hairline)'}`,
                  background: 'var(--paper)', cursor: 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative'
                }}
                onClick={() => onThemeToggle('custom')}
              >
                <div style={{
                  width: 22, height: 22, borderRadius: '50%',
                  background: 'conic-gradient(#ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)',
                  position: 'relative', overflow: 'hidden'
                }}>
                  <input 
                    type="color" 
                    value={customColor} 
                    onChange={(e) => {
                      onCustomColorChange(e.target.value);
                      onThemeToggle('custom');
                    }}
                    style={{ position: 'absolute', top: -10, left: -10, width: 44, height: 44, opacity: 0, cursor: 'pointer' }}
                  />
                </div>
              </div>
            </div>
          </div>

          <button onClick={() => setStyleModalOpen(false)} style={{
            marginTop: 4, padding: '12px', background: 'var(--ink)', color: '#fff', 
            borderRadius: 12, border: 'none', cursor: 'pointer', fontWeight: 700, fontSize: 15
          }}>닫기</button>
        </div>
      )}

      <div style={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center', overflow: 'auto', position: 'relative',
        marginRight: multiState && chatVisible && !isMobile ? 280 : 0 }}>
        <div
          ref={containerRef}
          onPointerDown={handlePointerDown}
          onPointerMove={handlePointerMove}
          style={{ position: 'relative', touchAction: 'none', overflow: 'hidden' }}
        >
           {board.length > 0 && <GameGrid board={board} cellSize={appleSize} selection={selection} appleShape={appleShape} />}

           {multiState && multiPlayers && (
             <div style={{
               position: 'absolute', right: -164, top: 0,
               width: 154, background: 'rgba(0,0,0,0.78)', borderRadius: 12,
               padding: '12px 10px', color: '#fff', fontSize: 12,
               fontFamily: 'var(--font-body)', display: 'flex', flexDirection: 'column', gap: 6
             }}>
               <div style={{ fontWeight: 700, fontSize: 11, opacity: 0.6, letterSpacing: '0.05em', marginBottom: 4 }}>LIVE</div>
               {Object.entries(multiPlayers)
                 .sort((a, b) => (b[1].score || 0) - (a[1].score || 0))
                 .map(([uid, p], i) => (
                   <div key={uid} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 4 }}>
                     <span style={{
                       overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 84,
                       color: uid === multiState.userId ? 'var(--honey)' : '#fff',
                       fontWeight: uid === multiState.userId ? 700 : 400,
                       fontSize: 12
                     }}>{i + 1}. {p.displayName || '플레이어'}</span>
                     <span style={{ fontFamily: 'var(--font-num)', fontWeight: 700, fontSize: 13 }}>{p.score || 0}</span>
                   </div>
                 ))
               }
             </div>
           )}
           
           {isDragging && (
             <div style={{
               position: 'absolute',
               left: Math.min(dragStart.x, dragEnd.x),
               top: Math.min(dragStart.y, dragEnd.y),
               width: Math.abs(dragEnd.x - dragStart.x),
               height: Math.abs(dragEnd.y - dragStart.y),
               border: '2px solid #2f6fdb',
               background: 'rgba(47,111,219,0.10)',
               borderRadius: 8,
               pointerEvents: 'none'
             }} />
           )}

           {/* Sum Indicator (복구) */}
           {isDragging && currentSum > 0 && (() => {
             const cW = containerRef.current ? containerRef.current.offsetWidth : 9999;
             const cH = containerRef.current ? containerRef.current.offsetHeight : 9999;
             const tipLeft = dragEnd.x + 12 > cW - 90 ? dragEnd.x - 90 : dragEnd.x + 12;
             const tipTop = dragEnd.y - 24 < 0 ? dragEnd.y + 8 : Math.min(dragEnd.y - 24, cH - 36);
             return (
             <div style={{
               position: 'absolute',
               left: tipLeft,
               top: tipTop,
               padding: '4px 10px',
               background: (config.clearType === 'original' ? currentSum === 10 : (currentSum % 10 === 0 && currentSum <= 50)) ? '#2f6fdb' : 'var(--ink)',
               color: '#fff',
               borderRadius: 8,
               fontFamily: 'var(--font-num)', fontSize: 16, fontWeight: 700,
               pointerEvents: 'none', whiteSpace: 'nowrap', zIndex: 100
             }}>
               합 {currentSum}
             </div>
           );
           })()}

           {floatingTexts.map(t => (
             <div key={t.id} className="combo-text" style={{ 
               position: 'absolute', left: t.x, top: t.y, pointerEvents: 'none',
               animation: 'floatUp 0.8s ease-out forwards',
               fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 24,
               color: 'var(--apple)', textShadow: '2px 2px 0 #fff, -2px -2px 0 #fff, 2px -2px 0 #fff, -2px 2px 0 #fff',
               zIndex: 200
             }}>
               {t.text}
             </div>
           ))}
        </div>
      </div>

      <style>{`
        @keyframes floatUp {
          0% { transform: translateY(0); opacity: 1; }
          100% { transform: translateY(-50px); opacity: 0; }
        }
      `}</style>

      {/* AdSense 배너 */}
      <div style={{ display: 'flex', justifyContent: 'center', overflow: 'hidden', maxHeight: (isMobile || isShortScreen) ? 0 : isTablet ? 42 : 60 }}>
        <ins className="adsbygoogle"
          style={{ display: 'block', width: '100%', height: (isMobile || isShortScreen) ? 0 : isTablet ? 36 : 50 }}
          data-ad-client="ca-pub-7531779285959632"
          data-ad-slot="AUTO"
          data-ad-format="horizontal"
          data-full-width-responsive="true" />
        <script dangerouslySetInnerHTML={{ __html: '(adsbygoogle = window.adsbygoogle || []).push({});' }} />
      </div>

      {/* Game Footer Actions */}
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: (isMobile || isShortScreen) ? 8 : 12, paddingBottom: (isMobile || isShortScreen) ? 4 : 10 }}>
        <button onClick={() => onFinish(engine.getScore(), 'quit', multiPlayersRef.current || {})} style={{
           padding: (isMobile || isShortScreen) ? '8px 14px' : isTablet ? '11px 18px' : '14px 24px', background: 'var(--ink)', color: 'var(--paper)', border: 'none', borderRadius: 16,
           cursor: 'pointer', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: (isMobile || isShortScreen) ? 13 : 16
        }}>그만하기</button>
        {!multiState && (
          <button onClick={() => setShowRestartConfirm(true)} style={{
             padding: (isMobile || isShortScreen) ? '8px 14px' : isTablet ? '11px 18px' : '14px 24px', background: 'var(--leaf)', color: '#fff', border: 'none', borderRadius: 16,
             cursor: 'pointer', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: (isMobile || isShortScreen) ? 13 : 16
          }}>새 게임</button>
        )}
        <button onClick={onQuit} style={{
           padding: (isMobile || isShortScreen) ? '8px 14px' : isTablet ? '11px 18px' : '14px 24px', background: 'var(--paper-warm)', color: 'var(--ink)', border: '1px solid var(--hairline)', borderRadius: 16,
           cursor: 'pointer', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: (isMobile || isShortScreen) ? 13 : 16
        }}>나가기</button>
      </div>

      {/* Restart Confirmation Modal */}
      {showRestartConfirm && (
        <div style={{
          position: 'absolute', inset: 0, zIndex: 2000,
          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: 32, maxWidth: 340, width: '90%',
            boxShadow: '0 20px 40px rgba(0,0,0,0.12)',
            display: 'flex', flexDirection: 'column', gap: 16, textAlign: 'center'
          }}>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 700, color: 'var(--ink)' }}>새 게임을 시작할까요?</div>
            <div style={{ fontSize: 14, color: 'var(--ink-mute)', lineHeight: 1.5 }}>현재 점수는 저장되지 않습니다.<br/>같은 모드로 새로운 사과 배치가 시작됩니다.</div>
            <div style={{ display: 'flex', gap: 12 }}>
              <button onClick={() => setShowRestartConfirm(false)} style={{
                flex: 1, padding: '14px', borderRadius: 12, border: '1px solid var(--hairline)',
                background: 'var(--paper)', cursor: 'pointer', fontWeight: 600, fontSize: 15
              }}>취소</button>
              <button onClick={() => { setShowRestartConfirm(false); onRestart(); }} style={{
                flex: 1, padding: '14px', borderRadius: 12, border: 'none',
                background: 'var(--leaf)', color: '#fff', cursor: 'pointer', fontWeight: 700, fontSize: 15
              }}>새 게임 시작</button>
            </div>
          </div>
        </div>
      )}

      {/* 멀티플레이 인게임 채팅 */}
      {multiState && (
        <div style={{
          position: 'fixed', right: 12, bottom: 90, zIndex: 500,
          width: chatVisible ? 260 : 'auto', height: chatVisible ? 380 : 'auto',
          background: 'var(--paper)',
          borderRadius: 14, border: '1px solid var(--hairline)',
          boxShadow: '0 6px 20px rgba(0,0,0,0.08)',
          display: 'flex', flexDirection: 'column',
          overflow: 'hidden', transition: 'width 0.2s, height 0.2s',
          fontFamily: 'var(--font-body)'
        }}>
          {/* 헤더 */}
          <div style={{
            padding: chatVisible ? '12px 14px' : '12px',
            borderBottom: chatVisible ? '1px solid var(--hairline)' : 'none',
            fontWeight: 700, fontSize: 14, color: 'var(--ink)',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            flexShrink: 0
          }}>
            {chatVisible && <span>채팅</span>}
            <button
              onClick={() => setChatVisible(v => !v)}
              style={{
                background: 'none', border: 'none', cursor: 'pointer',
                fontSize: 13, fontWeight: 600, color: 'var(--ink-mute)', padding: 0, fontFamily: 'inherit',
                lineHeight: 1, marginLeft: chatVisible ? 'auto' : 0
              }}
              title={chatVisible ? '채팅 숨기기' : '채팅 열기'}
            >
              {chatVisible ? '접기' : '채팅'}
            </button>
          </div>

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

          {/* 입력창 */}
          {chatVisible && (
            <div style={{ padding: '8px 10px', borderTop: '1px solid var(--hairline)', display: 'flex', gap: 6, flexShrink: 0 }}>
              <input
                style={{
                  flex: 1, minWidth: 0, padding: '8px 10px', borderRadius: 9,
                  border: '1.5px solid var(--hairline)',
                  fontSize: 13, background: 'var(--paper)', color: 'var(--ink)',
                  outline: 'none', boxSizing: 'border-box', fontFamily: 'var(--font-body)'
                }}
                type="text"
                maxLength={120}
                placeholder="메시지..."
                value={chatInput}
                onChange={(e) => setChatInput(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' && !e.shiftKey && chatInput.trim()) {
                    e.preventDefault();
                    const text = chatInput;
                    setChatInput('');
                    const myName = (multiPlayers && multiPlayers[multiState.userId])
                      ? multiPlayers[multiState.userId].displayName : '플레이어';
                    window.sendChatMessage(multiState.roomId, multiState.userId, myName, text);
                  }
                }}
              />
              <button
                onClick={() => {
                  if (!chatInput.trim()) return;
                  const text = chatInput;
                  setChatInput('');
                  const myName = (multiPlayers && multiPlayers[multiState.userId])
                    ? multiPlayers[multiState.userId].displayName : '플레이어';
                  window.sendChatMessage(multiState.roomId, multiState.userId, myName, text);
                }}
                disabled={!chatInput.trim()}
                style={{
                  padding: '8px 12px', borderRadius: 9, border: 'none',
                  background: chatInput.trim() ? 'var(--leaf)' : 'var(--hairline)',
                  color: '#fff', fontWeight: 700, fontSize: 14,
                  cursor: chatInput.trim() ? 'pointer' : 'default'
                }}
              >보내기</button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { GameScreen });
