// Componente Modal: Vista Previa y Descarga de Cartones en PDF (A4)
const { memo } = React;

const CardsPdfModal = memo(function CardsPdfModal({
  isOpen = false,
  onClose,
  cards = [],
  playerName = 'Jugador'
}) {
  if (!isOpen || !cards || cards.length === 0) return null;

  const safeName = playerName || 'Jugador Oficial';

  const handleDownload = () => {
    if (window.downloadCardsPDF) {
      window.downloadCardsPDF(cards, safeName);
    }
  };

  const handlePrint = () => {
    window.print();
  };

  return (
    <div style={{
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      background: 'rgba(0, 0, 0, 0.85)',
      backdropFilter: 'blur(8px)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      zIndex: 999999,
      padding: '16px'
    }}>
      <div className="app-card" style={{
        maxWidth: '820px',
        width: '100%',
        maxHeight: '92vh',
        display: 'flex',
        flexDirection: 'column',
        animation: 'popIn 0.3s ease',
        overflow: 'hidden',
        border: '2px solid var(--accent-gold)'
      }}>
        {/* Cabecera del Modal */}
        <div className="card-header" style={{
          padding: '16px 20px',
          borderBottom: '1px solid var(--border-subtle)',
          background: 'linear-gradient(135deg, rgba(15, 23, 42, 0.95), rgba(30, 41, 59, 0.95))'
        }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <i className="fa-solid fa-file-pdf" style={{ color: 'var(--accent-gold)', fontSize: '1.4rem' }}></i>
              <h3 className="card-title" style={{ margin: 0, fontSize: '1.25rem', fontWeight: '900' }}>
                Descargar / Imprimir Cartones Oficiales
              </h3>
            </div>
            <span style={{ fontSize: '0.82rem', color: 'var(--text-muted)' }}>
              Jugador: <strong style={{ color: 'var(--text-main)' }}>{safeName}</strong> • {cards.length} {cards.length === 1 ? 'cartón oficial' : 'cartones oficiales'} listos para descargar o imprimir.
            </span>
          </div>

          <button type="button" className="btn btn-secondary btn-sm" onClick={onClose}>
            <i className="fa-solid fa-xmark"></i>
          </button>
        </div>

        {/* Banner Oficial de Pozo Total y Premios */}
        <div style={{
          padding: '12px 20px',
          background: 'linear-gradient(135deg, #0f172a 0%, #1e293b 100%)',
          borderBottom: '1px solid rgba(245, 158, 11, 0.4)',
          display: 'flex',
          flexDirection: 'column',
          gap: '10px'
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '8px' }}>
            <span style={{ fontSize: '0.85rem', color: '#cbd5e1', fontWeight: '600', display: 'flex', alignItems: 'center', gap: '6px' }}>
              <i className="fa-solid fa-star" style={{ color: '#f59e0b' }}></i> Sorteo Oficial en Vivo de 90 Bolillas
            </span>
            <div style={{
              background: 'rgba(6, 182, 212, 0.18)',
              color: 'var(--accent-cyan)',
              border: '1px solid var(--accent-cyan)',
              fontWeight: '800',
              fontSize: '0.82rem',
              padding: '4px 12px',
              borderRadius: '20px',
              display: 'flex',
              alignItems: 'center',
              gap: '6px'
            }}>
              <i className="fa-solid fa-trophy"></i> 3 Grandes Premios + Gran Sorteo Final
            </div>
          </div>

          {/* Cuadrícula de Premios Oficiales */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fit, minmax(130px, 1fr))',
            gap: '8px',
            marginTop: '4px'
          }}>
            <div style={{
              background: 'rgba(245, 158, 11, 0.08)',
              border: '1px solid rgba(245, 158, 11, 0.35)',
              borderRadius: '8px',
              padding: '8px 10px',
              textAlign: 'center'
            }}>
              <div style={{ color: '#f59e0b', fontWeight: '900', fontSize: '0.8rem', letterSpacing: '0.04em' }}>PREMIO 1</div>
              <div style={{ color: '#cbd5e1', fontSize: '0.74rem' }}>Línea: <strong>$10.000</strong></div>
              <div style={{ color: '#fbbf24', fontWeight: '900', fontSize: '0.82rem' }}>Bingo: $100.000</div>
            </div>

            <div style={{
              background: 'rgba(16, 185, 129, 0.08)',
              border: '1px solid rgba(16, 185, 129, 0.35)',
              borderRadius: '8px',
              padding: '8px 10px',
              textAlign: 'center'
            }}>
              <div style={{ color: '#34d399', fontWeight: '900', fontSize: '0.8rem', letterSpacing: '0.04em' }}>PREMIO 2</div>
              <div style={{ color: '#cbd5e1', fontSize: '0.74rem' }}>Línea: <strong>$10.000</strong></div>
              <div style={{ color: '#34d399', fontWeight: '900', fontSize: '0.82rem' }}>Bingo: $50.000</div>
            </div>

            <div style={{
              background: 'rgba(16, 185, 129, 0.08)',
              border: '1px solid rgba(16, 185, 129, 0.35)',
              borderRadius: '8px',
              padding: '8px 10px',
              textAlign: 'center'
            }}>
              <div style={{ color: '#34d399', fontWeight: '900', fontSize: '0.8rem', letterSpacing: '0.04em' }}>PREMIO 3</div>
              <div style={{ color: '#cbd5e1', fontSize: '0.74rem' }}>Línea: <strong>$10.000</strong></div>
              <div style={{ color: '#34d399', fontWeight: '900', fontSize: '0.82rem' }}>Bingo: $50.000</div>
            </div>

            <div style={{
              background: 'rgba(6, 182, 212, 0.08)',
              border: '1px solid rgba(6, 182, 212, 0.35)',
              borderRadius: '8px',
              padding: '8px 10px',
              textAlign: 'center'
            }}>
              <div style={{ color: '#38bdf8', fontWeight: '900', fontSize: '0.78rem', letterSpacing: '0.04em' }}>GRAN SORTEO FINAL</div>
              <div style={{ color: '#cbd5e1', fontSize: '0.72rem' }}>Por N° de Cartón</div>
              <div style={{ color: '#38bdf8', fontWeight: '900', fontSize: '0.82rem' }}>Premio: $10.000</div>
            </div>
          </div>
        </div>

        {/* Barra de Acciones Principales */}
        <div style={{
          padding: '14px 20px',
          background: 'rgba(0, 172, 193, 0.08)',
          borderBottom: '1px solid var(--border-subtle)',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          flexWrap: 'wrap',
          gap: '12px'
        }}>
          <div style={{ fontSize: '0.88rem', color: 'var(--text-main)', fontWeight: '700' }}>
            <i className="fa-solid fa-circle-check" style={{ color: 'var(--accent-green)', marginRight: '6px' }}></i>
            Cartones verificados en formato oficial A4
          </div>

          <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
            <button
              type="button"
              className="btn btn-primary"
              onClick={handleDownload}
              style={{ fontWeight: '800', display: 'flex', alignItems: 'center', gap: '8px', padding: '10px 18px' }}
            >
              <i className="fa-solid fa-download"></i>
              Descargar Archivo PDF
            </button>

            <button
              type="button"
              className="btn btn-secondary"
              onClick={handlePrint}
              style={{ fontWeight: '700', display: 'flex', alignItems: 'center', gap: '8px', padding: '10px 16px', color: 'var(--accent-gold)', border: '1px solid var(--accent-gold)' }}
            >
              <i className="fa-solid fa-print"></i>
              Imprimir / Guardar en PDF
            </button>
          </div>
        </div>

        {/* Vista Previa Desplazable de Cartones */}
        <div style={{
          flex: 1,
          overflowY: 'auto',
          padding: '18px 20px',
          display: 'flex',
          flexDirection: 'column',
          gap: '16px',
          background: 'var(--bg-app)'
        }}>
          {cards.map((card, idx) => {
            const isPromo = card.es_promo || card.esPromo || (idx === 3 && cards.length === 4);
            const themeClass = 'card-theme-ruby';

            return (
              <div key={card.id || idx} className={`bingo-card-3x9-wrapper ${themeClass}`} style={{ margin: 0, padding: '12px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <i className="fa-solid fa-ticket" style={{ color: 'var(--tag-color, #38bdf8)' }}></i>
                    <span style={{ fontWeight: '800', fontSize: '0.95rem' }}>{card.title || `Cartón Oficial #${idx + 1}`}</span>
                    {isPromo && (
                      <span className="brand-badge" style={{ backgroundColor: 'rgba(245, 158, 11, 0.25)', color: '#f59e0b', border: '1px solid #f59e0b', fontWeight: '900', fontSize: '0.72rem', padding: '2px 8px' }}>
                        🎁 PROMO 3+1 REGALO
                      </span>
                    )}
                  </div>
                  <span className="card-serial-tag">N°: {card.id || card.card_code || `CR-${10000 + idx + 1}`}</span>
                </div>

                <div className="teal-bingo-ticket" style={{ padding: '6px' }}>
                  <div className="ticket-col-headers">
                    {['1-9','10-19','20-29','30-39','40-49','50-59','60-69','70-79','80-90'].map((lbl, cIdx) => (
                      <div key={cIdx} className="ticket-col-header-item">{lbl}</div>
                    ))}
                  </div>

                  <div className="ticket-grid-3x9">
                    {(card.grid || []).map((row, rIdx) => (
                      <div key={rIdx} className="ticket-row">
                        {row.map((cellNum, cIdx) => (
                          cellNum !== null && cellNum !== undefined ? (
                            <div key={cIdx} className="ticket-cell" style={{ minHeight: '32px', fontSize: '1rem', fontWeight: '800' }}>
                              <span>{cellNum}</span>
                            </div>
                          ) : (
                            <div key={cIdx} className="ticket-cell empty" style={{ minHeight: '32px' }}>
                              {rIdx === 2 && cIdx === 7 && (
                                <span className="watermark-text">Bingo la Mami</span>
                              )}
                            </div>
                          )
                        ))}
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Pie del Modal */}
        <div style={{
          padding: '12px 20px',
          borderTop: '1px solid var(--border-subtle)',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          background: 'rgba(15, 23, 42, 0.95)'
        }}>
          <span style={{ fontSize: '0.78rem', color: 'var(--text-muted)' }}>
            Válido para la sala oficial en directo (Sorteo 90 Bolillas).
          </span>

          <button type="button" className="btn btn-secondary" onClick={onClose} style={{ padding: '8px 20px' }}>
            Cerrar
          </button>
        </div>
      </div>
    </div>
  );
});

window.CardsPdfModal = CardsPdfModal;
