// screens-coop.jsx — 2인 협력 모드 전체 UI
// step: 'setup' | 'waiting' | 'playing' | 'result'

const COOP_COLORS = {
  host: 'rgba(27,100,50,0.38)',
  guest: 'rgba(25,118,210,0.38)',
  hostBorder: '#1B4332',
  guestBorder: '#1565C0',
};

// ─── 보드 렌더 (협력 모드 전용: 두 플레이어 selection 동시 표시) ───────────
function CoopGrid({ board, cols, cellSize, mySelection, otherSelection, isHost, appleShape }) {
  const GAP = 2;
  const PADDING = 4;
  const rows = board.length;

  const myColor   = isHost ? COOP_COLORS.host  : COOP_COLORS.guest;
  const otherColor = isHost ? COOP_COLORS.guest : COOP_COLORS.host;

  const inSel = (sel, r, c) =>
    sel && r >= sel.r1 && r <= sel.r2 && c >= sel.c1 && c <= sel.c2;

  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: `repeat(${cols}, ${cellSize}px)`,
      gridTemplateRows: `repeat(${rows}, ${cellSize}px)`,
      gap: GAP, padding: PADDING,
      background: 'var(--paper-dark)',
      borderRadius: 12,
      border: '2px solid var(--hairline)',
      boxShadow: '0 10px 30px rgba(0,0,0,0.1)',
    }}>
      {board.map((row, r) => row.map((apple, c) => {
        const isMine  = inSel(mySelection, r, c);
        const isOther = inSel(otherSelection, r, c);
        const bg = isMine && isOther
          ? 'rgba(128,0,128,0.38)'  // 겹침 → 보라
          : isMine   ? myColor
          : isOther  ? otherColor
          : 'transparent';

        return (
          <div key={`${r}-${c}`} style={{
            position: 'relative',
            background: bg,
            borderRadius: 4,
            transition: 'background 0.05s',
          }}>
            {apple > 0 ? (
              <AppleCell n={apple} size={cellSize} shape={appleShape || 'realistic'} selected={false} />
            ) : (
              <div style={{ width: cellSize, height: cellSize }} />
            )}
          </div>
        );
      }))}
    </div>
  );
}

