// Room screen — what you see AFTER creating/joining a room.
// Host sees game mode selection + rounds config + start. Non-host sees "waiting for host".
// Persistent player avatars + presence + chat.

const AVATAR_COLORS = ['#E75002', '#3FA890', '#EEE4DA', '#ffb84a', '#ff7bb8', '#b9a4ff', '#9fd96a', '#ff5e5e'];

const SAMPLE_ROOM_PLAYERS = [
  { id: 1, name: 'Getza',   you: true,  host: true,  ready: true,  color: AVATAR_COLORS[0] },
  { id: 2, name: 'Lucía',                            ready: true,  color: AVATAR_COLORS[1] },
  { id: 3, name: 'Tomás',                            ready: false, color: AVATAR_COLORS[2] },
  { id: 4, name: 'Mariana',                          ready: true,  color: AVATAR_COLORS[3] },
];

const GAME_MODES = [
  { id: 'classic', name: 'Reverse Vox · Classic', tag: 'ORIGINAL',       status: 'ready', short: 'Graba · Invierte · Imita', desc: 'El juego original. Grabas una frase, se invierte, otro jugador la escucha e imita.', icon: 'mic' },
  { id: 'battle',  name: 'Reverse Battle',        tag: 'PRÓXIMAMENTE',   status: 'soon',  short: 'Duelos 1v1 por puntos',    desc: 'Dos jugadores imitan el mismo audio invertido, la sala vota quién se acercó más.',  icon: 'swords' },
  { id: 'chain',   name: 'Cadena Rota',           tag: 'PRÓXIMAMENTE',   status: 'soon',  short: 'Teléfono roto invertido',  desc: 'Cada jugador imita al anterior; la cadena se pasa. Al final comparamos.',            icon: 'chain' },
];

const SAMPLE_CHAT = [
  { id: 1, author: 'Lucía',   color: '#3FA890', text: '¡Hola! ¿Qué tal?', t: '20:14', self: false },
  { id: 2, author: 'Tomás',   color: '#EEE4DA', text: 'Listo para hacer el ridículo 😂', t: '20:14', self: false },
  { id: 3, author: 'Getza',   color: '#E75002', text: 'Esperen que configuro las rondas', t: '20:15', self: true },
];

