// Componente: Vitrina y Explorador de Cartones Aleatorios antes de Comprar
const { useState, useEffect, useMemo, useCallback } = React;

function CardShowcase({ onSelectCardToBuy, onNavigateToBot }) {
  const [cardsCount, setCardsCount] = useState(8);
  const [cardsList, setCardsList] = useState([]);
  const [selectedCards, setSelectedCards] = useState([]);
  const [filterLuckyNumber, setFilterLuckyNumber] = useState('');
  const [isShuffling, setIsShuffling] = useState(false);

  // Función para generar una tanda de cartones aleatorios 3x9
  const generateRandomBatch = useCallback((count = 8) => {
    setIsShuffling(true);
    const newCards = [];
    for (let i = 1; i <= count; i++) {
      if (window.generateCard3x9) {
        newCards.push(window.generateCard3x9(i, 15));
      } else {
        const randomCode = 'CR-' + Math.floor(10000 + Math.random() * 90000);
        const numCol0_A = ((i * 2) % 8) + 1; // Estrictamente 1 a 8
        const numCol0_B = numCol0_A < 9 ? 9 : 8; // Estrictamente 1 a 9
        newCards.push({
          id: randomCode,
          title: `Cartón Serie #${i}`,
          grid: [
            [numCol0_A, null, 20 + (i % 9), null, 40 + (i % 9), null, 60 + (i % 9), null, 80 + (i % 10)],
            [null, 10 + (i % 9), null, 30 + (i % 9), null, 50 + (i % 9), null, 70 + (i % 9), null],
            [numCol0_B, null, 25 + (i % 4), null, 45 + (i % 4), null, null, 75 + (i % 4), 90]
          ],
          allNumbers: [numCol0_A, numCol0_B, 10 + (i % 9), 20 + (i % 9), 25 + (i % 4), 30 + (i % 9), 40 + (i % 9), 45 + (i % 4), 50 + (i % 9), 60 + (i % 9), 70 + (i % 9), 75 + (i % 4), 80 + (i % 10), 90]
        });
      }
    }
    setCardsList(newCards);
    setIsShuffling(false);
  }, []);

  useEffect(() => {
    generateRandomBatch(cardsCount);
  }, [cardsCount, generateRandomBatch]);

  // Filtro por números de la suerte
  const filteredCards = useMemo(() => {
    if (!filterLuckyNumber.trim()) return cardsList;
    const nums = filterLuckyNumber
      .split(/[\s,.-]+/)
      .map(n => parseInt(n.trim(), 10))
      .filter(n => !isNaN(n) && n >= 1 && n <= 90);

    if (nums.length === 0) return cardsList;

    return cardsList.filter(c => {
      const allNums = c.allNumbers || (c.grid ? c.grid.flat().filter(n => n !== null && n !== undefined) : []);
      return nums.every(fn => allNums.includes(fn));
    });
  }, [cardsList, filterLuckyNumber]);

  // Selección múltiple para compra con promo 3+1 sin recargas
  const toggleSelectCard = useCallback((card, e) => {
    if (e && e.preventDefault) e.preventDefault();
    if (e && e.stopPropagation) e.stopPropagation();

    setSelectedCards(prev => {
      const exists = prev.some(c => c.id === card.id);
      if (exists) return prev.filter(c => c.id !== card.id);
      if (prev.length >= 12) {
        alert("Puedes seleccionar un máximo de 12 cartones por pedido.");
        return prev;
      }
      return [...prev, card];
    });
  }, []);

  // Cálculo de precio y promo única 3+1: La máxima promo es 4 cartones por $3.000
  const selectedCount = selectedCards.length;
  const isExactThree = selectedCount === 3;
  const isFourOrMore = selectedCount >= 4;
  const bonusCardsToAward = isExactThree ? 1 : 0;
  const promoFreeCount = isFourOrMore ? 1 : 0; // Máximo 1 cartón gratis
  const payableCount = isExactThree ? 3 : (isFourOrMore ? selectedCount - 1 : selectedCount);
  const totalPrice = payableCount * 1000;
  const totalCardsToReceive = isExactThree ? 4 : selectedCount;

  // Comprar un cartón individual de inmediato
  const handleBuySingle = (card, e) => {
    if (e && e.preventDefault) e.preventDefault();
    if (e && e.stopPropagation) e.stopPropagation();
    if (onSelectCardToBuy) {
      onSelectCardToBuy([card]);
    } else if (onNavigateToBot) {
      onNavigateToBot([card]);
    }
  };

  // Comprar todos los cartones seleccionados
  const handleBuySelected = () => {
    if (selectedCards.length === 0) return;
    if (onSelectCardToBuy) {
      onSelectCardToBuy(selectedCards);
    } else if (onNavigateToBot) {
      onNavigateToBot(selectedCards);
    }
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
      {/* Banner de la Vitrina */}
      <div className="hero-banner">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '16px' }}>
          <div>
            <h1 className="hero-title">
              <i className="fa-solid fa-store" style={{ color: 'var(--accent-gold)', marginRight: '10px' }}></i>
              Vitrina de Cartones Disponibles
            </h1>
            <p className="hero-description">
              Explora combinaciones aleatorias de <strong>cartones 3x9 oficiales</strong> antes de comprar. Revisa sus 15 números, busca por tus números de la suerte o baraja una nueva tanda.
            </p>
          </div>

          <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
            <button 
              type="button"
              className="btn btn-secondary"
              onClick={() => window.downloadCardsPDF && window.downloadCardsPDF(selectedCount > 0 ? selectedCards : cardsList, selectedCount > 0 ? 'Cartones Seleccionados' : 'Catálogo de Cartones')}
              style={{ color: 'var(--accent-gold)', border: '1px solid rgba(245, 158, 11, 0.4)', fontWeight: '700', display: 'flex', alignItems: 'center', gap: '6px' }}
              title="Descargar PDF de los cartones mostrados en pantalla"
            >
              <i className="fa-solid fa-file-pdf"></i>
              {selectedCount > 0 ? `Descargar ${selectedCount} en PDF` : 'Descargar Catálogo en PDF'}
            </button>

            <button 
              type="button"
              className="btn btn-secondary"
              onClick={() => generateRandomBatch(cardsCount)}
              disabled={isShuffling}
            >
              <i className={`fa-solid fa-shuffle ${isShuffling ? 'fa-spin' : ''}`}></i>
              {isShuffling ? 'Barajando...' : 'Barajar Nuevos Cartones'}
            </button>

            <button 
              type="button"
              className="btn btn-primary"
              onClick={handleBuySelected}
              disabled={selectedCount === 0}
              style={{ fontWeight: '800' }}
            >
              <i className="fa-solid fa-cart-shopping"></i>
              {selectedCount === 4
                ? `Comprar 4 Cartones (Promo 3+1: Pagas 3) - $${totalPrice.toLocaleString('es-AR')}`
                : selectedCount === 3
                ? `Comprar 3 Cartones (Recibes 4 con Promo 3+1) - $${totalPrice.toLocaleString('es-AR')}`
                : selectedCount > 4
                ? `Comprar ${selectedCount} Cartones (Recibes ${totalCardsToReceive}) - $${totalPrice.toLocaleString('es-AR')}`
                : `Comprar Seleccionados (${selectedCount}) - $${totalPrice.toLocaleString('es-AR')}`
              }
            </button>
          </div>
        </div>
      </div>

      {/* Barra de Filtros y Controles de la Vitrina */}
      <div className="app-card" style={{ padding: '16px 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '14px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px', flex: 1, minWidth: '260px' }}>
          <div style={{ position: 'relative', width: '100%', maxWidth: '380px' }}>
            <i className="fa-solid fa-clover" style={{ position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)', color: 'var(--accent-green)' }}></i>
            <input 
              type="text"
              className="input-field"
              placeholder="Buscar por números de la suerte (ej: 7, 23, 77)..."
              value={filterLuckyNumber}
              onChange={(e) => setFilterLuckyNumber(e.target.value)}
              style={{ width: '100%', paddingLeft: '36px' }}
            />
          </div>

          {filterLuckyNumber && (
            <button 
              className="btn btn-secondary btn-sm" 
              onClick={() => setFilterLuckyNumber('')}
              style={{ fontSize: '0.75rem' }}
            >
              Limpiar
            </button>
          )}
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <span style={{ fontSize: '0.85rem', color: 'var(--text-muted)' }}>
            Mostrar:
          </span>
          <div style={{ display: 'flex', gap: '6px' }}>
            {[4, 8, 12].map(num => (
              <button
                key={num}
                className={`btn btn-sm ${cardsCount === num ? 'btn-primary' : 'btn-secondary'}`}
                onClick={() => setCardsCount(num)}
              >
                {num} cartones
              </button>
            ))}
          </div>

          <span className="brand-badge" style={{ backgroundColor: 'var(--accent-gold)', color: '#111', fontWeight: '800' }}>
            PROMO: 3 + 1 GRATIS
          </span>
        </div>
      </div>

      {/* Grid de Cartones Completos 3x9 */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(420px, 1fr))', gap: '24px', width: '100%', boxSizing: 'border-box' }}>
        {filteredCards.map((card, idx) => {
          const isSelected = selectedCards.some(c => c.id === card.id);
          const allNums = card.allNumbers || (card.grid ? card.grid.flat().filter(n => n !== null && n !== undefined) : []);
          const themeClass = 'card-theme-ruby';

          return (
            <div 
              key={card.id}
              className={`bingo-card-3x9-wrapper ${themeClass} ${isSelected ? 'is-user-card' : ''}`}
              style={{
                transition: 'all 0.2s ease',
                position: 'relative',
                boxSizing: 'border-box',
                width: '100%'
              }}
            >
              {/* Cabecera del Cartón Completo */}
              <div className="card-header-bar" style={{ marginBottom: '12px' }}>
                <div className="card-header-info">
                  <span className="card-title-text" style={{ fontSize: '1.15rem' }}>{card.title}</span>
                  <span className="card-serial-tag" style={{ fontSize: '0.85rem' }}>N°: {card.id}</span>
                </div>

                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <span className="brand-badge" style={{ backgroundColor: 'rgba(16, 185, 129, 0.2)', color: 'var(--accent-green)', border: '1px solid var(--accent-green)', fontWeight: '800' }}>
                    ● DISPONIBLE
                  </span>
                  <span style={{ fontSize: '1.1rem', fontWeight: '900', color: 'var(--accent-gold)' }}>
                    $1.000
                  </span>
                </div>
              </div>

              {/* Cuadrícula Física 3x9 Oficial */}
              <div className="teal-bingo-ticket" style={{ padding: '8px' }}>
                <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, idx) => (
                    <div key={idx} 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: '38px' }}>
                            <span>{cellNum}</span>
                          </div>
                        ) : (
                          <div key={cIdx} className="ticket-cell empty" style={{ minHeight: '38px' }}>
                            {rIdx === 2 && cIdx === 7 && (
                              <span className="watermark-text">Lota Familiar La Mami</span>
                            )}
                          </div>
                        )
                      ))}
                    </div>
                  ))}
                </div>
              </div>

              {/* Pie de Estado con Indicadores de Fila */}
              <div className="ticket-status-footer" style={{ marginTop: '10px', paddingTop: '8px' }}>
                <div className="row-indicators">
                  {[1, 2, 3].map(rowNum => (
                    <span key={rowNum} className="row-indicator-badge">
                      Fila {rowNum}: 5 Números
                    </span>
                  ))}
                </div>

                <span style={{ fontSize: '0.82rem', color: 'var(--accent-cyan)', fontWeight: '700' }}>
                  15 Números Oficiales
                </span>
              </div>

              {/* Botones de Acción de Compra en el Cartón */}
              <div style={{ marginTop: '12px', paddingTop: '12px', borderTop: '1px solid var(--border-subtle)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: '10px', flexWrap: 'wrap' }}>
                <button
                  type="button"
                  className={`btn ${isSelected ? 'btn-primary' : 'btn-secondary'}`}
                  onClick={(e) => toggleSelectCard(card, e)}
                  style={{ display: 'flex', alignItems: 'center', gap: '6px', fontWeight: '700', padding: '8px 14px' }}
                >
                  <i className={`fa-solid ${isSelected ? 'fa-check' : 'fa-plus'}`}></i>
                  {isSelected ? '✓ Seleccionado' : 'Añadir al Pedido (3+1)'}
                </button>

                <button
                  type="button"
                  className="btn btn-primary"
                  onClick={(e) => handleBuySingle(card, e)}
                  style={{ fontWeight: '800', display: 'flex', alignItems: 'center', gap: '8px', padding: '8px 18px', fontSize: '0.95rem' }}
                >
                  <i className="fa-solid fa-cart-shopping"></i>
                  Comprar Este Cartón ($1.000)
                </button>
              </div>
            </div>
          );
        })}
      </div>

      {filteredCards.length === 0 && (
        <div className="app-card" style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--text-muted)' }}>
          <i className="fa-solid fa-clover" style={{ fontSize: '2.5rem', color: 'var(--text-dim)', marginBottom: '12px' }}></i>
          <h3 style={{ margin: '0 0 8px 0', color: 'var(--text-main)' }}>No se encontraron cartones con esos números</h3>
          <p style={{ margin: '0 0 16px 0', fontSize: '0.9rem' }}>Prueba barajar una nueva tanda o cambiar el número de búsqueda.</p>
          <button type="button" className="btn btn-primary" onClick={() => generateRandomBatch(cardsCount)}>
            <i className="fa-solid fa-shuffle"></i> Barajar Nueva Tanda
          </button>
        </div>
      )}
    </div>
  );
}

window.CardShowcase = CardShowcase;