// ─── 협력 게임 화면 ──────────────────────────────────────────────────────────
function CoopGame({ roomId, roomData, userId, isHost, config, appleShape, onFinish, breakpoint }) {
  const GAP = 2;
  const PADDING = 4;

  const { isMobile, isShortScreen } = breakpoint || {};
  const hudPadding = (isMobile || isShortScreen) ? '6px 12px' : '10px 20px';
  const hudFontSize = (isMobile || isShortScreen) ? 18 : 28;
  const hudLabelSize = (isMobile || isShortScreen) ? 8 : 10;

  // board: 2D array (로컬 렌더용)
  const [board, setBoard] = React.useState([]);
  const [mySelection, setMySelection] = React.useState(null);
  const [otherSelection, setOtherSelection] = React.useState(null);
  const [myScore, setMyScore] = React.useState(0);
  const [otherScore, setOtherScore] = React.useState(0);
  const [timeLeft, setTimeLeft] = React.useState(parseInt(config.timeMode) || 120);
  const [isDragging, setIsDragging] = React.useState(false);
  const [dragStart, setDragStart] = React.useState({ x: 0, y: 0 });
  const [cellSize, setCellSize] = React.useState(40);
  const [floatingTexts, setFloatingTexts] = React.useState([]);
  const [flashMsg, setFlashMsg] = React.useState('');

  const containerRef = React.useRef(null);
  const engineRef    = React.useRef(null);  // host 전용
  const selThrottle  = React.useRef(null);
  const timerRef     = React.useRef(null);
  const unsubRef     = React.useRef(null);
  const finishedRef  = React.useRef(false);

  const rows = config.rows || 10;
  const cols = config.cols || 17;

  // 플레이어 목록에서 상대방 uid 파악
  const otherUid = Object.keys(roomData.players || {}).find(uid => uid !== userId);

  // ── 보드 flat ↔ 2D 변환 ────────────────────────────────────────────────
  const flatTo2D = (flat) => {
    const grid = [];
    for (let r = 0; r < rows; r++) {
      grid.push(flat.slice(r * cols, r * cols + cols));
    }
    return grid;
  };

  const boardTo2D = (flat) => flatTo2D(flat.map(v => v || 0));

  // ── 셀 크기 자동 조절 ──────────────────────────────────────────────────
  React.useEffect(() => {
    const updateSize = () => {
      if (!containerRef.current) return;
      const rect = containerRef.current.getBoundingClientRect();
      const maxW = rect.width  - PADDING * 2;
      const maxH = rect.height - PADDING * 2;
      let s = Math.min(
        (maxW - (cols - 1) * GAP) / cols,
        (maxH - (rows - 1) * GAP) / rows
      );
      s = Math.max(16, Math.min(s, 60));
      setCellSize(Math.floor(s));
    };
    updateSize();
    window.addEventListener('resize', updateSize);
    const t = setTimeout(updateSize, 50);
    return () => { window.removeEventListener('resize', updateSize); clearTimeout(t); };
  }, [cols, rows]);

  // ── RTDB 구독 (상태 동기화) ──────────────────────────────────────────
  React.useEffect(() => {
    const unsub = window.listenCoopRoom(roomId, (data) => {
      if (!data) return;

      // 보드 동기화
      if (data.board) {
        const grid = boardTo2D(data.board);
        setBoard(grid);
        // host 엔진도 RTDB board와 동기화 (충돌 방지)
        if (isHost && engineRef.current) {
          engineRef.current.board = grid.map(r => [...r]);
          engineRef.current.score = (data.scores && data.scores[userId]) || 0;
          engineRef.current.updateSumTable();
        }
      }

      // 점수
      if (data.scores) {
        setMyScore(data.scores[userId] || 0);
        if (otherUid) setOtherScore(data.scores[otherUid] || 0);
      }

      // 타이머 (guest는 RTDB timeLeft를 보고 렌더)
      if (!isHost && data.timeLeft !== undefined) {
        setTimeLeft(data.timeLeft);
      }

      // 상대방 selection
      if (data.selections && otherUid && data.selections[otherUid]) {
        setOtherSelection(data.selections[otherUid]);
      } else {
        setOtherSelection(null);
      }

      // guest의 pendingMove 처리 (host만)
      if (isHost && data.pendingMove && otherUid && data.pendingMove[otherUid]) {
        handleGuestMove(data.pendingMove[otherUid]);
      }

      // 종료
      if (data.status === 'finished' && !finishedRef.current) {
        finishedRef.current = true;
        onFinish(data);
      }
    });
    unsubRef.current = unsub;
    return () => { unsub(); };
  }, [roomId, otherUid]);

  // ── Host: GameEngine 초기화 + 보드 push ──────────────────────────────
  React.useEffect(() => {
    if (!isHost) return;

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

    const engine = new GameEngine(rows, cols);
    engine.initBoard(boardData);
    engineRef.current = engine;

    const flat = engine.getBoard().flat();
    setBoard(engine.getBoard().map(r => [...r]));

    window.startCoopGame(roomId, flat, config.timeMode);
  }, []);

  // ── Host: 타이머 ─────────────────────────────────────────────────────
  React.useEffect(() => {
    if (!isHost) return;

    timerRef.current = setInterval(async () => {
      setTimeLeft(prev => {
        const next = prev - 1;
        window.updateCoopTimeLeft(roomId, next);
        if (next <= 0) {
          clearInterval(timerRef.current);
          if (!finishedRef.current) {
            finishedRef.current = true;
            const engine = engineRef.current;
            const total = engine ? engine.getScore() : 0;
            window.finishCoopGame(roomId, total);
          }
        }
        return next;
      });
    }, 1000);

    return () => clearInterval(timerRef.current);
  }, [isHost]);

  // ── Host: guest move 처리 ────────────────────────────────────────────
  const handleGuestMove = async (move) => {
    const engine = engineRef.current;
    if (!engine) return;

    await window.clearCoopPendingMove(roomId, otherUid);

    const { r1, c1, r2, c2 } = move;
    const beforeApples = engine.getRemainingApples();
    const ok = engine.evaluateSelection(r1, c1, r2, c2, config.clearType || 'original');

    if (ok) {
      const removed = beforeApples - engine.getRemainingApples();
      const flat = engine.getBoard().flat();
      const guestScore = (roomData.scores && roomData.scores[otherUid] || 0) + removed;
      await window.updateCoopBoard(roomId, flat, userId, engine.getScore(), otherUid, guestScore);

      if (engine.getRemainingApples() === 0) {
        if (!finishedRef.current) {
          finishedRef.current = true;
          await window.finishCoopGame(roomId, engine.getScore() + guestScore);
        }
      }
    }
  };

  // ── 드래그 선택 계산 (공통) ──────────────────────────────────────────
  const computeSelection = (start, end) => {
    const left   = Math.min(start.x, end.x);
    const right  = Math.max(start.x, end.x);
    const top    = Math.min(start.y, end.y);
    const bottom = Math.max(start.y, end.y);
    const HIT = cellSize * 0.28;

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

    for (let r = 0; r < rows; r++) {
      for (let c = 0; c < cols; c++) {
        const cx = PADDING + c * (cellSize + GAP) + cellSize / 2;
        const cy = PADDING + r * (cellSize + GAP) + cellSize / 2;
        if (cx >= left - HIT && cx <= right + HIT && cy >= top - HIT && cy <= bottom + HIT) {
          r1 = Math.min(r1, r); c1 = Math.min(c1, c);
          r2 = Math.max(r2, r); c2 = Math.max(c2, c);
          found = true;
        }
      }
    }
    return found ? { r1, c1, r2, c2 } : null;
  };

  // 로컬 sum 계산 (UX 피드백용)
  const localSum = (sel) => {
    if (!sel || !board.length) return 0;
    let s = 0;
    for (let r = sel.r1; r <= sel.r2; r++) {
      for (let c = sel.c1; c <= sel.c2; c++) {
        s += (board[r] && board[r][c]) || 0;
      }
    }
    return s;
  };

  // ── 포인터 이벤트 ────────────────────────────────────────────────────
  const handlePointerDown = (e) => {
    const rect = containerRef.current.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    setIsDragging(true);
    setDragStart({ x, y });
    const sel = computeSelection({ x, y }, { x, y });
    setMySelection(sel);
  };

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

    // selection throttle: 80ms마다 RTDB 업데이트
    if (!selThrottle.current) {
      selThrottle.current = setTimeout(async () => {
        selThrottle.current = null;
        if (sel) await window.updateCoopSelection(roomId, userId, sel);
      }, 80);
    }
  };

  const handlePointerUp = async () => {
    if (!isDragging) return;
    setIsDragging(false);
    await window.updateCoopSelection(roomId, userId, null);

    if (!mySelection) { setMySelection(null); return; }

    if (isHost) {
      // host: 직접 엔진 적용
      const engine = engineRef.current;
      if (!engine) { setMySelection(null); return; }

      const beforeApples = engine.getRemainingApples();
      const ok = engine.evaluateSelection(
        mySelection.r1, mySelection.c1, mySelection.r2, mySelection.c2,
        config.clearType || 'original'
      );

      if (ok) {
        const removed = beforeApples - engine.getRemainingApples();
        const flat = engine.getBoard().flat();
        const guestScore = roomData.scores && otherUid ? (roomData.scores[otherUid] || 0) : undefined;
        await window.updateCoopBoard(roomId, flat, userId, engine.getScore(), otherUid, guestScore);
        showCombo(removed);

        if (engine.getRemainingApples() === 0 && !finishedRef.current) {
          finishedRef.current = true;
          const total = engine.getScore() + (guestScore || 0);
          await window.finishCoopGame(roomId, total);
        }
      }
    } else {
      // guest: pendingMove 전송
      const sum = localSum(mySelection);
      const isMatch = config.clearType === 'multiples'
        ? (sum % 10 === 0 && sum > 0 && sum <= 50)
        : (sum === 10);

      if (isMatch) {
        await window.sendCoopMove(
          roomId, userId,
          mySelection.r1, mySelection.c1, mySelection.r2, mySelection.c2
        );
      }
    }

    setMySelection(null);
  };

  const showCombo = (removed) => {
    let msg = '';
    if (removed >= 4) msg = 'Excellent!!';
    else if (removed === 3) msg = 'Great!';
    else if (removed === 2) msg = 'Good!';
    if (!msg) return;
    const id = Date.now();
    setFloatingTexts(p => [...p, { id, text: `${msg} +${removed}` }]);
    setTimeout(() => setFloatingTexts(p => p.filter(t => t.id !== id)), 900);
  };

  const formatTime = (s) => {
    const m = Math.floor(s / 60);
    const sec = s % 60;
    return `${String(m).padStart(2, '0')}:${String(sec).padStart(2, '0')}`;
  };

  const players = roomData.players || {};
  const myName    = players[userId]    ? players[userId].displayName    : 'P1';
  const otherName = otherUid && players[otherUid] ? players[otherUid].displayName : 'P2';
  const totalScore = myScore + otherScore;
  const warn = timeLeft <= 10;

  return (
    <div
      style={{
        width: '100%', height: '100%',
        background: 'var(--paper)',
        display: 'flex', flexDirection: 'column', gap: 10,
        padding: '16px 20px',
        userSelect: 'none', WebkitUserSelect: 'none',
        fontFamily: 'var(--font-body)', position: 'relative', overflow: 'hidden'
      }}
      onPointerUp={handlePointerUp}
      onPointerLeave={handlePointerUp}
    >
      {/* HUD */}
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        background: 'var(--ink)', borderRadius: 16, padding: hudPadding, color: '#fff',
        boxShadow: '0 6px 20px rgba(0,0,0,0.15)', flexShrink: 0
      }}>
        {/* 합산 점수 */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
          <span style={{ fontSize: hudLabelSize, fontFamily: 'var(--font-mono)', opacity: 0.6, letterSpacing: '0.1em' }}>TOTAL</span>
          <span style={{ fontSize: hudFontSize, fontFamily: 'var(--font-num)', fontWeight: 800, lineHeight: 1 }}>{totalScore}</span>
        </div>

        {/* 개인 점수 */}
        <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 10, opacity: 0.6, marginBottom: 2 }}>
              <span style={{ color: '#74C69D' }}>●</span> {myName}
            </div>
            <div style={{ fontSize: 18, fontFamily: 'var(--font-num)', fontWeight: 700 }}>{myScore}</div>
          </div>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 10, opacity: 0.6, marginBottom: 2 }}>
              <span style={{ color: '#90CAF9' }}>●</span> {otherName}
            </div>
            <div style={{ fontSize: 18, fontFamily: 'var(--font-num)', fontWeight: 700 }}>{otherScore}</div>
          </div>
        </div>

        {/* 타이머 */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
          <span style={{ fontSize: hudLabelSize, fontFamily: 'var(--font-mono)', opacity: 0.6, letterSpacing: '0.1em' }}>TIME</span>
          <span style={{
            fontSize: hudFontSize, fontFamily: 'var(--font-num)', fontWeight: 800, lineHeight: 1,
            color: warn ? '#ff4d4d' : '#fff',
            animation: warn ? 'pulse 0.8s infinite' : 'none'
          }}>{formatTime(timeLeft)}</span>
        </div>
      </div>

      {/* 보드 */}
      <div
        ref={containerRef}
        style={{ flex: 1, position: 'relative', overflow: 'hidden', cursor: 'crosshair' }}
        onPointerDown={handlePointerDown}
        onPointerMove={handlePointerMove}
      >
        {board.length > 0 && (
          <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
            <CoopGrid
              board={board}
              cols={cols}
              cellSize={cellSize}
              mySelection={mySelection}
              otherSelection={otherSelection}
              isHost={isHost}
              appleShape={appleShape}
            />
          </div>
        )}

        {/* 드래그 합계 표시 */}
        {mySelection && (() => {
          const sum = isHost
            ? (engineRef.current ? engineRef.current.getAreaSum(mySelection.r1, mySelection.c1, mySelection.r2, mySelection.c2) : localSum(mySelection))
            : localSum(mySelection);
          const isMatch = config.clearType === 'multiples'
            ? (sum % 10 === 0 && sum > 0 && sum <= 50)
            : (sum === 10);
          return (
            <div style={{
              position: 'absolute', top: 12, left: '50%', transform: 'translateX(-50%)',
              background: isMatch ? 'var(--leaf)' : 'var(--ink)',
              color: '#fff', borderRadius: 20, padding: '6px 18px',
              fontFamily: 'var(--font-num)', fontSize: 22, fontWeight: 800,
              boxShadow: '0 4px 12px rgba(0,0,0,0.2)', pointerEvents: 'none'
            }}>
              {sum}
            </div>
          );
        })()}

        {/* 콤보 텍스트 */}
        {floatingTexts.map(t => (
          <div key={t.id} className="combo-text" style={{ top: '40%', left: '50%', transform: 'translateX(-50%)', fontSize: 32 }}>
            {t.text}
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── 방 대기실 ─────────────────────────────────────────────────────────────
function CoopWaiting({ roomId, roomData, userId, isHost, onStartGame, onLeave }) {
  const players = roomData.players || {};
  const uids = Object.keys(players);
  const canStart = isHost && uids.length === 2;

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

  return (
    <div style={{
      width: '100%', height: '100%', display: 'flex',
      alignItems: 'center', justifyContent: 'center',
      background: 'var(--paper)', fontFamily: 'var(--font-body)'
    }}>
      <div style={{
        background: 'var(--paper-warm)', borderRadius: 24, padding: '36px 32px',
        border: '1.5px solid var(--ink)', boxShadow: '6px 6px 0 var(--ink)',
        width: 'min(92vw, 440px)', display: 'flex', flexDirection: 'column', gap: 24
      }}>
        <div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--apple-deep)', letterSpacing: '0.16em', textTransform: 'uppercase', marginBottom: 8 }}>
            🤝 협력 모드
          </div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 700, color: 'var(--ink)' }}>
            대기 중...
          </div>
          <div style={{ fontSize: 13, color: 'var(--ink-mute)', marginTop: 6, lineHeight: 1.5 }}>
            친구에게 방 코드를 알려주세요. 2명이 모이면 시작할 수 있어요.
          </div>
        </div>

        {/* 방 코드 */}
        <div style={{
          background: 'var(--paper)', borderRadius: 14, padding: '16px 20px',
          border: '1.5px solid var(--hairline)', cursor: 'pointer',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center'
        }} onClick={copyCode} title="클릭해서 복사">
          <div>
            <div style={{ fontSize: 11, color: 'var(--ink-mute)', marginBottom: 4, letterSpacing: '0.08em' }}>방 코드</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 22, fontWeight: 700, color: 'var(--ink)', letterSpacing: '0.1em' }}>
              {roomId}
            </div>
          </div>
          <span style={{ fontSize: 20, opacity: 0.5 }}>📋</span>
        </div>

        {/* 플레이어 목록 */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {uids.map((uid, i) => (
            <div key={uid} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              background: 'var(--paper)', borderRadius: 12, padding: '12px 16px',
              border: uid === userId ? '1.5px solid var(--leaf)' : '1.5px solid var(--hairline)'
            }}>
              <span style={{
                width: 32, height: 32, borderRadius: '50%',
                background: i === 0 ? 'var(--leaf)' : '#1565C0',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#fff', fontWeight: 700, fontSize: 14
              }}>{i === 0 ? 'P1' : 'P2'}</span>
              <span style={{ fontWeight: 600, color: 'var(--ink)' }}>
                {players[uid].displayName}
                {uid === userId && <span style={{ fontSize: 11, color: 'var(--ink-mute)', marginLeft: 6 }}>(나)</span>}
              </span>
            </div>
          ))}
          {uids.length < 2 && (
            <div style={{
              display: 'flex', alignItems: 'center', gap: 12,
              background: 'var(--paper)', borderRadius: 12, padding: '12px 16px',
              border: '1.5px dashed var(--hairline)'
            }}>
              <span style={{
                width: 32, height: 32, borderRadius: '50%',
                background: 'var(--hairline)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: 'var(--ink-mute)', fontWeight: 700, fontSize: 14
              }}>P2</span>
              <span style={{ color: 'var(--ink-mute)', fontSize: 14 }}>친구를 기다리는 중...</span>
            </div>
          )}
        </div>

        {/* 버튼 */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {isHost && (
            <button
              onClick={onStartGame}
              disabled={!canStart}
              style={{
                padding: '16px', borderRadius: 14, border: 'none',
                background: canStart ? 'var(--ink)' : 'var(--hairline)',
                color: '#fff', fontWeight: 700, fontSize: 16,
                cursor: canStart ? 'pointer' : 'default', transition: 'background 0.15s'
              }}
            >
              {canStart ? '🍎 게임 시작' : '친구를 기다리는 중...'}
            </button>
          )}
          {!isHost && (
            <div style={{
              padding: '16px', borderRadius: 14, background: 'var(--paper-dark)',
              textAlign: 'center', color: 'var(--ink-mute)', fontSize: 14
            }}>
              방장이 게임을 시작하길 기다리는 중...
            </div>
          )}
          <button onClick={onLeave} style={{
            padding: '14px', borderRadius: 14,
            border: '1.5px solid var(--hairline)', background: 'transparent',
            color: 'var(--ink-mute)', fontWeight: 600, fontSize: 14, cursor: 'pointer'
          }}>
            나가기
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── 결과 화면 ─────────────────────────────────────────────────────────────
function CoopResult({ roomData, userId, onBack }) {
  const players = roomData.players || {};
  const scores  = roomData.scores  || {};
  const result  = roomData.result  || {};
  const uids = Object.keys(players);
  const totalScore = result.totalScore || Object.values(scores).reduce((a, b) => a + b, 0);

  return (
    <div style={{
      width: '100%', height: '100%', display: 'flex',
      alignItems: 'center', justifyContent: 'center',
      background: 'var(--paper)', fontFamily: 'var(--font-body)'
    }}>
      <div style={{
        background: 'var(--paper-warm)', borderRadius: 24, padding: '40px 32px',
        border: '1.5px solid var(--ink)', boxShadow: '6px 6px 0 var(--ink)',
        width: 'min(92vw, 440px)', display: 'flex', flexDirection: 'column', gap: 24,
        textAlign: 'center'
      }}>
        <div>
          <div style={{ fontSize: 48 }}>🏆</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 700, color: 'var(--ink)', marginTop: 8 }}>
            협력 완료!
          </div>
          <div style={{ fontSize: 14, color: 'var(--ink-mute)', marginTop: 6 }}>
            두 사람이 힘을 합쳐 수확했어요
          </div>
        </div>

        {/* 합산 점수 */}
        <div style={{
          background: 'var(--ink)', borderRadius: 16, padding: '20px',
          color: '#fff'
        }}>
          <div style={{ fontSize: 12, opacity: 0.6, letterSpacing: '0.1em', marginBottom: 4 }}>TOTAL HARVEST</div>
          <div style={{ fontSize: 52, fontFamily: 'var(--font-num)', fontWeight: 900, lineHeight: 1 }}>{totalScore}</div>
          <div style={{ fontSize: 13, opacity: 0.6, marginTop: 4 }}>사과 {totalScore}개</div>
        </div>

        {/* 개인 기여 */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {uids.map((uid, i) => (
            <div key={uid} style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              background: 'var(--paper)', borderRadius: 12, padding: '14px 18px',
              border: uid === userId ? '1.5px solid var(--leaf)' : '1.5px solid var(--hairline)'
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{
                  width: 28, height: 28, borderRadius: '50%',
                  background: i === 0 ? 'var(--leaf)' : '#1565C0',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: '#fff', fontWeight: 700, fontSize: 12
                }}>{i === 0 ? 'P1' : 'P2'}</span>
                <span style={{ fontWeight: 600, color: 'var(--ink)', fontSize: 15 }}>
                  {players[uid].displayName}
                  {uid === userId && <span style={{ fontSize: 11, color: 'var(--ink-mute)', marginLeft: 4 }}>(나)</span>}
                </span>
              </div>
              <div style={{ fontFamily: 'var(--font-num)', fontSize: 22, fontWeight: 800, color: 'var(--ink)' }}>
                {scores[uid] || 0}
              </div>
            </div>
          ))}
        </div>

        <button onClick={onBack} style={{
          padding: '16px', borderRadius: 14, border: 'none',
          background: 'var(--ink)', color: '#fff', fontWeight: 700, fontSize: 16, cursor: 'pointer'
        }}>
          메인으로 돌아가기
        </button>
      </div>
    </div>
  );
}