function RoomScreen({
  onLeave, buttonStyle, isHost, chatLayout, sidebarCollapsed, setSidebarCollapsed,
  players: externalPlayers, roomCode: externalCode,
  rounds: externalRounds, setRounds: externalSetRounds,
  timer: externalTimer, setTimer: externalSetTimer,
  clipDuration: externalClipDuration, setClipDuration: externalSetClipDuration,
  onStart, onReady,
  chatMessages: externalMessages, onSendChat,
}) {
  const players = Array.isArray(externalPlayers) ? externalPlayers : [];

  const [modeInternal, setModeInternal] = React.useState('classic');
  const [roundsInternal, setRoundsInternal] = React.useState(3);
  const [timerInternal, setTimerInternal] = React.useState(45);
  const [clipDurationInternal, setClipDurationInternal] = React.useState(5);

  const mode = modeInternal;
  const setMode = setModeInternal;
  const rounds = externalRounds !== undefined ? externalRounds : roundsInternal;
  const setRounds = externalSetRounds || setRoundsInternal;
  const timer = externalTimer !== undefined ? externalTimer : timerInternal;
  const setTimer = externalSetTimer || setTimerInternal;
  const clipDuration = externalClipDuration !== undefined ? externalClipDuration : clipDurationInternal;
  const setClipDuration = externalSetClipDuration || setClipDurationInternal;

  const maxRounds = Math.max(1, players.length - 1);

  // Clamp rounds if players change
  React.useEffect(() => {
    if (rounds > maxRounds) setRounds(maxRounds);
  }, [maxRounds]);

  const myPlayer = players.find(p => p.you);
  const amReady = myPlayer ? myPlayer.ready : false;
  const allReady = players.length >= 2 && players.every(p => p.ready);

  const content = (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '16px 24px 24px', minHeight: 0 }}>
      <div className="rv-main" style={{
        display: 'grid',
        gridTemplateColumns: '320px 1fr',
        gap: 20,
        flex: 1,
        maxWidth: 1100,
        width: '100%',
        margin: '0 auto',
      }}>
        {/* Left column — room info + players + mic */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <RoomInfoCard onLeave={onLeave} buttonStyle={buttonStyle} isHost={isHost}
            playerCount={players.filter(p => p.id).length}
            code={externalCode || 'KM4P9X'}
            amReady={amReady}
            onReady={onReady ? () => onReady(amReady) : undefined}
          />
          <PlayersGrid players={players} />
          <MicCard compact />
        </div>

        {/* Right column — host controls or guest waiting + ad */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {isHost
            ? <HostControls mode={mode} setMode={setMode}
                rounds={rounds} setRounds={setRounds}
                maxRounds={maxRounds}
                timer={timer} setTimer={setTimer}
                clipDuration={clipDuration} setClipDuration={setClipDuration}
                buttonStyle={buttonStyle}
                onStart={onStart}
                canStart={allReady}
              />
            : <GuestWaiting />
          }
          <AdSidebarCard />
        </div>
      </div>
    </div>
  );

  if (chatLayout === 'sidebar') {
    return (
      <div style={{ display: 'flex', flex: 1, minHeight: 0 }}>
        <div style={{ flex: 1, minWidth: 0 }}>{content}</div>
        <ChatSidebar players={players} collapsed={sidebarCollapsed} setCollapsed={setSidebarCollapsed}
          buttonStyle={buttonStyle}
          externalMessages={externalMessages}
          onSend={onSendChat}
        />
      </div>
    );
  }
  return (
    <>
      {content}
      <FloatingChat players={players} buttonStyle={buttonStyle}
        externalMessages={externalMessages}
        onSend={onSendChat}
      />
    </>
  );
}

