// lobby-screen.jsx — room creation, joining, and pre-game lobby
// Exports: LobbyScreen

function LobbyScreen({ roomState, myTeam, isHost, onLocalMode }) {
  const { useState, useEffect } = React;

  // Landing sub-view state
  const [view, setView] = useState('landing'); // 'landing' | 'create' | 'join'
  const [createName, setCreateName] = useState('');
  const [createRounds, setCreateRounds] = useState(2);
  const [joinCode, setJoinCode] = useState('');
  const [joinName, setJoinName] = useState('');

  const cleanName = (v) => v.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 5);
  const cleanCode = (v) => v.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 4);

  // If we already have a room, show lobby view
  const inRoom = roomState && roomState.phase === 'lobby';

  const handleCreate = () => {
    if (!createName.trim()) return;
    window.sfx && window.sfx.lock();
    window.socketClient.emit('create_room', { teamName: createName.trim(), rounds: createRounds });
  };

  const handleJoin = () => {
    if (!joinCode.trim() || !joinName.trim()) return;
    window.sfx && window.sfx.lock();
    window.socketClient.emit('join_room', { code: joinCode.trim(), teamName: joinName.trim() });
  };

  const handleStart = () => {
    if (!roomState || roomState.teams.length < 2) return;
    window.sfx && window.sfx.start();
    window.socketClient.emit('start_game');
  };

  if (inRoom) {
    // ── Lobby view ─────────────────────────────────────────────────────────
    const canStart = isHost && roomState.teams.length >= 2;
    return (
      <div className="screen fade-in" style={{ paddingTop: 10, gap: 16 }}>
        <Marquee title="Guessdit" subtitle="High-Speed Charades · No Talking!" />

        {/* Room code */}
        <div style={panelStyle}>
          <div className="eyebrow" style={{ textAlign: 'center', marginBottom: 10 }}>
            — Share This Code —
          </div>
          <div className="room-code">
            {roomState.code}
          </div>
          <div style={{
            fontFamily: 'var(--font-ui)',
            fontSize: 13,
            color: 'var(--fg-quiet)',
            textAlign: 'center',
            marginTop: 8,
          }}>
            Open this page on each team's phone and enter the code above
          </div>
        </div>

        {/* Teams list */}
        <div style={panelStyle}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
            <span className="eyebrow">★ Teams Joined</span>
            <span style={{ fontFamily: 'var(--font-arcade)', fontSize: 9, color: 'var(--fg-quiet)' }}>
              {roomState.teams.length}/4
            </span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {roomState.teams.map((team, i) => (
              <div key={team.name} style={{
                display: 'flex',
                alignItems: 'center',
                gap: 10,
                padding: '10px 14px',
                borderRadius: 10,
                background: team.name === myTeam
                  ? 'rgba(255,94,58,0.15)'
                  : 'rgba(255,255,255,0.04)',
                border: team.name === myTeam
                  ? '1px solid rgba(255,94,58,0.4)'
                  : '1px solid rgba(255,255,255,0.07)',
              }}>
                <span style={{
                  fontFamily: 'var(--font-arcade)',
                  fontSize: 9,
                  color: team.name === myTeam ? 'var(--accent)' : 'var(--fg-quiet)',
                  width: 22,
                }}>
                  P{i + 1}
                </span>
                <span style={{
                  fontFamily: 'var(--font-arcade)',
                  fontSize: 14,
                  letterSpacing: 2,
                  color: team.name === myTeam ? 'var(--accent)' : 'var(--fg)',
                  flex: 1,
                }}>
                  {team.name}
                </span>
                {team.name === myTeam && (
                  <span style={{
                    fontFamily: 'var(--font-arcade)',
                    fontSize: 8,
                    letterSpacing: 2,
                    color: 'var(--accent)',
                    background: 'rgba(255,94,58,0.15)',
                    border: '1px solid rgba(255,94,58,0.3)',
                    padding: '3px 7px',
                    borderRadius: 999,
                  }}>YOU</span>
                )}
                {team.name === roomState.hostTeam && (
                  <span style={{
                    fontFamily: 'var(--font-arcade)',
                    fontSize: 8,
                    letterSpacing: 2,
                    color: 'var(--accent-2)',
                    background: 'rgba(255,210,63,0.12)',
                    border: '1px solid rgba(255,210,63,0.25)',
                    padding: '3px 7px',
                    borderRadius: 999,
                  }}>HOST</span>
                )}
                {!team.socketId && (
                  <span style={{
                    fontFamily: 'var(--font-arcade)',
                    fontSize: 8,
                    color: 'var(--fg-quiet)',
                  }}>···</span>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Rounds info */}
        <div style={{ ...panelStyle, padding: '12px 16px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontFamily: 'var(--font-arcade)', fontSize: 9, letterSpacing: 2, color: 'var(--fg-quiet)' }}>
              ROUNDS
            </span>
            <span style={{ fontFamily: 'var(--font-arcade)', fontSize: 16, color: 'var(--accent-2)' }}>
              {roomState.rounds}
            </span>
          </div>
        </div>

        <div className="spacer" />

        {isHost ? (
          <button
            className="btn"
            disabled={!canStart}
            onClick={handleStart}
          >
            {roomState.teams.length < 2
              ? '⏳ Waiting for teams...'
              : `▶ Start Game · ${roomState.teams.length} teams`}
          </button>
        ) : (
          <div style={{
            textAlign: 'center',
            fontFamily: 'var(--font-arcade)',
            fontSize: 9,
            letterSpacing: 2,
            color: 'var(--fg-quiet)',
            padding: '16px 0',
            animation: 'waitPulse 1.8s ease-in-out infinite',
          }}>
            ⏳ WAITING FOR HOST TO START...
          </div>
        )}
      </div>
    );
  }

  // ── Landing / form views ────────────────────────────────────────────────
  if (view === 'create') {
    return (
      <div className="screen fade-in" style={{ paddingTop: 10 }}>
        <Marquee title="Guessdit" subtitle="Create a New Room" mini />

        <div style={panelStyle}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Your Team Name</div>
          <input
            className="tag-input"
            value={createName}
            placeholder="TEAM1"
            maxLength={5}
            inputMode="text"
            autoComplete="off"
            autoCapitalize="characters"
            spellCheck={false}
            autoFocus
            onChange={(e) => setCreateName(cleanName(e.target.value))}
            onKeyDown={(e) => e.key === 'Enter' && handleCreate()}
          />
        </div>

        <div style={panelStyle}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>▣ Rounds</div>
          <div className="row" style={{ gap: 8 }}>
            {[1, 2, 3].map((r) => (
              <button
                key={r}
                onClick={() => { window.sfx && window.sfx.pick(); setCreateRounds(r); }}
                style={{
                  appearance: 'none', flex: 1, padding: '16px 0',
                  borderRadius: 12, cursor: 'pointer',
                  border: r === createRounds ? '1px solid rgba(255,94,58,0.55)' : '1px solid rgba(255,255,255,0.1)',
                  background: r === createRounds ? 'rgba(255,94,58,0.18)' : 'rgba(255,255,255,0.04)',
                  color: r === createRounds ? 'var(--accent)' : 'var(--fg-dim)',
                  fontFamily: 'var(--font-arcade)', fontSize: 18,
                  boxShadow: r === createRounds ? '0 0 0 1px rgba(255,94,58,0.25)' : 'none',
                }}
              >{r}</button>
            ))}
          </div>
        </div>

        <div className="spacer" />

        <button className="btn" disabled={!createName.trim()} onClick={handleCreate}>
          ▶ Create Room
        </button>
        <button className="btn ghost" onClick={() => setView('landing')}>← Back</button>
      </div>
    );
  }

  if (view === 'join') {
    return (
      <div className="screen fade-in" style={{ paddingTop: 10 }}>
        <Marquee title="Guessdit" subtitle="Join a Room" mini />

        <div style={panelStyle}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Room Code</div>
          <input
            className="tag-input"
            value={joinCode}
            placeholder="ABCD"
            maxLength={4}
            inputMode="text"
            autoComplete="off"
            autoCapitalize="characters"
            spellCheck={false}
            autoFocus
            onChange={(e) => setJoinCode(cleanCode(e.target.value))}
          />
        </div>

        <div style={panelStyle}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Your Team Name</div>
          <input
            className="tag-input"
            value={joinName}
            placeholder="TEAM2"
            maxLength={5}
            inputMode="text"
            autoComplete="off"
            autoCapitalize="characters"
            spellCheck={false}
            onChange={(e) => setJoinName(cleanName(e.target.value))}
            onKeyDown={(e) => e.key === 'Enter' && handleJoin()}
          />
        </div>

        <div className="spacer" />

        <button
          className="btn"
          disabled={joinCode.length < 4 || !joinName.trim()}
          onClick={handleJoin}
        >
          ▶ Join Room
        </button>
        <button className="btn ghost" onClick={() => setView('landing')}>← Back</button>
      </div>
    );
  }

  // Default landing view
  return (
    <div className="screen fade-in">
      <Marquee title="Guessdit" subtitle="High-Speed Charades · No Talking!" />

      <div style={{ textAlign: 'center', marginBottom: 8 }}>
        <div style={{ color: 'var(--fg-dim)', fontSize: 14, lineHeight: 1.7 }}>
          Each team joins on their own phone.<br />
          The TV shows whatever you cast.
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 8 }}>
        <button
          className="btn go"
          onClick={() => { window.sfx && window.sfx.start(); onLocalMode && onLocalMode(); }}
        >
          ▶ Play Now · One Phone
        </button>
        <button
          className="btn"
          onClick={() => { window.sfx && window.sfx.pick(); setView('create'); }}
        >
          ★ Create Room · Multi-Device
        </button>
        <button
          className="btn secondary"
          onClick={() => { window.sfx && window.sfx.pick(); setView('join'); }}
        >
          → Join Existing Room
        </button>
      </div>

      {/* How to play */}
      <div style={{ ...panelStyle, marginTop: 16 }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>? How to Play</div>

        <div style={{ color: 'var(--accent-2)', fontFamily: 'var(--font-arcade)', fontSize: 9, letterSpacing: 2, marginBottom: 6 }}>
          ▶ ONE PHONE
        </div>
        <ol style={{ margin: '0 0 14px', paddingLeft: 22, color: 'var(--fg-dim)', fontSize: 13, lineHeight: 1.85 }}>
          <li>Enter team names and tap <b>Play Now</b></li>
          <li>Pass the phone to each team when prompted</li>
          <li><b>Pick 4 cards</b> secretly — don't show the others</li>
          <li><b>Order</b> them, then <b>act</b> — no talking, no sounds</li>
          <li>Pass back and repeat for every team</li>
        </ol>

        <div style={{ color: 'var(--accent)', fontFamily: 'var(--font-arcade)', fontSize: 9, letterSpacing: 2, marginBottom: 6 }}>
          ★ MULTI-DEVICE
        </div>
        <ol style={{ margin: 0, paddingLeft: 22, color: 'var(--fg-dim)', fontSize: 13, lineHeight: 1.85 }}>
          <li>Host creates a room and shares the 4-letter code</li>
          <li>Each team joins on <b>their own phone</b></li>
          <li>Idle teams watch the live <b style={{ color: 'var(--accent)' }}>timer</b> on their screen</li>
          <li>Everyone sees the same countdown — cast to a TV for maximum chaos</li>
        </ol>
      </div>

      <div className="spacer" />

      <div style={{ textAlign: 'center', fontFamily: 'var(--font-arcade)', fontSize: 8, letterSpacing: 3, color: 'var(--fg-quiet)', marginTop: 8, lineHeight: 2.2 }}>
        © 2026 · GUESSDIT · NO TALKING<br />
        <span style={{ color: 'var(--accent-2)', opacity: 0.7 }}>✦ MISCELLANEOUS GAMES ✦</span>
      </div>
    </div>
  );
}

const panelStyle = {
  background: 'rgba(255, 255, 255, 0.04)',
  border: '1px solid rgba(255, 255, 255, 0.07)',
  borderRadius: 'var(--r-lg)',
  padding: '16px 16px 18px',
};

window.LobbyScreen = LobbyScreen;