// ─── 방 참가 (코드 입력) ───────────────────────────────────────────────────
function CoopJoin({ userId, displayName, onJoined, onBack }) {
  const [code, setCode] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');

  const handleJoin = async () => {
    const id = code.trim();
    if (!id) return;
    setLoading(true); setError('');
    try {
      const { cleanup } = await window.joinCoopRoom(id, userId, displayName);
      onJoined(id, cleanup);
    } catch (e) {
      setError(e.message || '참가에 실패했습니다.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      width: '100%', height: '100%', display: 'flex',
      alignItems: 'center', justifyContent: 'center',
      background: 'var(--paper)', fontFamily: 'var(--font-body)'
    }}>
      <div style={{
        background: 'var(--paper-warm)', borderRadius: 24, padding: '36px 32px',
        border: '1.5px solid var(--ink)', boxShadow: '6px 6px 0 var(--ink)',
        width: 'min(92vw, 400px)', display: 'flex', flexDirection: 'column', gap: 20
      }}>
        <div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--apple-deep)', letterSpacing: '0.16em', textTransform: 'uppercase', marginBottom: 8 }}>
            🤝 협력 모드
          </div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 700, color: 'var(--ink)' }}>
            방 코드 입력
          </div>
        </div>

        <input
          type="text"
          value={code}
          onChange={e => { setCode(e.target.value); setError(''); }}
          onKeyDown={e => { if (e.key === 'Enter') handleJoin(); }}
          placeholder="방 코드를 입력하세요"
          style={{
            width: '100%', padding: '14px 16px', borderRadius: 12,
            border: error ? '1.5px solid #cc0000' : '1.5px solid var(--hairline)',
            fontFamily: 'var(--font-mono)', fontSize: 18,
            background: 'var(--paper)', color: 'var(--ink)',
            outline: 'none', boxSizing: 'border-box', letterSpacing: '0.05em'
          }}
          autoFocus
        />
        {error && <div style={{ color: '#cc0000', fontSize: 13 }}>⚠️ {error}</div>}

        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <button onClick={handleJoin} disabled={!code.trim() || loading} style={{
            padding: '15px', borderRadius: 14, border: 'none',
            background: code.trim() && !loading ? 'var(--ink)' : 'var(--hairline)',
            color: '#fff', fontWeight: 700, fontSize: 16,
            cursor: code.trim() && !loading ? 'pointer' : 'default'
          }}>
            {loading ? '참가 중...' : '참가하기'}
          </button>
          <button onClick={onBack} style={{
            padding: '14px', borderRadius: 14,
            border: '1.5px solid var(--hairline)', background: 'transparent',
            color: 'var(--ink-mute)', fontWeight: 600, fontSize: 14, cursor: 'pointer'
          }}>뒤로</button>
        </div>
      </div>
    </div>
  );
}