// ─────────────────────────────────────────────
function RoomInfoCard({ onLeave, buttonStyle, isHost, playerCount, code, amReady, onReady }) {
  const [showCode, setShowCode] = React.useState(true);
  const [copied, setCopied] = React.useState(false);
  const onCopy = () => {
    const url = new URL(window.location.href);
    url.searchParams.set('room', code);
    navigator.clipboard?.writeText(url.toString());
    setCopied(true);
    setTimeout(() => setCopied(false), 1200);
  };

  return (
    <section style={{
      background: 'var(--panel)',
      border: '1px solid var(--line)',
      borderTop: '3px solid var(--amber)',
      borderRadius: 4, padding: '18px 20px',
      position: 'relative',
    }}>
      <div style={{ position: 'absolute', top: 0, right: 80, width: 30, height: 3, background: 'var(--teal)' }} />
      <div style={{ position: 'absolute', top: 0, right: 24, width: 50, height: 3, background: 'var(--taupe)' }} />

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
        <div style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: 3, fontWeight: 700, color: 'var(--amber)' }}>
          ▸ SALA CONECTADA <span style={{ color: 'var(--taupe)' }}>· {playerCount}/8</span>
        </div>
        <button onClick={onLeave} style={{
          background: 'transparent', border: '1px solid rgba(255,59,59,0.35)',
          color: 'var(--danger)', padding: '4px 10px', borderRadius: 3,
          fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: 2, cursor: 'pointer', fontWeight: 700,
        }}>× SALIR</button>
      </div>

      <div style={{
        display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap',
        padding: 12, background: 'rgba(200,184,169,0.04)', borderRadius: 3,
        border: '1px dashed var(--line2)',
      }}>
        <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--taupe)', letterSpacing: 2, fontWeight: 600 }}>CÓDIGO</div>
        <div style={{
          fontFamily: 'var(--mono)', fontSize: 22, color: 'var(--cream)',
          letterSpacing: 5, background: '#000',
          padding: '6px 14px', borderRadius: 3, fontWeight: 700,
          border: '1px solid var(--taupe)',
          filter: showCode ? 'none' : 'blur(6px)',
          transition: 'filter 0.2s',
        }}>{code}</div>
        <button onClick={() => setShowCode(!showCode)} style={{ background: 'transparent', border: '1px solid var(--line2)', color: 'var(--taupe)', padding: '6px 10px', borderRadius: 3, cursor: 'pointer', fontSize: 13 }}>
          {showCode ? '🙈' : '👁'}
        </button>
        <button onClick={onCopy} style={{
          background: copied ? 'var(--teal)' : 'transparent',
          color: copied ? '#000' : 'var(--taupe)',
          border: copied ? '1px solid var(--teal)' : '1px solid var(--line2)',
          padding: '6px 12px', fontSize: 11, fontFamily: 'var(--mono)', letterSpacing: 1,
          borderRadius: 3, cursor: 'pointer', fontWeight: 700,
        }}>{copied ? '✓ COPIADO' : '🔗 COPIAR ENLACE'}</button>
      </div>

      {!isHost && (
        <div style={{
          marginTop: 12, padding: '10px 12px', background: 'rgba(63,168,144,0.08)',
          border: '1px solid rgba(63,168,144,0.25)', borderRadius: 3,
          fontSize: 12, color: 'var(--text-dim)',
        }}>
          <span style={{ fontFamily: 'var(--mono)', color: 'var(--teal)', fontSize: 10, letterSpacing: 2, marginRight: 8, fontWeight: 700 }}>INFO</span>
          El anfitrión está eligiendo el modo de juego. Marca <strong style={{ color: 'var(--cream)' }}>Estoy listo</strong> cuando puedas jugar.
        </div>
      )}

      <div style={{ display: 'flex', gap: 10, marginTop: 14 }}>
        <button onClick={onReady} style={{
          flex: 1, padding: '12px', borderRadius: 3, fontSize: 14, fontWeight: 700,
          cursor: 'pointer', letterSpacing: 1,
          background: amReady ? 'var(--teal)' : undefined,
          color: amReady ? '#000' : undefined,
          border: amReady ? '2px solid var(--teal)' : undefined,
          ...(!amReady ? buttonStyleFor(buttonStyle) : {}),
        }}>
          {amReady ? '✓ LISTO' : '● ESTOY LISTO'}
        </button>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────
function PlayersGrid({ players }) {
  return (
    <Panel title="JUGADORES" titleRight={
      <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--teal)', letterSpacing: 2 }}>
        ● {players.filter(p => p.id).length} CONECTADOS
      </div>
    }>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
        {Array.from({ length: 8 }).map((_, i) => {
          const p = players[i];
          const isYou = p?.you;
          return (
            <div key={i} style={{
              aspectRatio: '1',
              background: p ? (isYou ? 'rgba(231,80,2,0.10)' : 'var(--panel2)') : 'transparent',
              border: p ? (isYou ? '1px solid var(--amber)' : '1px solid var(--line2)') : '1px dashed var(--line)',
              borderRadius: 4, padding: 8, display: 'flex', flexDirection: 'column',
              alignItems: 'center', justifyContent: 'center', gap: 4, position: 'relative',
            }}>
              {p ? (
                <>
                  <div style={{
                    width: 38, height: 38, borderRadius: '50%',
                    background: p.color,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontWeight: 700, fontSize: 15, color: '#000',
                    border: '2px solid var(--taupe)',
                  }}>{p.name.slice(0, 1)}</div>
                  <div style={{ fontSize: 11, color: 'var(--cream)', textAlign: 'center', maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: 600 }}>
                    {p.name}{isYou ? ' (tú)' : ''}
                  </div>
                  <div style={{ display: 'flex', gap: 4, fontFamily: 'var(--mono)', fontSize: 8, letterSpacing: 1, fontWeight: 700 }}>
                    {p.host && <span style={{ color: 'var(--amber)' }}>HOST</span>}
                    <span style={{ color: p.ready ? 'var(--teal)' : 'var(--taupe-dim)' }}>{p.ready ? '✓ READY' : '…'}</span>
                  </div>
                </>
              ) : (
                <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--dim)' }}>{String(i + 1).padStart(2, '0')}</span>
              )}
            </div>
          );
        })}
      </div>
    </Panel>
  );
}

