// Componente Atómico Memoizado: Consola de Controles del Organizador
const { memo, useState, useCallback, useRef } = React;

const ControlesOrganizador = memo(function ControlesOrganizador({
  calledBallsCount = 0,
  calledBalls = [],
  isAutoDrawing = false,
  drawPausedByPrize = false,
  countdown = 5,
  voiceEnabled = true,
  isRafflingCard = false,
  prizeCardRaffleWinner = null,
  prizeBingoWinner = null,
  showMatrix = false,
  currentRound = 1,
  roundBingoPrize = 100000,
  onSetActiveRound,
  onDrawNextBall,
  onCallSpecificBall,
  onToggleAutoDraw,
  onResetGame,
  onRaffleCardNumber,
  onToggleMatrix,
  onToggleVoice,
  onOpenVoiceSettings
}) {
  const [manualBallInput, setManualBallInput] = useState('');
  const [inputError, setInputError] = useState('');
  const [isCalling, setIsCalling] = useState(false);
  const inputRef = useRef(null);

  const handleManualSubmit = useCallback(async (e) => {
    if (e) e.preventDefault();
    const val = parseInt(manualBallInput.trim(), 10);
    if (isNaN(val) || val < 1 || val > 90) {
      setInputError('Ingresa un número de bolilla válido (1 - 90)');
      return;
    }
    if (calledBalls.includes(val)) {
      setInputError(`La bolilla ${val} ya fue cantada previamente.`);
      return;
    }

    setInputError('');
    if (onCallSpecificBall) {
      setIsCalling(true);
      const res = await onCallSpecificBall(val);
      setIsCalling(false);
      if (res && res.success) {
        setManualBallInput('');
        if (inputRef.current) inputRef.current.focus();
      } else if (res && res.error) {
        setInputError(res.error);
      }
    }
  }, [manualBallInput, calledBalls, onCallSpecificBall]);

  const handleInputChange = (e) => {
    const raw = e.target.value.replace(/[^0-9]/g, '');
    if (raw.length > 2) return; // Máximo 2 dígitos (1 - 90)
    setManualBallInput(raw);
    if (!raw) {
      setInputError('');
      return;
    }
    const num = parseInt(raw, 10);
    if (num > 90) {
      setInputError('El bolillero solo contiene números hasta el 90.');
    } else if (calledBalls.includes(num)) {
      setInputError(`⚠️ La bolilla ${num} ya fue cantada.`);
    } else {
      setInputError('');
    }
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '14px', width: '100%' }}>
      {/* =========================================================================
          1. CARGA MANUAL DE BOLILLAS (Ideal para sorteo con bolillero físico y video)
         ========================================================================= */}
      <div style={{
        background: 'linear-gradient(135deg, rgba(15, 23, 42, 0.85), rgba(30, 41, 59, 0.95))',
        border: '1.5px solid rgba(0, 172, 193, 0.4)',
        borderRadius: 'var(--radius-lg)',
        padding: '14px 16px',
        boxShadow: '0 4px 18px rgba(0, 172, 193, 0.1)'
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <span style={{ 
              backgroundColor: 'var(--accent-teal)', 
              color: '#ffffff', 
              width: '26px', 
              height: '26px', 
              borderRadius: '50%', 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'center', 
              fontSize: '0.85rem'
            }}>
              🎱
            </span>
            <span style={{ fontSize: '0.94rem', fontWeight: '800', color: '#ffffff' }}>
              Cargar Bolilla de tu Bolillero Físico
            </span>
          </div>
          <span style={{ fontSize: '0.75rem', color: 'var(--accent-teal)', fontWeight: '700' }}>
            {90 - calledBallsCount} restantes
          </span>
        </div>

        <form onSubmit={handleManualSubmit} style={{ display: 'flex', gap: '10px', alignItems: 'center' }}>
          <div style={{ position: 'relative', flex: '0 0 100px' }}>
            <input
              ref={inputRef}
              type="text"
              inputMode="numeric"
              placeholder="1-90"
              value={manualBallInput}
              onChange={handleInputChange}
              disabled={isCalling || calledBallsCount >= 90}
              style={{
                width: '100%',
                padding: '10px 8px',
                fontSize: '1.3rem',
                fontWeight: '900',
                fontFamily: 'var(--font-numbers)',
                textAlign: 'center',
                backgroundColor: 'rgba(15, 23, 42, 0.95)',
                border: inputError ? '2px solid #ef4444' : '2px solid var(--accent-teal)',
                borderRadius: 'var(--radius-md)',
                color: '#ffffff',
                outline: 'none',
                boxShadow: 'inset 0 2px 4px rgba(0,0,0,0.5)'
              }}
            />
          </div>

          <button
            type="submit"
            className="btn btn-primary"
            disabled={!manualBallInput || isCalling || Boolean(inputError) || calledBallsCount >= 90}
            style={{
              flex: 1,
              padding: '12px 16px',
              fontSize: '0.96rem',
              fontWeight: '800',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: '8px',
              background: 'linear-gradient(135deg, var(--accent-teal), #0284c7)'
            }}
          >
            <i className={`fa-solid ${isCalling ? 'fa-spinner fa-spin' : 'fa-bullhorn'}`}></i>
            <span>{isCalling ? 'Procesando...' : 'Cargar y Cantar Bolilla'}</span>
          </button>
        </form>

        {inputError && (
          <div style={{ 
            marginTop: '8px', 
            fontSize: '0.8rem', 
            color: '#f87171', 
            fontWeight: '600',
            display: 'flex',
            alignItems: 'center',
            gap: '6px'
          }}>
            <i className="fa-solid fa-triangle-exclamation"></i>
            <span>{inputError}</span>
          </div>
        )}

        <div style={{ marginTop: '8px', fontSize: '0.74rem', color: 'var(--text-muted)' }}>
          💡 <strong style={{ color: 'var(--text-main)' }}>Tip:</strong> También puedes abrir el <em>Tablero 1-90</em> y hacer clic directamente sobre cualquier bolilla disponible.
        </div>
      </div>

      {/* =========================================================================
          2. EXTRACCIÓN AUTOMÁTICA O ALEATORIA ALTERNATIVA
         ========================================================================= */}
      <div style={{ display: 'flex', gap: '10px' }}>
        <button 
          className="btn btn-secondary" 
          style={{ flex: 1, padding: '10px', fontSize: '0.88rem', fontWeight: '700' }}
          onClick={onDrawNextBall}
          disabled={calledBallsCount >= 90 || isAutoDrawing}
          title="Extrae una bolilla aleatoria no cantada desde PostgreSQL"
        >
          <i className="fa-solid fa-shuffle"></i>
          Extraer al Azar
        </button>

        <button 
          className={`btn ${isAutoDrawing ? 'btn-secondary' : drawPausedByPrize ? 'btn-accent' : 'btn-secondary'}`}
          style={{ 
            flex: 1, 
            padding: '10px', 
            fontSize: '0.88rem', 
            backgroundColor: isAutoDrawing ? '#f59e0b' : drawPausedByPrize ? 'var(--accent-green)' : undefined,
            color: isAutoDrawing ? '#111827' : undefined,
            fontWeight: '700'
          }}
          onClick={onToggleAutoDraw}
          disabled={calledBallsCount >= 90}
        >
          <i className={`fa-solid ${isAutoDrawing ? 'fa-pause' : drawPausedByPrize ? 'fa-play' : 'fa-bolt'}`}></i>
          {isAutoDrawing ? `Pausar Auto (${countdown}s)` : drawPausedByPrize ? '▶ Continuar Auto' : 'Sorteo Auto (5s)'}
        </button>
      </div>

      {/* =========================================================================
          3. SELECTOR DE PREMIOS OFICIALES ("Lota Familiar La Mami: 3 -> 2 -> 1")
         ========================================================================= */}
      <div style={{
        background: 'linear-gradient(135deg, rgba(15, 23, 42, 0.9), rgba(30, 41, 59, 0.95))',
        border: '1.5px solid rgba(245, 158, 11, 0.45)',
        borderRadius: 'var(--radius-md)',
        padding: '12px 14px',
        display: 'flex',
        flexDirection: 'column',
        gap: '10px'
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '8px' }}>
          <span style={{ fontSize: '0.86rem', fontWeight: '900', color: 'var(--accent-gold)', display: 'flex', alignItems: 'center', gap: '6px' }}>
            <i className="fa-solid fa-layer-group"></i> ETAPA DEL SORTEO: ¿En qué premio te encuentras?
          </span>
          <span style={{ fontSize: '0.78rem', color: 'var(--text-muted)' }}>
            Sorteando ahora: <strong style={{ color: currentRound === 1 ? 'var(--accent-gold)' : 'var(--accent-green)' }}>
              {currentRound === 1 ? 'Premio 1 Mayor ($100k)' : currentRound === 2 ? 'Premio 2 ($50k)' : 'Premio 3 ($50k)'}
            </strong>
          </span>
        </div>

        <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
          {[
            { round: 3, label: '1°: Premio 3', prize: '$50.000', badge: '1° Sorteo' },
            { round: 2, label: '2°: Premio 2', prize: '$50.000', badge: '2° Sorteo' },
            { round: 1, label: '3°: Premio 1 Mayor', prize: '$100.000', badge: 'POZO MAYOR' }
          ].map(r => {
            const isCurrent = currentRound === r.round;
            return (
              <button
                key={r.round}
                type="button"
                onClick={() => onSetActiveRound && onSetActiveRound(r.round)}
                className={`btn btn-sm ${isCurrent ? (r.round === 1 ? 'btn-accent' : 'btn-primary') : 'btn-secondary'}`}
                style={{
                  flex: '1 1 120px',
                  padding: '9px 8px',
                  fontSize: '0.84rem',
                  fontWeight: '800',
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  gap: '3px',
                  background: isCurrent 
                    ? (r.round === 1 ? 'linear-gradient(135deg, #f59e0b, #d97706)' : 'linear-gradient(135deg, #10b981, #059669)') 
                    : undefined,
                  color: isCurrent ? (r.round === 1 ? '#111827' : '#ffffff') : undefined,
                  border: isCurrent ? (r.round === 1 ? '2px solid #fbbf24' : '2px solid #34d399') : '1px solid rgba(255, 255, 255, 0.1)',
                  boxShadow: isCurrent ? (r.round === 1 ? '0 0 14px rgba(245, 158, 11, 0.45)' : '0 0 12px rgba(16, 185, 129, 0.4)') : 'none',
                  cursor: 'pointer'
                }}
                title={`Activar y situarme en Premio ${r.round} (Bingo ${r.prize} + Línea $10.000)`}
              >
                <span style={{ fontSize: '0.7rem', opacity: isCurrent ? 0.9 : 0.65, fontWeight: '700', textTransform: 'uppercase' }}>
                  {r.badge}
                </span>
                <span>{isCurrent ? '🎯' : '⚪'} {r.label}</span>
                <span style={{ fontSize: '0.74rem', opacity: isCurrent ? 1 : 0.8, fontWeight: '800' }}>
                  Bingo {r.prize}
                </span>
              </button>
            );
          })}
        </div>
      </div>

      {/* =========================================================================
          4. GRAN SORTEO FINAL POR N° DE CARTÓN (Desbloqueado al Finalizar el Premio 1 Mayor)
         ========================================================================= */}
      {(() => {
        const isAllRoundsFinished = (currentRound === 1 && Boolean(prizeBingoWinner)) || (currentRound === 3 && Boolean(prizeBingoWinner)) || Boolean(prizeCardRaffleWinner);
        const isRaffleUnlocked = isAllRoundsFinished || Boolean(prizeCardRaffleWinner);

        return (
          <div style={{
            background: prizeCardRaffleWinner
              ? 'linear-gradient(135deg, rgba(16, 185, 129, 0.15), rgba(15, 23, 42, 0.7))'
              : isAllRoundsFinished
              ? 'linear-gradient(135deg, rgba(16, 185, 129, 0.25), rgba(14, 116, 144, 0.35))'
              : 'rgba(15, 23, 42, 0.7)',
            border: prizeCardRaffleWinner
              ? '1.5px solid var(--accent-green)'
              : isAllRoundsFinished
              ? '2px solid var(--accent-green)'
              : '1.5px dashed rgba(148, 163, 184, 0.25)',
            borderRadius: 'var(--radius-md)',
            padding: '12px 16px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            flexWrap: 'wrap',
            gap: '12px',
            boxShadow: isAllRoundsFinished && !prizeCardRaffleWinner ? '0 0 20px rgba(16, 185, 129, 0.3)' : 'none',
            transition: 'all 0.3s ease'
          }}>
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
                <span style={{ fontSize: '0.92rem', fontWeight: '800', color: isRaffleUnlocked ? '#38bdf8' : 'var(--text-muted)' }}>
                  🎟️ Gran Sorteo Final por N° de Cartón ($10.000)
                </span>
                <span style={{ 
                  fontSize: '0.68rem', 
                  backgroundColor: prizeCardRaffleWinner 
                    ? 'var(--accent-green)' 
                    : isAllRoundsFinished 
                    ? 'var(--accent-green)' 
                    : 'rgba(239, 68, 68, 0.2)', 
                  color: prizeCardRaffleWinner || isAllRoundsFinished ? '#111827' : '#fca5a5',
                  padding: '2px 8px',
                  borderRadius: '4px',
                  fontWeight: '900',
                  border: !isRaffleUnlocked ? '1px solid rgba(239, 68, 68, 0.3)' : 'none'
                }}>
                  {prizeCardRaffleWinner 
                    ? '✓ FINALIZADO' 
                    : isAllRoundsFinished 
                    ? '🎉 ¡DESBLOQUEADO! ETAPA FINAL' 
                    : `🔒 BLOQUEADO (Ronda ${currentRound} de 3)`}
                </span>
              </div>

              <div style={{ fontSize: '0.78rem', color: isAllRoundsFinished ? '#a7f3d0' : 'var(--text-muted)', marginTop: '4px' }}>
                {prizeCardRaffleWinner ? (
                  <span style={{ color: 'var(--accent-green)', fontWeight: '700' }}>
                    ✓ ¡Cartón Ganador: {prizeCardRaffleWinner.title} ({prizeCardRaffleWinner.cardId})!
                  </span>
                ) : isAllRoundsFinished ? (
                  '⭐ ¡Los 3 Premios Mayores de Bingo han finalizado! Pulsa el botón para realizar el Gran Sorteo Final.'
                ) : currentRound === 3 ? (
                  '🔒 Se desbloqueará automáticamente al cantarse el BINGO de este Premio 3.'
                ) : (
                  `🔒 Bloqueado: Se desbloqueará automáticamente al finalizar todos los premios (Premio 3 Bingo).`
                )}
              </div>
            </div>

            <button 
              type="button"
              className="btn btn-sm"
              onClick={onRaffleCardNumber}
              disabled={!isAllRoundsFinished || isRafflingCard || prizeCardRaffleWinner !== null}
              style={{ 
                fontWeight: '900', 
                fontSize: '0.85rem',
                background: prizeCardRaffleWinner 
                  ? 'rgba(16, 185, 129, 0.2)' 
                  : isAllRoundsFinished 
                  ? 'linear-gradient(135deg, #10b981, #0284c7)' 
                  : 'rgba(51, 65, 85, 0.6)',
                color: isAllRoundsFinished && !prizeCardRaffleWinner ? '#ffffff' : 'var(--text-muted)',
                border: prizeCardRaffleWinner 
                  ? '1px solid var(--accent-green)' 
                  : isAllRoundsFinished 
                  ? '1px solid #34d399' 
                  : '1px solid rgba(255, 255, 255, 0.1)',
                padding: '10px 16px',
                cursor: (!isAllRoundsFinished || prizeCardRaffleWinner !== null) ? 'not-allowed' : 'pointer',
                boxShadow: isAllRoundsFinished && !prizeCardRaffleWinner ? '0 0 15px rgba(16, 185, 129, 0.5)' : 'none'
              }}
              title={
                prizeCardRaffleWinner 
                  ? 'El sorteo final ya fue realizado' 
                  : isAllRoundsFinished 
                  ? 'Ejecutar el Gran Sorteo Final entre todos los cartones activos' 
                  : 'Bloqueado hasta que finalicen los 3 premios (se cante BINGO de Premio 3)'
              }
            >
              <i className={`fa-solid ${isRafflingCard ? 'fa-spinner fa-spin' : prizeCardRaffleWinner ? 'fa-check' : isAllRoundsFinished ? 'fa-gift' : 'fa-lock'}`}></i>
              <span style={{ marginLeft: '6px' }}>
                {isRafflingCard 
                  ? 'Sorteando Serie Final...' 
                  : prizeCardRaffleWinner 
                  ? '✓ Sorteo Final Realizado' 
                  : isAllRoundsFinished 
                  ? 'Sortear N° de Cartón ($10k)' 
                  : 'Sorteo Bloqueado'}
              </span>
            </button>
          </div>
        );
      })()}

      {/* =========================================================================
          5. UTILIDADES (Tablero y Nueva Partida)
         ========================================================================= */}
      <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end', alignItems: 'center' }}>
        <button 
          className="btn btn-secondary btn-sm"
          onClick={onToggleMatrix}
        >
          <i className="fa-solid fa-table-cells"></i>
          {showMatrix ? 'Ocultar Tablero' : 'Tablero 1-90'}
        </button>

        <button 
          className="btn btn-secondary btn-sm"
          onClick={onResetGame} 
          title="Reiniciar partida a cero en PostgreSQL"
        >
          <i className="fa-solid fa-arrows-rotate"></i>
          Nueva Partida
        </button>
      </div>
    </div>
  );
});

window.ControlesOrganizador = ControlesOrganizador;