// ─── 최상위 CoopScreen ──────────────────────────────────────────────────────
function CoopScreen({ user, config, appleShape, onBack, breakpoint }) {
  // step: 'select' | 'waiting' | 'playing' | 'result'
  const [step, setStep]       = React.useState('select');
  const [roomId, setRoomId]   = React.useState('');
  const [roomData, setRoomData] = React.useState(null);
  const [isHost, setIsHost]   = React.useState(false);
  const [error, setError]     = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [subStep, setSubStep] = React.useState('menu'); // 'menu' | 'join'

  const cleanupRef   = React.useRef(null);
  const unsubRef     = React.useRef(null);

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

  // ── 방 리스닝 시작 ──
  const startListening = (rid) => {
    if (unsubRef.current) unsubRef.current();
    const unsub = window.listenCoopRoom(rid, (data) => {
      setRoomData(data);
      if (data.status === 'playing' && step !== 'playing' && step !== 'result') {
        setStep('playing');
      }
      if (data.status === 'finished' && step !== 'result') {
        setStep('result');
      }
    });
    unsubRef.current = unsub;
  };

  // ── 방 만들기 ──
  const handleCreate = async () => {
    if (!userId) { setError('로그인이 필요합니다.'); return; }
    setLoading(true); setError('');
    try {
      const { roomId: rid, cleanup } = await window.createCoopRoom(config, userId, displayName);
      cleanupRef.current = cleanup;
      setRoomId(rid);
      setIsHost(true);
      startListening(rid);
      setStep('waiting');
    } catch (e) {
      setError(e.message || '방 생성에 실패했습니다.');
    } finally {
      setLoading(false);
    }
  };

  // ── 방 참가 완료 ──
  const handleJoined = (rid, cleanup) => {
    cleanupRef.current = cleanup;
    setRoomId(rid);
    setIsHost(false);
    startListening(rid);
    setStep('waiting');
  };

  // ── 게임 시작 (host) ──
  const handleStartGame = () => {
    // CoopGame 컴포넌트 내부에서 board 생성 및 startCoopGame 호출
    setStep('playing');
  };

  // ── 종료 처리 ──
  const handleFinish = (data) => {
    setRoomData(data);
    setStep('result');
  };

  // ── 나가기 ──
  const handleLeave = async () => {
    if (unsubRef.current) { unsubRef.current(); unsubRef.current = null; }
    if (cleanupRef.current) { cleanupRef.current(); cleanupRef.current = null; }
    if (roomId && userId) {
      try { await window.leaveCoopRoom(roomId, userId, isHost); } catch (e) {}
    }
    setStep('select');
    setSubStep('menu');
    setRoomId('');
    setRoomData(null);
  };

  // ── 언마운트 정리 ──
  React.useEffect(() => {
    return () => {
      if (unsubRef.current) unsubRef.current();
      if (cleanupRef.current) cleanupRef.current();
    };
  }, []);

  // ── 렌더 ──
  if (step === 'select') {
    if (subStep === 'join') {
      return (
        <CoopJoin
          userId={userId}
          displayName={displayName}
          onJoined={handleJoined}
          onBack={() => setSubStep('menu')}
        />
      );
    }

    return (
      <div style={{
        width: '100%', height: '100%', display: 'flex',
        alignItems: 'center', justifyContent: 'center',
        background: 'var(--paper)', fontFamily: 'var(--font-body)'
      }}>
        <div style={{
          background: 'var(--paper-warm)', borderRadius: 24, padding: '36px 32px',
          border: '1.5px solid var(--ink)', boxShadow: '6px 6px 0 var(--ink)',
          width: 'min(92vw, 420px)', display: 'flex', flexDirection: 'column', gap: 20
        }}>
          <div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--apple-deep)', letterSpacing: '0.16em', textTransform: 'uppercase', marginBottom: 8 }}>
              🤝 협력 모드
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 700, color: 'var(--ink)' }}>
              같이 따기
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-mute)', marginTop: 8, lineHeight: 1.6 }}>
              친구와 <strong>같은 보드</strong>를 함께 클리어하세요.<br/>
              <span style={{ color: '#1B4332' }}>●</span> 초록 P1 &nbsp;
              <span style={{ color: '#1565C0' }}>●</span> 파란 P2
            </div>
          </div>

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

          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <button onClick={handleCreate} disabled={loading} style={{
              padding: '16px', borderRadius: 14, border: 'none',
              background: loading ? 'var(--hairline)' : 'var(--ink)',
              color: '#fff', fontWeight: 700, fontSize: 16, cursor: loading ? 'default' : 'pointer'
            }}>
              {loading ? '생성 중...' : '🏠 방 만들기'}
            </button>
            <button onClick={() => setSubStep('join')} disabled={loading} style={{
              padding: '16px', borderRadius: 14,
              border: '1.5px solid var(--ink)', background: 'transparent',
              color: 'var(--ink)', fontWeight: 700, fontSize: 16, cursor: 'pointer'
            }}>
              🔑 코드로 참가
            </button>
            <button onClick={onBack} style={{
              padding: '14px', borderRadius: 14,
              border: '1.5px solid var(--hairline)', background: 'transparent',
              color: 'var(--ink-mute)', fontWeight: 600, fontSize: 14, cursor: 'pointer'
            }}>
              뒤로
            </button>
          </div>
        </div>
      </div>
    );
  }

  if (step === 'waiting' && roomData) {
    return (
      <CoopWaiting
        roomId={roomId}
        roomData={roomData}
        userId={userId}
        isHost={isHost}
        onStartGame={handleStartGame}
        onLeave={handleLeave}
      />
    );
  }

  if (step === 'playing' && roomData) {
    return (
      <CoopGame
        roomId={roomId}
        roomData={roomData}
        userId={userId}
        isHost={isHost}
        config={config}
        appleShape={appleShape}
        onFinish={handleFinish}
        breakpoint={breakpoint}
      />
    );
  }

  if (step === 'result' && roomData) {
    return (
      <CoopResult
        roomData={roomData}
        userId={userId}
        onBack={() => { handleLeave(); onBack(); }}
      />
    );
  }

  // 로딩 중
  return (
    <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ color: 'var(--ink-mute)', fontSize: 16 }}>로딩 중...</div>
    </div>
  );
}