// ─────────────────────────────────────────────
function HostControls({ mode, setMode, rounds, setRounds, maxRounds, timer, setTimer, clipDuration, setClipDuration, buttonStyle, onStart, canStart }) {
  const current = GAME_MODES.find(m => m.id === mode);
  const timerHint = timer <= 35 ? 'Rápido · al toque' : timer <= 50 ? 'Recomendado' : 'Cómodo · pensado';
  const clipHint = clipDuration <= 4 ? 'Muy corto' : clipDuration === 5 ? 'Recomendado ★' : clipDuration <= 8 ? 'Moderado' : clipDuration <= 12 ? 'Cómodo' : 'Largo';
  return (
    <Panel title="MODO DE JUEGO · SOLO ANFITRIÓN" titleRight={
      <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--dim)', letterSpacing: 2 }}>
        {GAME_MODES.filter(m => m.status === 'ready').length} DISP. · {GAME_MODES.filter(m => m.status === 'soon').length} PRÓX.
      </div>
    }>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {GAME_MODES.map(m => (
          <ModeCard key={m.id} mode={m} selected={mode === m.id && m.status === 'ready'}
            onSelect={() => m.status === 'ready' && setMode(m.id)} />
        ))}
      </div>

      {current && current.status === 'ready' && (
        <div style={{
          marginTop: 18, padding: '20px 16px 16px',
          background: 'linear-gradient(180deg, rgba(0,0,0,0.45), rgba(0,0,0,0.25))',
          border: '1px solid var(--line)', borderRadius: 4, position: 'relative',
        }}>
          <div style={{
            position: 'absolute', top: -10, left: 14,
            background: 'var(--panel)', padding: '0 10px',
            fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--amber)', letterSpacing: 3,
          }}>▸ CONFIGURACIÓN</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12, paddingTop: 6 }}>
            <Knob label="RONDAS" min={1} max={maxRounds} step={1}
              value={rounds} onChange={setRounds} unit={rounds}
              hint={`Máx · ${maxRounds} (N−1)`}
              color="var(--amber)" size={72} />
            <Knob label="TIEMPO FASE" min={30} max={60} step={5}
              value={timer} onChange={setTimer} unit={`${timer}s`}
              hint={timerHint}
              color="var(--teal)" size={72} />
            <Knob label="DURACIÓN CLIP" min={3} max={15} step={1}
              value={clipDuration} onChange={setClipDuration} unit={`${clipDuration}s`}
              hint={clipHint}
              color="var(--amber2)" size={72} />
          </div>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            marginTop: 14, paddingTop: 12, borderTop: '1px dashed var(--line)',
            fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: 2, color: 'var(--dim)',
          }}>
            <span>● PWR</span><span>● MIX</span>
            <span style={{ color: 'var(--teal)' }}>● READY</span>
            <span>{rounds} × {timer}s · clip {clipDuration}s</span>
          </div>
        </div>
      )}

      <button onClick={canStart ? onStart : undefined} disabled={!canStart} style={{
        marginTop: 16, width: '100%', padding: '16px', borderRadius: 3,
        fontSize: 15, fontWeight: 700, letterSpacing: 1,
        cursor: canStart ? 'pointer' : 'not-allowed',
        opacity: canStart ? 1 : 0.4,
        ...buttonStyleFor(buttonStyle),
      }}>
        {canStart ? '▶ INICIAR PARTIDA' : '⏳ Esperando que todos estén listos…'}
      </button>
    </Panel>
  );
}

