// Componente Atómico Memoizado: Cartón Físico 3x9 con Estampado Elástico y Radar
const { memo, useMemo } = React;

const COL_RANGES = [
  { label: '1-9', min: 1, max: 9 },
  { label: '10-19', min: 10, max: 19 },
  { label: '20-29', min: 20, max: 29 },
  { label: '30-39', min: 30, max: 39 },
  { label: '40-49', min: 40, max: 49 },
  { label: '50-59', min: 50, max: 59 },
  { label: '60-69', min: 60, max: 69 },
  { label: '70-79', min: 70, max: 79 },
  { label: '80-90', min: 80, max: 90 }
];

const CartonView = memo(function CartonView({
  card,
  calledBalls = [],
  isLeaderRadar = false,
  isUserCard = false,
  onInspect = null
}) {
  if (!card) return null;

  // Métricas memoizadas por cartón
  const { allNums, matchedCount, totalNums, isCardBingo, missingNums, rowData, numCompletedRows } = useMemo(() => {
    const numbers = card.allNumbers && card.allNumbers.length > 0
      ? card.allNumbers
      : (card.grid ? card.grid.flat().filter(n => n !== null && n !== undefined) : []);

    const matched = card.matchedCount !== undefined
      ? card.matchedCount
      : numbers.filter(n => calledBalls.includes(n)).length;

    const total = card.totalNums || numbers.length || 15;
    const isBingo = matched === total;

    const missing = card.missingNumbers && card.missingNumbers.length > 0
      ? card.missingNumbers
      : numbers.filter(n => !calledBalls.includes(n));

    const rows = (card.grid || []).map((row, rIdx) => {
      const rowNumbers = row.filter(n => n !== null && n !== undefined);
      const rowMatched = rowNumbers.filter(n => calledBalls.includes(n)).length;
      const isRowComplete = rowNumbers.length > 0 && rowMatched === rowNumbers.length;
      return { rIdx, rowNumbers, rowMatched, isRowComplete };
    });

    const completedRowsCount = card.completedRows !== undefined
      ? card.completedRows
      : rows.filter(r => r.isRowComplete).length;

    return {
      allNums: numbers,
      matchedCount: matched,
      totalNums: total,
      isCardBingo: isBingo,
      missingNums: missing,
      rowData: rows,
      numCompletedRows: completedRowsCount
    };
  }, [card, calledBalls]);

  const cardClass = useMemo(() => {
    if (isCardBingo) return 'card-winner';
    if (numCompletedRows === 2) return 'has-2-lines';
    if (numCompletedRows === 1) return 'has-1-line';
    if (missingNums.length <= 2 && missingNums.length > 0) return 'near-bingo';
    return '';
  }, [isCardBingo, numCompletedRows, missingNums.length]);

  // Tema Oficial Único: Rojo Rubí para todos los cartones
  const themeClass = 'card-theme-ruby';

  const isInactive = card.is_active === false || card.isActive === false;

  return (
    <div className={`bingo-card-3x9-wrapper ${themeClass} ${cardClass} ${isUserCard ? 'is-user-card' : ''}`} style={{ opacity: isInactive ? 0.85 : 1 }}>
      {/* Cabecera del Cartón */}
      <div className="card-header-bar">
        <div className="card-header-info">
          <span className="card-title-text">
            <i className="fa-solid fa-ticket" style={{ color: 'var(--tag-color, var(--accent-cyan))', fontSize: '0.9rem' }}></i>
            {card.title || card.playerName || `Cartón ${card.id}`}
          </span>
          <span className="card-serial-tag">N°: {card.id || card.card_code}</span>
          {(card.es_promo || card.esPromo) && (
            <span className="brand-badge" style={{ backgroundColor: 'rgba(245, 158, 11, 0.25)', color: '#f59e0b', border: '1px solid #f59e0b', fontWeight: '900', fontSize: '0.74rem' }}>
              🎁 PROMO 3+1 REGALO
            </span>
          )}
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
          {isInactive && (
            <span className="brand-badge" style={{ backgroundColor: 'rgba(245, 158, 11, 0.25)', color: 'var(--accent-gold)', border: '1px solid var(--accent-gold)', fontWeight: '800' }}>
              🟡 PENDIENTE DE PAGO
            </span>
          )}
          {numCompletedRows === 1 && (
            <span className="brand-badge" style={{ backgroundColor: 'var(--accent-gold)', color: '#111', fontWeight: '900' }}>
              ★ 1 LÍNEA
            </span>
          )}
          {numCompletedRows === 2 && (
            <span className="brand-badge" style={{ backgroundColor: '#8b5cf6', color: '#fff', fontWeight: '900' }}>
              ★★ 2 LÍNEAS
            </span>
          )}
          {isCardBingo && (
            <span className="brand-badge" style={{ backgroundColor: 'var(--accent-green)', color: '#fff', fontWeight: '900' }}>
              ★★★ ¡BINGO!
            </span>
          )}

          {isLeaderRadar && missingNums.length === 1 && (
            <span className="card-radar-missing-badge" style={{ background: 'rgba(244, 63, 94, 0.25)', borderColor: '#f43f5e', color: '#fca5a5', fontWeight: '900' }}>
              🔥 ¡ESPERA EL #{missingNums[0]}!
            </span>
          )}
          {isLeaderRadar && missingNums.length === 2 && (
            <span className="card-radar-missing-badge" style={{ fontWeight: '800' }}>
              ⚡ Espera: #{missingNums.join(', #')}
            </span>
          )}

          {/* Mini Barra de Aciertos */}
          <div style={{ display: 'flex', alignItems: 'center', gap: '6px', background: 'rgba(0,0,0,0.3)', padding: '3px 8px', borderRadius: '12px', border: '1px solid rgba(255,255,255,0.08)' }}>
            <div style={{ width: '50px', height: '6px', background: 'rgba(255, 255, 255, 0.1)', borderRadius: '3px', overflow: 'hidden' }}>
              <div style={{
                width: `${Math.round((matchedCount / totalNums) * 100)}%`,
                height: '100%',
                background: isCardBingo ? 'linear-gradient(90deg, #10b981, #34d399)' : numCompletedRows > 0 ? 'linear-gradient(90deg, #f59e0b, #fbbf24)' : 'linear-gradient(90deg, var(--accent-cyan), #0284c7)',
                transition: 'width 0.3s ease'
              }} />
            </div>
            <span style={{ fontSize: '0.82rem', fontWeight: '900', fontFamily: 'var(--font-numbers)', color: isCardBingo ? '#34d399' : 'var(--text-main)' }}>
              {matchedCount}/{totalNums}
            </span>
          </div>

          {onInspect && (
            <button 
              className="leaderboard-inspect-btn" 
              onClick={() => onInspect(card)}
              title="Validar este cartón oficial al instante (Línea / Bingo)"
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: '5px',
                padding: '4px 10px',
                fontSize: '0.76rem',
                fontWeight: '800',
                borderRadius: 'var(--radius-sm)',
                background: 'linear-gradient(135deg, rgba(245, 158, 11, 0.2), rgba(217, 119, 6, 0.25))',
                border: '1px solid var(--accent-gold)',
                color: 'var(--accent-gold)',
                cursor: 'pointer'
              }}
            >
              <i className="fa-solid fa-stamp"></i>
              <span>Validar</span>
            </button>
          )}
        </div>
      </div>

      {/* Cuadrícula 3x9 Física */}
      <div className="teal-bingo-ticket">
        {/* Tira superior oficial del ticket */}
        <div style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          padding: '4px 10px',
          background: 'rgba(0, 0, 0, 0.45)',
          borderRadius: '6px 6px 0 0',
          marginBottom: '5px',
          borderBottom: '1px solid rgba(255, 255, 255, 0.15)'
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
            <span style={{ color: 'var(--accent-color, #fbbf24)', fontSize: '0.85rem' }}>★</span>
            <span style={{ fontSize: '0.74rem', fontWeight: '900', letterSpacing: '0.08em', color: '#ffffff', textTransform: 'uppercase' }}>
              BINGO LA MAMI • OFICIAL
            </span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <span style={{
              fontSize: '0.68rem',
              fontWeight: '900',
              color: 'var(--accent-color, #38bdf8)',
              background: 'rgba(0,0,0,0.5)',
              padding: '1px 8px',
              borderRadius: '4px',
              border: '1px solid rgba(255, 255, 255, 0.2)'
            }}>
              {(card.es_promo || card.esPromo) ? '🎁 PROMO 3+1 REGALO' : '90 BOLILLAS'}
            </span>
            <span style={{ fontSize: '0.74rem', fontWeight: '800', color: '#ffffff', fontFamily: 'monospace' }}>
              {card.id || card.card_code}
            </span>
          </div>
        </div>

        <div className="ticket-col-headers">
          {COL_RANGES.map((col, idx) => (
            <div key={idx} className="ticket-col-header-item">{col.label}</div>
          ))}
        </div>

        <div className="ticket-grid-3x9">
          {(card.grid || []).map((row, rowIdx) => (
            <div key={rowIdx} className="ticket-row">
              {row.map((cellNum, colIdx) => {
                const isNumber = cellNum !== null && cellNum !== undefined;
                const isPainted = isNumber && calledBalls.includes(cellNum);
                const isWaitingTarget = isNumber && !isPainted && isLeaderRadar && missingNums.length <= 2 && missingNums.includes(cellNum);

                if (!isNumber) {
                  return (
                    <div key={colIdx} className="ticket-cell empty">
                      {rowIdx === 2 && colIdx === 7 && (
                        <span className="watermark-text">Bingo la Mami</span>
                      )}
                    </div>
                  );
                }

                return (
                  <div 
                    key={colIdx} 
                    className={`ticket-cell ${isPainted ? 'painted' : ''} ${isWaitingTarget ? 'waiting-target' : ''}`}
                    title={isPainted ? `¡Número ${cellNum} CANTADO!` : isWaitingTarget ? `¡FALTA EL #${cellNum} PARA BINGO!` : `Número ${cellNum}`}
                  >
                    <span>{cellNum}</span>
                  </div>
                );
              })}
            </div>
          ))}
        </div>
      </div>

      {/* Barra de Estado de Filas */}
      <div className="ticket-status-footer">
        <div className="row-indicators">
          {rowData.map((r, rIdx) => (
            <span 
              key={rIdx} 
              className={`row-indicator-badge ${r.isRowComplete ? 'completed' : ''}`}
            >
              Fila {rIdx + 1}: {r.rowMatched}/{r.rowNumbers.length} {r.isRowComplete ? '✓ LÍNEA' : ''}
            </span>
          ))}
        </div>

        <span style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}>
          {totalNums - matchedCount === 0 ? '¡Cartón Completo!' : `Faltan ${totalNums - matchedCount} números`}
        </span>
      </div>
    </div>
  );
});

window.CartonView = CartonView;