function ModeCard({ mode, selected, onSelect }) {
  const isReady = mode.status === 'ready';
  return (
    <div onClick={onSelect} style={{
      position: 'relative',
      background: selected ? 'rgba(63,168,144,0.10)' : 'var(--panel2)',
      color: 'var(--text)',
      border: selected ? '1px solid var(--teal)' : '1px solid var(--line)',
      borderLeft: selected ? '4px solid var(--teal)' : '1px solid var(--line)',
      borderRadius: 4, padding: '12px 14px',
      cursor: isReady ? 'pointer' : 'default',
      opacity: isReady ? 1 : 0.55,
      transition: 'background 0.15s, border-color 0.15s',
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        <ModeIcon kind={mode.icon} selected={selected} disabled={!isReady} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 2 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--cream)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1, minWidth: 0 }}>{mode.name}</div>
            <div style={{
              fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: 2,
              padding: '2px 6px', borderRadius: 2, flexShrink: 0, fontWeight: 700,
              background: 'transparent',
              color: isReady ? 'var(--teal)' : 'var(--taupe-dim)',
              border: `1px solid ${isReady ? 'rgba(63,168,144,0.4)' : 'var(--line)'}`,
            }}>{mode.tag}</div>
          </div>
          <div style={{ fontSize: 11, color: 'var(--taupe)', marginBottom: 4 }}>{mode.short}</div>
          <div style={{ fontSize: 11, color: 'var(--dim)', lineHeight: 1.5 }}>{mode.desc}</div>
        </div>
        {selected && (
          <div style={{
            width: 22, height: 22, borderRadius: '50%', background: 'var(--teal)',
            color: '#000', display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontWeight: 700, fontSize: 13, flexShrink: 0,
          }}>✓</div>
        )}
      </div>
    </div>
  );
}

function ModeIcon({ kind, selected, disabled }) {
  const bg = selected ? 'var(--teal)' : 'var(--panel)';
  const color = selected ? '#000' : disabled ? 'var(--dim)' : 'var(--amber)';
  const size = 36;
  return (
    <div style={{ width: size, height: size, borderRadius: 4, flexShrink: 0, background: bg, border: selected ? 'none' : '1px solid var(--line2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <svg width="18" height="18" viewBox="0 0 20 20" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
        {kind === 'mic' && (<><rect x="7" y="2" width="6" height="11" rx="3" /><path d="M3 10a7 7 0 0 0 14 0M10 17v2" /></>)}
        {kind === 'swords' && (<><path d="M14 3l4 4-7 7-4-4 7-7zM3 14l4 4M14 17l3-3" /></>)}
        {kind === 'chain' && (<><path d="M8 12l4-4M6 10a3 3 0 0 1 0-4l2-2a3 3 0 0 1 4 4M14 10a3 3 0 0 1 0 4l-2 2a3 3 0 0 1-4-4" /></>)}
      </svg>
    </div>
  );
}

// ─────────────────────────────────────────────
function GuestWaiting() {
  return (
    <Panel title="ESPERANDO AL ANFITRIÓN">
      <div style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16,
        padding: '32px 20px', textAlign: 'center',
        background: 'var(--panel2)', borderRadius: 4,
        border: '1px solid var(--line2)', borderTop: '3px solid var(--teal)',
        position: 'relative',
      }}>
        <div style={{
          width: 56, height: 56, borderRadius: '50%', border: '4px solid rgba(200,184,169,0.12)',
          borderTopColor: 'var(--teal)', animation: 'rvspin 0.9s linear infinite',
        }} />
        <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--cream)', fontFamily: '"Fredoka", system-ui, sans-serif' }}>
          El anfitrión está configurando la partida
        </div>
        <div style={{ fontSize: 12, color: 'var(--taupe)', maxWidth: 280, lineHeight: 1.5 }}>
          Cuando elija el modo y arranque, empezará la primera ronda.
          Aprovecha para probar el micrófono y chatear con el resto.
        </div>
      </div>
    </Panel>
  );
}

function AdSidebarCard() {
  return (
    <div style={{
      border: '1px dashed rgba(255,255,255,0.08)', borderRadius: 3, padding: 18,
      background: 'rgba(255,255,255,0.015)',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
    }}>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--dim)', letterSpacing: 2 }}>[ SPONSOR · 300×250 ]</div>
      <div style={{
        width: '100%', height: 200,
        background: `repeating-linear-gradient(45deg, transparent 0 8px, rgba(255,255,255,0.02) 8px 16px)`,
        border: '1px dashed rgba(255,255,255,0.08)', borderRadius: 3,
        display: 'flex', alignItems: 'center', justifyContent: 'center', textAlign: 'center',
        fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--dim)', letterSpacing: 1, padding: 16,
      }}>espacio para patrocinador<br/>no se muestra durante<br/>la partida activa</div>
    </div>
  );
}

// ═════════════════════════════════════════════
// CHAT
// ═════════════════════════════════════════════

function ChatSidebar({ players, collapsed, setCollapsed, buttonStyle, externalMessages, onSend }) {
  const [input, setInput] = React.useState('');
  const scrollRef = React.useRef(null);

  const messages = Array.isArray(externalMessages) ? externalMessages : [];

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  const send = async (e) => {
    e?.preventDefault();
    const text = input.trim();
    if (!text || !onSend) return;
    setInput('');
    await onSend(text);
  };

  if (collapsed) {
    return (
      <button onClick={() => setCollapsed(false)} style={{
        width: 44, flexShrink: 0, background: 'var(--panel)', borderLeft: '1px solid var(--line)',
        border: 'none', borderLeft: '1px solid var(--line)',
        color: 'var(--amber)', cursor: 'pointer', display: 'flex',
        flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 14,
        fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: 2,
        padding: '20px 0', writingMode: 'vertical-rl', transform: 'rotate(180deg)',
      }}>
        <span>◂ CHAT · {messages.length}</span>
      </button>
    );
  }

  return (
    <aside style={{
      width: 340, flexShrink: 0,
      background: 'var(--panel)', borderLeft: '1px solid var(--line)',
      display: 'flex', flexDirection: 'column',
      maxHeight: 'calc(100vh - 120px)', position: 'sticky', top: 0,
    }}>
      <div style={{
        padding: '14px 16px', borderBottom: '1px solid var(--line)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        background: 'linear-gradient(180deg, rgba(231,80,2,0.05), transparent)',
      }}>
        <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--amber)', letterSpacing: 3 }}>▸ CHAT DE LA SALA</div>
        <button onClick={() => setCollapsed(true)} style={{ background: 'transparent', border: 'none', color: 'var(--taupe)', fontSize: 18, cursor: 'pointer', padding: 0, lineHeight: 1 }}>×</button>
      </div>
      <div style={{
        padding: '8px 12px', borderBottom: '1px solid var(--line)',
        display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center',
        background: 'rgba(0,0,0,0.25)',
      }}>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--taupe)', letterSpacing: 2, marginRight: 4 }}>EN SALA</span>
        {players.map(p => (
          <div key={p.id} title={p.name} style={{
            width: 22, height: 22, borderRadius: '50%', background: p.color,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 10, fontWeight: 700, color: '#000',
            border: p.you ? '2px solid var(--amber)' : '1.5px solid var(--taupe)',
          }}>{p.name.slice(0, 1)}</div>
        ))}
      </div>
      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {messages.map(m => <ChatMessage key={m.id} msg={m} />)}
      </div>
      <form onSubmit={send} style={{ padding: 10, borderTop: '1px solid var(--line)', display: 'flex', gap: 6, background: 'var(--panel2)' }}>
        <input value={input} onChange={e => setInput(e.target.value)}
          placeholder="Escribe un mensaje..." maxLength={300}
          style={{ flex: 1, background: 'var(--panel)', border: '1px solid var(--line)', color: 'var(--text)', padding: '9px 12px', borderRadius: 3, outline: 'none', fontSize: 13 }}
        />
        <button type="submit" style={{ padding: '0 14px', borderRadius: 3, fontSize: 14, fontWeight: 600, cursor: 'pointer', ...buttonStyleFor(buttonStyle) }}>➤</button>
      </form>
    </aside>
  );
}

function ChatMessage({ msg }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: msg.self ? 'flex-end' : 'flex-start', maxWidth: '100%' }}>
      <div style={{ display: 'flex', gap: 8, alignItems: 'baseline', marginBottom: 2, fontSize: 10, fontFamily: 'var(--mono)' }}>
        <span style={{ color: msg.color, fontWeight: 700, letterSpacing: 1 }}>{msg.self ? 'TÚ' : msg.author.toUpperCase()}</span>
        <span style={{ color: 'var(--dim)', opacity: 0.7 }}>{msg.t}</span>
      </div>
      <div style={{
        padding: '8px 12px', borderRadius: 3, fontSize: 13, lineHeight: 1.4,
        maxWidth: '85%', wordBreak: 'break-word',
        background: msg.self ? 'rgba(231,80,2,0.10)' : 'var(--panel2)',
        border: msg.self ? '1px solid var(--amber)' : '1px solid var(--line)',
        color: 'var(--text)',
      }}>{msg.text}</div>
    </div>
  );
}

function FloatingChat({ players, buttonStyle, externalMessages, onSend }) {
  const [open, setOpen] = React.useState(false);
  const [input, setInput] = React.useState('');
  const [unread, setUnread] = React.useState(0);
  const scrollRef = React.useRef(null);

  const messages = Array.isArray(externalMessages) ? externalMessages : [];

  React.useEffect(() => {
    if (open && scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, open]);

  const send = async (e) => {
    e?.preventDefault();
    const text = input.trim();
    if (!text || !onSend) return;
    setInput('');
    await onSend(text);
  };

  return (
    <>
      <button onClick={() => { setOpen(!open); setUnread(0); }} style={{
        position: 'fixed', bottom: 120, right: 24, zIndex: 50,
        width: 56, height: 56, borderRadius: '50%',
        background: 'var(--amber)', color: '#0e0b08', border: 'none',
        fontSize: 22, cursor: 'pointer',
        boxShadow: '0 8px 24px rgba(255,138,61,0.35), 0 0 0 4px rgba(255,138,61,0.12)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        💬
        {unread > 0 && !open && (
          <span style={{ position: 'absolute', top: -4, right: -4, minWidth: 20, height: 20, padding: '0 6px', borderRadius: 10, background: 'var(--danger)', color: '#fff', fontSize: 11, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', border: '2px solid var(--bg)' }}>{unread}</span>
        )}
      </button>
      {open && (
        <div style={{
          position: 'fixed', bottom: 190, right: 24, zIndex: 50,
          width: 360, maxWidth: 'calc(100vw - 48px)', height: 480, maxHeight: 'calc(100vh - 220px)',
          background: 'var(--panel)', border: '1px solid var(--line2)', borderRadius: 6,
          display: 'flex', flexDirection: 'column',
          boxShadow: '0 24px 60px rgba(0,0,0,0.6)',
        }}>
          <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--amber)', letterSpacing: 3 }}>▸ CHAT · {players.length} EN SALA</div>
            <button onClick={() => setOpen(false)} style={{ background: 'transparent', border: 'none', color: 'var(--dim)', fontSize: 18, cursor: 'pointer' }}>×</button>
          </div>
          <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
            {messages.map(m => <ChatMessage key={m.id} msg={m} />)}
          </div>
          <form onSubmit={send} style={{ padding: 10, borderTop: '1px solid var(--line)', display: 'flex', gap: 6, background: 'var(--panel2)' }}>
            <input value={input} onChange={e => setInput(e.target.value)}
              placeholder="Escribe un mensaje..." maxLength={300}
              style={{ flex: 1, background: 'var(--panel)', border: '1px solid var(--line)', color: 'var(--text)', padding: '9px 12px', borderRadius: 3, outline: 'none', fontSize: 13 }}
            />
            <button type="submit" style={{ padding: '0 14px', borderRadius: 3, fontSize: 14, fontWeight: 600, cursor: 'pointer', ...buttonStyleFor(buttonStyle) }}>➤</button>
          </form>
        </div>
      )}
    </>
  );
}

Object.assign(window, { RoomScreen, ChatSidebar, FloatingChat });
