// Componente Panel de Vendedor / Promotor Autorizado (Carga Rápida de Jugadores)
const { useState, useEffect, useCallback, useMemo } = React;

function SellerView({ currentUser, onLogout }) {
  let room = {};
  try {
    if (window.useBingoRoom) {
      room = window.useBingoRoom();
    }
  } catch (e) {}

  const receipts = room.receipts || [];
  const reloadDatabase = room.reloadDatabase || (() => {});
  const isSalesOpen = room.isSalesOpen !== undefined ? room.isSalesOpen : true;

  const sellerId = currentUser?.id || null;
  const sellerName = currentUser?.name || 'Vendedor Autorizado';
  const sellerPhone = currentUser?.phone || '';

  // Filtrar comprobantes registrados por este vendedor
  const myReceipts = useMemo(() => {
    return receipts.filter(r => {
      if (sellerId && r.seller_id === sellerId) return true;
      if (r.seller_name && r.seller_name.toLowerCase() === sellerName.toLowerCase()) return true;
      if (r.notes && r.notes.toLowerCase().includes(sellerName.toLowerCase())) return true;
      return false;
    });
  }, [receipts, sellerId, sellerName]);

  const stats = useMemo(() => {
    const totalPlayers = myReceipts.length;
    const totalCards = myReceipts.reduce((acc, r) => acc + (parseInt(r.cards_count, 10) || 0), 0);
    const totalAmount = myReceipts.reduce((acc, r) => acc + (parseFloat(r.amount) || 0), 0);
    return { totalPlayers, totalCards, totalAmount };
  }, [myReceipts]);

  // Estado del Formulario de Carga
  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    cardsCount: 3, // Promo 3+1 recomendada por defecto
    paymentMethod: 'Efectivo',
    operationNumber: '',
    notes: ''
  });

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [lastAssignedResult, setLastAssignedResult] = useState(null);
  const [autoDownloadPdf, setAutoDownloadPdf] = useState(false);

  // Estados para Modal de Consulta de Cartones de Ventas Pasadas
  const [viewingReceipt, setViewingReceipt] = useState(null);
  const [viewingCards, setViewingCards] = useState([]);
  const [loadingViewingCards, setLoadingViewingCards] = useState(false);
  const [downloadingReceiptId, setDownloadingReceiptId] = useState(null);

  // Cálculo de promoción: La máxima promo es 3+1 (4 cartones x $3.000)
  const count = parseInt(formData.cardsCount || 1, 10);
  const isExactThree = count === 3;
  const isFourOrMore = count >= 4;
  const bonusCards = (isExactThree || isFourOrMore) ? 1 : 0; // Máximo 1 cartón de regalo en total
  const payableCount = isExactThree ? 3 : (isFourOrMore ? count - 1 : count);
  const totalPrice = payableCount * 1000;
  const totalCardsToReceive = isExactThree ? 4 : count;

  // Generador de vista previa de cartones antes de emitir
  const generateCardsPreview = useCallback((numCards, buyerName = '') => {
    const list = [];
    const displayName = buyerName ? buyerName.trim() : 'Comprador';
    for (let i = 1; i <= numCards; i++) {
      if (window.generateSingleCard3x9) {
        const c = window.generateSingleCard3x9(i);
        const isBonus = (numCards === 4 && i === 4) || (numCards > 3 && i > (numCards - 1));
        list.push({
          id: c.card_code,
          card_code: c.card_code,
          title: isBonus ? `Cartón #${i} (🎁 PROMO 3+1 REGALO)` : `Cartón #${i}`,
          grid: c.grid,
          allNumbers: c.numbers,
          numbers: c.numbers,
          es_promo: isBonus
        });
      }
    }
    return list;
  }, []);

  const [previewCards, setPreviewCards] = useState(() => generateCardsPreview(4));
  const [activeViewTab, setActiveViewTab] = useState(() => {
    try {
      const urlParams = new URLSearchParams(window.location.search);
      const tab = urlParams.get('subtab') || urlParams.get('tab');
      if (tab === 'catalog') return 'catalog';
      if (tab === 'settlement' || tab === 'rendicion' || tab === 'caja') return 'settlement';
      return 'sell';
    } catch (e) {
      return 'sell';
    }
  });

  // Estados para la Rendición de Ventas / Arqueo de Caja
  const [settlementFilter, setSettlementFilter] = useState('all'); // 'all' | 'today'
  const [commissionRate, setCommissionRate] = useState(0); // Comisiones no visibles por el momento
  const [settlementSearch, setSettlementSearch] = useState('');

  // Cálculos contables oficiales para la Rendición de Ventas
  const settlementStats = useMemo(() => {
    const todayStr = new Date().toISOString().slice(0, 10);
    const filteredByDate = myReceipts.filter(r => {
      if (settlementFilter === 'today') {
        const rDate = r.created_at ? r.created_at.slice(0, 10) : todayStr;
        return rDate === todayStr;
      }
      return true;
    });

    const totalPlayers = filteredByDate.length;
    const totalCards = filteredByDate.reduce((acc, r) => acc + (parseInt(r.cards_count, 10) || 0), 0);
    const totalAmount = filteredByDate.reduce((acc, r) => acc + (parseFloat(r.amount) || 0), 0);

    let cashAmount = 0;
    let transferAmount = 0;
    filteredByDate.forEach(r => {
      const isTransfer = r.notes && r.notes.toLowerCase().includes('transferencia');
      const amt = parseFloat(r.amount) || 0;
      if (isTransfer) transferAmount += amt;
      else cashAmount += amt;
    });

    const paidCards = Math.round(totalAmount / 1000);
    const bonusCards = Math.max(0, totalCards - paidCards);

    const commRate = parseFloat(commissionRate || 0);
    const commissionAmount = (totalAmount * commRate) / 100;
    const netToOrganizer = totalAmount - commissionAmount;

    // Filtrar por término de búsqueda en la tabla de rendición
    const searchLow = settlementSearch.trim().toLowerCase();
    const visibleReceipts = filteredByDate.filter(r => {
      if (!searchLow) return true;
      const pName = (r.player_name || '').toLowerCase();
      const pPhone = (r.player_phone || '').toLowerCase();
      const pNotes = (r.notes || '').toLowerCase();
      const pOp = (r.operation_number || '').toLowerCase();
      return pName.includes(searchLow) || pPhone.includes(searchLow) || pNotes.includes(searchLow) || pOp.includes(searchLow);
    });

    return {
      filteredReceipts: filteredByDate,
      visibleReceipts,
      totalPlayers,
      totalCards,
      totalAmount,
      cashAmount,
      transferAmount,
      paidCards,
      bonusCards,
      commissionAmount,
      netToOrganizer
    };
  }, [myReceipts, settlementFilter, commissionRate, settlementSearch]);

  // Generador de mensaje formal de Rendición para WhatsApp
  const handleSendSettlementWhatsApp = () => {
    const dateStr = new Date().toLocaleString('es-AR', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });

    const lines = [
      `📋 *PLANILLA OFICIAL DE RENDICIÓN DE VENTAS*`,
      `⭐ *LOTA FAMILIAR LA MAMI - ARQUEO DE CAJA*`,
      `👤 *Vendedora:* ${sellerName}`,
      `📱 *Teléfono:* ${sellerPhone || 'No registrado'}`,
      `📅 *Fecha de Corte:* ${dateStr}`,
      `=================================`,
      `💰 *TOTAL RECAUDADO (A RENDIR):* $${settlementStats.totalAmount.toLocaleString('es-AR')}`,
      `💵 *Efectivo en Mano:* $${settlementStats.cashAmount.toLocaleString('es-AR')}`,
      `💳 *Transferencias / Alias:* $${settlementStats.transferAmount.toLocaleString('es-AR')}`,
      `🎟️ *Cartones Emitidos:* ${settlementStats.totalCards} (${settlementStats.paidCards} pagados + ${settlementStats.bonusCards} promo regalo 🎁)`,
      `👥 *Clientes Atendidos:* ${settlementStats.totalPlayers} personas`,
      `=================================`
    ];

    if (commissionRate > 0) {
      lines.push(
        `💼 *Comisión Vendedora (${commissionRate}%):* $${settlementStats.commissionAmount.toLocaleString('es-AR')}`,
        `🏛️ *Neto a Entregar al Organizador:* $${settlementStats.netToOrganizer.toLocaleString('es-AR')}`,
        `=================================`
      );
    }

    lines.push(`📝 *DETALLE DE OPERACIONES (${settlementStats.filteredReceipts.length}):*`);

    settlementStats.filteredReceipts.forEach((r, idx) => {
      const isTransfer = r.notes && r.notes.toLowerCase().includes('transferencia');
      const method = isTransfer ? 'Transferencia' : 'Efectivo';
      const amt = (parseFloat(r.amount) || 0).toLocaleString('es-AR');
      lines.push(`${idx + 1}. *${r.player_name}* (${r.player_phone || '-'}) → ${r.cards_count} cartones • $${amt} [${method}]`);
    });

    lines.push(
      `=================================`,
      `✍️ _Arqueo de caja y rendición de cuentas conforme._`
    );

    const fullMsg = encodeURIComponent(lines.join('\n'));
    window.open(`https://wa.me/?text=${fullMsg}`, '_blank');
  };

  // Generador de Planilla Oficial de Rendición en PDF
  const handleDownloadSettlementReport = () => {
    if (window.downloadSettlementPDF) {
      window.downloadSettlementPDF({
        sellerName,
        sellerPhone,
        receipts: settlementStats.filteredReceipts,
        commissionRate,
        totalAmount: settlementStats.totalAmount,
        totalCards: settlementStats.totalCards,
        cashAmount: settlementStats.cashAmount,
        transferAmount: settlementStats.transferAmount
      });
    } else {
      window.print();
    }
  };

  // Generador de Planilla Oficial de Rendición en Excel (.CSV compatible con Excel y Sheets)
  const handleExportSettlementExcel = () => {
    if (window.exportSalesToExcel) {
      window.exportSalesToExcel({
        sellerName,
        sellerPhone,
        receipts: settlementStats.filteredReceipts,
        totalAmount: settlementStats.totalAmount,
        cashAmount: settlementStats.cashAmount,
        transferAmount: settlementStats.transferAmount,
        totalCards: settlementStats.totalCards,
        title: `Rendición de Ventas - ${sellerName}`
      });
    } else {
      alert("Módulo exportador de Excel no disponible.");
    }
  };
  const [showCatalogModal, setShowCatalogModal] = useState(() => {
    try {
      const urlParams = new URLSearchParams(window.location.search);
      return urlParams.get('modal') === 'catalog';
    } catch (e) {
      return false;
    }
  });
  const [isCustomSelection, setIsCustomSelection] = useState(false);
  // Estado exclusivo para el catálogo: empieza vacío (0) para que la vendedora/cliente elija uno por uno
  const [selectedCatalogCards, setSelectedCatalogCards] = useState([]);
  const [catalogSeriesOffset, setCatalogSeriesOffset] = useState(0);
  const [hideSoldCards, setHideSoldCards] = useState(() => {
    try {
      const urlParams = new URLSearchParams(window.location.search);
      return urlParams.get('hide_sold') === '1' || urlParams.get('hide_sold') === 'true';
    } catch (e) {
      return false;
    }
  });

  // Mapa reactivo en tiempo real de todos los cartones vendidos en la sala
  const soldCardsMap = useMemo(() => {
    const map = {};
    (room.realRoomCards || []).forEach(c => {
      const code = c.id || c.card_code;
      if (code) {
        const pName = c.playerName || c.player_name || (Array.isArray(c.usuarios) ? c.usuarios[0]?.nombre : c.usuarios?.nombre) || 'Comprador';
        const info = {
          code,
          playerName: pName,
          playerPhone: c.playerPhone || c.player_phone || '',
          sellerName: c.sellerName || c.seller_name || '',
          esPromo: c.esPromo || c.es_promo
        };
        map[code] = info;
        map[code.toLowerCase()] = info;
        map[code.toUpperCase()] = info;
      }
    });
    return map;
  }, [room.realRoomCards]);

  // Catálogo base de cartones oficiales pregenerados (Serie determinista consistente en todas las terminales)
  const generateCatalogBatch = useCallback((total = 48, offset = 0) => {
    const list = [];
    const seenCodes = new Set();
    for (let i = 1; i <= total; i++) {
      const idx = i + offset;
      if (window.generateSingleCard3x9) {
        const c = window.generateSingleCard3x9(idx);
        list.push({
          id: c.card_code,
          card_code: c.card_code,
          title: `Cartón #${idx}`,
          grid: c.grid,
          numbers: c.numbers,
          allNumbers: c.allNumbers || c.numbers
        });
        seenCodes.add(c.card_code);
      }
    }

    // Incorporar cualquier cartón ya vendido en la sala para visibilizar su bloqueo aunque no esté en la serie activa
    (room.realRoomCards || []).forEach(sc => {
      const code = sc.id || sc.card_code;
      if (code && !seenCodes.has(code)) {
        const pName = sc.playerName || sc.player_name || (Array.isArray(sc.usuarios) ? sc.usuarios[0]?.nombre : sc.usuarios?.nombre) || '';
        list.push({
          id: code,
          card_code: code,
          title: sc.title || (pName ? `Cartón de ${pName}` : `Cartón ${code}`),
          playerName: pName,
          grid: sc.grid,
          numbers: sc.allNumbers || sc.numbers || (sc.grid ? sc.grid.flat().filter(n => n !== null && n !== undefined) : []),
          allNumbers: sc.allNumbers || sc.numbers || (sc.grid ? sc.grid.flat().filter(n => n !== null && n !== undefined) : [])
        });
        seenCodes.add(code);
      }
    });

    return list;
  }, [room.realRoomCards]);

  const sellerCatalog = useMemo(() => {
    return generateCatalogBatch(48, catalogSeriesOffset);
  }, [generateCatalogBatch, catalogSeriesOffset]);

  const [catalogSearch, setCatalogSearch] = useState(() => {
    try {
      const urlParams = new URLSearchParams(window.location.search);
      return urlParams.get('q') || urlParams.get('search') || '';
    } catch (e) {
      return '';
    }
  });

  const handleRefreshSellerCatalog = () => {
    setCatalogSeriesOffset(prev => (prev >= 144 ? 0 : prev + 48));
  };

  // Contadores en vivo de Disponibles y Vendidos en el Catálogo
  const { availableCount, soldCount } = useMemo(() => {
    let sold = 0;
    let available = 0;
    sellerCatalog.forEach(c => {
      const code = c.id || c.card_code;
      if (soldCardsMap[code]) sold++;
      else available++;
    });
    return { availableCount: available, soldCount: sold };
  }, [sellerCatalog, soldCardsMap]);

  // Filtrado del catálogo por números de la suerte y por estado de venta
  const activeCatalogSearchNums = useMemo(() => {
    if (!catalogSearch.trim()) return [];
    return catalogSearch
      .split(/[\s,.-]+/)
      .map(n => parseInt(n.trim(), 10))
      .filter(n => !isNaN(n) && n >= 1 && n <= 90);
  }, [catalogSearch]);

  const filteredSellerCatalog = useMemo(() => {
    const rawSearch = catalogSearch.trim().toLowerCase();
    return sellerCatalog.filter(c => {
      const code = (c.id || c.card_code || '').toLowerCase();
      const isSold = Boolean(soldCardsMap[c.id] || soldCardsMap[c.card_code]);
      const soldInfo = soldCardsMap[c.id] || soldCardsMap[c.card_code];
      if (hideSoldCards && isSold) return false;

      if (!rawSearch) return true;

      // 1. Búsqueda directa por código de cartón (ej: "CR-10001" o "10001")
      if (code.includes(rawSearch) || (c.title && c.title.toLowerCase().includes(rawSearch))) {
        return true;
      }

      // 2. Búsqueda por nombre del comprador si ya está vendido (ej: "Sandra", "Alvaro")
      if (c.playerName && c.playerName.toLowerCase().includes(rawSearch)) {
        return true;
      }
      if (soldInfo && soldInfo.playerName && soldInfo.playerName.toLowerCase().includes(rawSearch)) {
        return true;
      }

      // 3. Búsqueda por números de la suerte (1 a 90)
      if (activeCatalogSearchNums.length > 0) {
        const allNums = c.allNumbers || (c.grid ? c.grid.flat().filter(n => n !== null && n !== undefined) : []);
        return activeCatalogSearchNums.every(fn => allNums.includes(fn));
      }

      return false;
    });
  }, [sellerCatalog, soldCardsMap, hideSoldCards, catalogSearch, activeCatalogSearchNums]);

  // Deselección reactiva en tiempo real si un cartón seleccionado es vendido por otro vendedor
  useEffect(() => {
    if (selectedCatalogCards.length === 0) return;
    const evicted = [];
    const remaining = selectedCatalogCards.filter(c => {
      const code = c.id || c.card_code;
      const soldInfo = soldCardsMap[code];
      if (soldInfo) {
        evicted.push({ code, by: soldInfo.playerName });
        return false;
      }
      return true;
    });

    if (evicted.length > 0) {
      setSelectedCatalogCards(remaining);
      const details = evicted.map(e => `${e.code} (vendido a ${e.by})`).join(', ');
      alert(`⚠️ AVISO EN TIEMPO REAL:\nEl/Los siguiente(s) cartón(es) acaban de ser vendidos en vivo por otro vendedor y fueron retirados de tu selección:\n• ${details}`);
    }
  }, [soldCardsMap]);

  // Selección/deselección de cartones en el catálogo embebido (uno por uno) con bloqueo en tiempo real
  const toggleSelectCatalogCard = (card) => {
    const code = card.id || card.card_code;
    const soldInfo = soldCardsMap[code];
    if (soldInfo) {
      alert(`🔒 CARTÓN BLOQUEADO: El cartón ${code} ya fue vendido a "${soldInfo.playerName}". No puede ser seleccionado.`);
      return;
    }

    setSelectedCatalogCards(prev => {
      const exists = prev.some(c => (c.id === card.id || c.card_code === card.id || c.id === card.card_code));
      if (exists) {
        return prev.filter(c => !(c.id === card.id || c.card_code === card.id || c.id === card.card_code));
      } else {
        if (prev.length >= 20) {
          alert("Máximo 20 cartones por venta.");
          return prev;
        }
        return [...prev, card];
      }
    });
  };

  const handleClearCatalogSelection = () => {
    setSelectedCatalogCards([]);
  };

  // Cálculos en vivo del catálogo (uno por uno)
  const catalogCount = selectedCatalogCards.length;
  const isCatalogPromoExact = catalogCount === 3;
  const isCatalogPromoFourOrMore = catalogCount >= 4;
  const catalogPayable = isCatalogPromoExact ? 3 : (isCatalogPromoFourOrMore ? catalogCount - 1 : catalogCount);
  const catalogTotalPrice = catalogPayable * 1000;

  // Cargar los cartones elegidos uno por uno del catálogo al formulario de venta
  const handleApplyCatalogSelectionToForm = () => {
    if (selectedCatalogCards.length === 0) {
      alert("Por favor selecciona al menos 1 cartón del catálogo.");
      return;
    }
    setIsCustomSelection(true);
    const chosen = selectedCatalogCards.map((c, idx) => ({
      ...c,
      id: c.id || c.card_code,
      card_code: c.card_code || c.id,
      title: (selectedCatalogCards.length >= 4 && idx === 3) || c.es_promo
        ? `Cartón #${idx + 1} (🎁 PROMO 3+1 REGALO)`
        : `Cartón #${idx + 1}`,
      es_promo: (selectedCatalogCards.length >= 4 && idx === 3) || !!c.es_promo
    }));
    setPreviewCards(chosen);

    const payable = chosen.length === 4 ? 3 : (chosen.length > 4 ? chosen.length - 1 : chosen.length);
    setFormData(prev => ({
      ...prev,
      cardsCount: payable
    }));
    setActiveViewTab('sell');
  };

  // Regenerar automáticamente SOLO si no se seleccionaron cartones a mano del catálogo
  useEffect(() => {
    if (!isCustomSelection) {
      setPreviewCards(generateCardsPreview(totalCardsToReceive, formData.name));
    }
  }, [totalCardsToReceive, generateCardsPreview, isCustomSelection]);

  const handleShufflePreviewCards = () => {
    setIsCustomSelection(false);
    setSelectedCatalogCards([]);
    setPreviewCards(generateCardsPreview(totalCardsToReceive, formData.name));
  };

  const handleResetToRandom = () => {
    setIsCustomSelection(false);
    setSelectedCatalogCards([]);
    setPreviewCards(generateCardsPreview(totalCardsToReceive, formData.name));
  };

  const handleCatalogConfirm = (data) => {
    if (data && data.cards && data.cards.length > 0) {
      setSelectedCatalogCards(data.cards);
      setIsCustomSelection(true);
      const chosen = data.cards.map((c, idx) => ({
        ...c,
        id: c.id || c.card_code,
        card_code: c.card_code || c.id,
        title: (data.cards.length >= 4 && idx === 3) || c.es_promo
          ? `Cartón #${idx + 1} (🎁 PROMO 3+1 REGALO)`
          : `Cartón #${idx + 1}`,
        es_promo: (data.cards.length >= 4 && idx === 3) || !!c.es_promo
      }));
      setPreviewCards(chosen);
      const payable = data.payableCount || (chosen.length === 4 ? 3 : (chosen.length > 4 ? chosen.length - 1 : chosen.length));
      setFormData(prev => ({
        ...prev,
        cardsCount: payable,
        name: data.playerName || prev.name,
        phone: data.playerPhone || prev.phone
      }));
      setActiveViewTab('sell');
      setShowCatalogModal(false);
    }
  };

  const handleOpenReceiptCards = async (receipt) => {
    setViewingReceipt(receipt);
    setLoadingViewingCards(true);
    try {
      if (window.ReceiptService && window.ReceiptService.getCardsByReceiptId) {
        const cards = await window.ReceiptService.getCardsByReceiptId(receipt.id);
        setViewingCards(cards || []);
      }
    } catch (e) {
      console.error("Error al cargar cartones:", e);
    } finally {
      setLoadingViewingCards(false);
    }
  };

  // Descarga directa en PDF para cualquier fila del historial del vendedor
  const handleDownloadReceiptPDF = async (receipt) => {
    if (!receipt) return;
    setDownloadingReceiptId(receipt.id);
    try {
      let cards = [];
      if (window.ReceiptService && window.ReceiptService.getCardsByReceiptId) {
        cards = await window.ReceiptService.getCardsByReceiptId(receipt.id);
      }

      // Si por alguna razón la BD aún no tiene los cartones o coinciden con el último emitido en memoria
      if ((!cards || cards.length === 0) && lastAssignedResult && lastAssignedResult.cards && (lastAssignedResult.phone === receipt.player_phone || lastAssignedResult.playerName === receipt.player_name)) {
        cards = lastAssignedResult.cards;
      }

      if (!cards || cards.length === 0) {
        alert("No se encontraron cartones guardados para este comprobante.");
        return;
      }

      if (window.downloadCardsPDF) {
        window.downloadCardsPDF(cards, receipt.player_name);
      } else {
        alert("El generador de PDF no está listo. Por favor refresca la página.");
      }
    } catch (err) {
      console.error("Error al descargar PDF:", err);
      alert("Error al descargar el PDF de cartones: " + (err.message || err));
    } finally {
      setDownloadingReceiptId(null);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!isSalesOpen) {
      alert("La venta oficial de cartones para este sorteo se encuentra CERRADA por el organizador.");
      return;
    }
    if (!formData.name.trim()) {
      alert("Por favor ingresa el Nombre y Apellido del comprador.");
      return;
    }
    if (!formData.phone.trim()) {
      alert("Por favor ingresa el WhatsApp o Teléfono del comprador.");
      return;
    }

    setIsSubmitting(true);

    try {
      if (!window.ReceiptService) {
        throw new Error("Servicio de comprobantes no disponible.");
      }

      const res = await window.ReceiptService.createManualPlayer({
        playerName: formData.name.trim(),
        playerPhone: formData.phone.trim(),
        cardsCount: payableCount,
        amount: totalPrice,
        operationNumber: formData.operationNumber || `VEND-${Date.now().toString().slice(-4)}`,
        sellerId: sellerId,
        sellerName: sellerName,
        paymentMethod: formData.paymentMethod,
        customCards: previewCards
      });

      if (res && res.success) {
        const assignedResult = {
          playerName: formData.name.trim(),
          phone: formData.phone.trim(),
          totalCards: totalCardsToReceive,
          cards: res.cards || previewCards,
          amount: totalPrice
        };
        setLastAssignedResult(assignedResult);

        // Si la vendedora activó la descarga automática para imprimir en papel
        if (autoDownloadPdf && window.downloadCardsPDF) {
          window.downloadCardsPDF(assignedResult.cards, assignedResult.playerName);
        }

        // Limpiar formulario y preparar nueva tanda para la próxima venta
        setFormData({
          name: '',
          phone: '',
          cardsCount: 3,
          paymentMethod: 'Efectivo',
          operationNumber: '',
          notes: ''
        });

        setPreviewCards(generateCardsPreview(4));
        reloadDatabase();
      } else {
        alert("No se pudo registrar la venta.");
      }
    } catch (err) {
      console.error(err);
      alert("Error al registrar jugador: " + err.message);
    } finally {
      setIsSubmitting(false);
    }
  };

  // Enviar mensaje de WhatsApp al comprador con sus cartones y enlace directo
  const handleSendWhatsApp = async (player) => {
    if (!player) return;
    const rawPhone = player.phone || player.player_phone || '';
    const cleanPhone = rawPhone.replace(/[^0-9]/g, '');
    const phoneWithCountry = cleanPhone.startsWith('54') ? cleanPhone : `549${cleanPhone}`;
    const pName = player.playerName || player.player_name || 'Jugador';
    const totalCount = player.totalCards || player.cards_count || (player.cards ? player.cards.length : '');

    // Si no tenemos los cartones del jugador pero tenemos el ID del comprobante, buscarlos
    let cards = player.cards || [];
    if ((!cards || cards.length === 0) && player.id && window.ReceiptService?.getCardsByReceiptId) {
      try {
        cards = await window.ReceiptService.getCardsByReceiptId(player.id);
      } catch (e) {}
    }

    let codesText = '';
    if (cards && cards.length > 0) {
      const codes = cards.map(c => c.card_code || c.id).filter(Boolean);
      if (codes.length > 0) {
        codesText = `\n🎟️ *Tus Códigos de Cartón:* ${codes.join(', ')}`;
      }
    }

    // Enlace inteligente directo con el teléfono para que al hacer clic se le carguen los cartones de inmediato
    const directLink = `${window.location.origin}${window.location.pathname}?mode=spectator&phone=${encodeURIComponent(cleanPhone)}`;

    const text = `🎉 ¡Hola ${pName}! Ya están registrados tus *${totalCount} cartones* para el sorteo oficial de *Lota Familiar La Mami*.${codesText}\n\n🏆 *Premios en Juego (en orden de sorteo):*\n• 1° Sorteo: Premio 3 (Bingo $50.000 + Línea $10.000)\n• 2° Sorteo: Premio 2 (Bingo $50.000 + Línea $10.000)\n• 3° Sorteo: Premio 1 Mayor (Bingo $100.000 + Línea $10.000)\n• Gran Sorteo Final por N° de Cartón: $10.000 al cierre\n\n📺 *Mirá el sorteo en vivo y jugá con tus cartones:* \n👉 ${directLink}\n\n📄 *¿Jugás en papel impreso?*\nSi compraste tu cartón físico en papel, ya podés tenerlo a mano para marcarlo con lapicera. O podés descargarlo e imprimirlo en PDF desde el mismo enlace con el botón "Descargar PDF (A4)".\n\n¡Mucha suerte! 🍀\n_Registrado por ${sellerName}_`;

    const url = `https://wa.me/${phoneWithCountry}?text=${encodeURIComponent(text)}`;
    window.open(url, '_blank');
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '24px', maxWidth: '1100px', margin: '0 auto' }}>
      {/* ========================================================
          1. HEADER Y TARJETAS DE ESTADÍSTICAS DEL VENDEDOR
         ======================================================== */}
      <div style={{
        background: 'linear-gradient(135deg, rgba(30, 41, 59, 0.95), rgba(15, 23, 42, 0.95))',
        border: '1.5px solid rgba(6, 182, 212, 0.4)',
        borderRadius: 'var(--radius-lg)',
        padding: '20px 24px',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        flexWrap: 'wrap',
        gap: '16px',
        boxShadow: '0 8px 24px rgba(6, 182, 212, 0.1)'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '14px' }}>
          <div style={{
            width: '54px',
            height: '54px',
            borderRadius: '50%',
            backgroundColor: 'rgba(6, 182, 212, 0.2)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: '1.5rem',
            color: 'var(--accent-cyan)'
          }}>
            <i className="fa-solid fa-user-tag"></i>
          </div>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <h2 style={{ fontSize: '1.3rem', fontWeight: '900', margin: 0, color: '#ffffff' }}>
                {sellerName}
              </h2>
              <span className="brand-badge" style={{ backgroundColor: 'var(--accent-cyan)', color: '#111827', fontWeight: '800' }}>
                Vendedor Oficial
              </span>
            </div>
            <p style={{ margin: '4px 0 0', fontSize: '0.85rem', color: 'var(--text-muted)' }}>
              Terminal de Carga de Jugadores • {sellerPhone ? `WhatsApp: ${sellerPhone}` : 'Acceso Directo'}
            </p>
          </div>
        </div>

        {/* Métricas del Vendedor */}
        <div style={{ display: 'flex', gap: '16px', flexWrap: 'wrap' }}>
          <div style={{ background: 'rgba(15, 23, 42, 0.7)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md)', padding: '10px 16px', textAlign: 'center' }}>
            <div style={{ fontSize: '0.72rem', color: 'var(--text-muted)', textTransform: 'uppercase', fontWeight: '800' }}>Jugadores</div>
            <div style={{ fontSize: '1.4rem', fontWeight: '900', color: 'var(--accent-teal)' }}>{stats.totalPlayers}</div>
          </div>

          <div style={{ background: 'rgba(15, 23, 42, 0.7)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md)', padding: '10px 16px', textAlign: 'center' }}>
            <div style={{ fontSize: '0.72rem', color: 'var(--text-muted)', textTransform: 'uppercase', fontWeight: '800' }}>Cartones Vendidos</div>
            <div style={{ fontSize: '1.4rem', fontWeight: '900', color: 'var(--accent-cyan)' }}>{stats.totalCards}</div>
          </div>

          <div style={{ background: 'rgba(15, 23, 42, 0.7)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md)', padding: '10px 16px', textAlign: 'center' }}>
            <div style={{ fontSize: '0.72rem', color: 'var(--text-muted)', textTransform: 'uppercase', fontWeight: '800' }}>Recaudado</div>
            <div style={{ fontSize: '1.4rem', fontWeight: '900', color: 'var(--accent-green)' }}>
              ${stats.totalAmount.toLocaleString('es-AR')}
            </div>
          </div>

          {/* Botón Acceso Rápido a Rendición */}
          <button
            type="button"
            className="btn btn-secondary"
            onClick={() => setActiveViewTab('settlement')}
            style={{
              background: activeViewTab === 'settlement' ? 'var(--accent-gold)' : 'rgba(245, 158, 11, 0.12)',
              border: '1.5px solid rgba(245, 158, 11, 0.5)',
              borderRadius: 'var(--radius-md)',
              padding: '8px 16px',
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
              color: activeViewTab === 'settlement' ? '#111827' : 'var(--accent-gold)',
              fontWeight: '900',
              cursor: 'pointer'
            }}
            title="Abrir resumen de rendición y arqueo de caja"
          >
            <i className="fa-solid fa-file-invoice-dollar" style={{ fontSize: '1.15rem', marginBottom: '2px' }}></i>
            <span style={{ fontSize: '0.72rem', textTransform: 'uppercase' }}>Rendir Caja</span>
          </button>
        </div>
      </div>

      {/* Aviso de Venta Cerrada por Organizador */}
      {!isSalesOpen && (
        <div style={{
          padding: '14px 18px',
          background: 'rgba(239, 68, 68, 0.16)',
          border: '1.5px solid rgba(239, 68, 68, 0.55)',
          borderRadius: 'var(--radius-lg)',
          color: '#fca5a5',
          fontSize: '0.88rem',
          display: 'flex',
          alignItems: 'center',
          gap: '12px',
          boxShadow: '0 4px 16px rgba(239, 68, 68, 0.15)'
        }}>
          <i className="fa-solid fa-lock" style={{ fontSize: '1.4rem', color: '#f87171' }}></i>
          <div>
            <strong style={{ color: '#ffffff', display: 'block', fontSize: '0.95rem' }}>
              VENTA DE CARTONES CERRADA POR EL ORGANIZADOR
            </strong>
            <span style={{ fontSize: '0.82rem', color: 'rgba(255,255,255,0.75)' }}>
              La emisión de nuevos cartones está bloqueada para este sorteo. Puedes consultar ventas anteriores y realizar tu Rendición de Ventas / Arqueo de Caja con total normalidad.
            </span>
          </div>
        </div>
      )}

      {/* Selector de Pestañas: Venta Directa vs Catálogo vs Rendición de Ventas */}
      <div style={{
        display: 'flex',
        gap: '12px',
        alignItems: 'center',
        background: 'rgba(15, 23, 42, 0.75)',
        padding: '10px 16px',
        borderRadius: 'var(--radius-lg)',
        border: '1px solid var(--border-subtle)',
        flexWrap: 'wrap'
      }}>
        <button
          type="button"
          className={`btn ${activeViewTab === 'sell' ? 'btn-primary' : 'btn-secondary'}`}
          onClick={() => setActiveViewTab('sell')}
          style={{
            fontWeight: '900',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            gap: '8px',
            padding: '10px 14px',
            fontSize: '0.88rem',
            flex: '1 1 auto',
            minWidth: 0
          }}
        >
          <i className="fa-solid fa-cart-shopping"></i>
          <span>1. Formulario de Venta</span>
          {!isSalesOpen && (
            <span style={{ backgroundColor: '#ef4444', color: '#ffffff', borderRadius: '12px', padding: '1px 7px', fontSize: '0.7rem', fontWeight: '900' }}>
              🔒 CERRADO
            </span>
          )}
        </button>

        <button
          type="button"
          className={`btn ${activeViewTab === 'catalog' ? 'btn-primary' : 'btn-secondary'}`}
          onClick={() => setActiveViewTab('catalog')}
          style={{
            fontWeight: '900',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            gap: '8px',
            padding: '10px 14px',
            fontSize: '0.88rem',
            flex: '1 1 auto',
            minWidth: 0,
            border: activeViewTab !== 'catalog' ? '1.5px solid var(--accent-gold)' : undefined,
            color: activeViewTab !== 'catalog' ? 'var(--accent-gold)' : undefined
          }}
        >
          <i className="fa-solid fa-layer-group"></i>
          <span>2. 🗂️ Catálogo de Cartones</span>
          {selectedCatalogCards.length > 0 && (
            <span style={{ backgroundColor: '#10b981', color: '#fff', borderRadius: '12px', padding: '2px 9px', fontSize: '0.74rem', fontWeight: '900' }}>
              ✓ {selectedCatalogCards.length}
            </span>
          )}
        </button>

        <button
          type="button"
          className={`btn ${activeViewTab === 'settlement' ? 'btn-primary' : 'btn-secondary'}`}
          onClick={() => setActiveViewTab('settlement')}
          style={{
            fontWeight: '900',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            gap: '8px',
            padding: '10px 14px',
            fontSize: '0.88rem',
            flex: '1 1 auto',
            minWidth: 0,
            background: activeViewTab === 'settlement' ? 'linear-gradient(135deg, #f59e0b, #d97706)' : undefined,
            color: activeViewTab === 'settlement' ? '#111827' : 'var(--accent-gold)',
            border: '1.5px solid rgba(245, 158, 11, 0.5)'
          }}
        >
          <i className="fa-solid fa-file-invoice-dollar"></i>
          <span>3. 📊 Rendición de Ventas</span>
        </button>
      </div>

      {/* ========================================================
          2. FORMULARIO PRINCIPAL: CARGA Y VENTA DE CARTONES
         ======================================================== */}
      {activeViewTab === 'sell' && (
      <div className="grid-2-col" style={{ alignItems: 'start' }}>
        {/* Formulario de Registro */}
        <div style={{
          background: 'var(--bg-surface)',
          border: '1.5px solid var(--border-subtle)',
          borderRadius: 'var(--radius-lg)',
          padding: '24px',
          boxShadow: 'var(--shadow-md)'
        }}>
          <h3 style={{ fontSize: '1.15rem', fontWeight: '900', margin: '0 0 16px', display: 'flex', alignItems: 'center', gap: '8px', color: 'var(--text-main)' }}>
            <i className="fa-solid fa-cart-plus" style={{ color: 'var(--accent-teal)' }}></i>
            Registrar Nuevo Comprador
          </h3>

          <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
            {/* Nombre */}
            <div>
              <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: '700', marginBottom: '6px', color: 'var(--text-main)' }}>
                Nombre y Apellido del Jugador <span style={{ color: '#ef4444' }}>*</span>
              </label>
              <input
                type="text"
                placeholder="Ej: Marcelo Gallardo"
                value={formData.name}
                onChange={e => setFormData({ ...formData, name: e.target.value })}
                required
                style={{
                  width: '100%',
                  padding: '11px 14px',
                  borderRadius: 'var(--radius-md)',
                  border: '1px solid var(--border-subtle)',
                  background: 'rgba(15, 23, 42, 0.6)',
                  color: '#ffffff',
                  fontSize: '0.95rem'
                }}
              />
            </div>

            {/* Teléfono / WhatsApp */}
            <div>
              <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: '700', marginBottom: '6px', color: 'var(--text-main)' }}>
                WhatsApp / Teléfono <span style={{ color: '#ef4444' }}>*</span>
              </label>
              <input
                type="text"
                placeholder="Ej: 3875123456"
                value={formData.phone}
                onChange={e => setFormData({ ...formData, phone: e.target.value })}
                required
                style={{
                  width: '100%',
                  padding: '11px 14px',
                  borderRadius: 'var(--radius-md)',
                  border: '1px solid var(--border-subtle)',
                  background: 'rgba(15, 23, 42, 0.6)',
                  color: '#ffffff',
                  fontSize: '0.95rem'
                }}
              />
            </div>

            {/* Selector de Promo / Cantidad de Cartones */}
            <div>
              <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: '700', marginBottom: '6px', color: 'var(--text-main)' }}>
                Combo / Cantidad de Cartones
              </label>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '8px', marginBottom: '8px' }}>
                <button
                  type="button"
                  className={`btn ${formData.cardsCount === 1 && !isCustomSelection ? 'btn-primary' : 'btn-secondary'}`}
                  onClick={() => { setIsCustomSelection(false); setFormData({ ...formData, cardsCount: 1 }); }}
                  style={{ padding: '8px', fontSize: '0.82rem', fontWeight: '800' }}
                >
                  1 Cartón<br />
                  <span style={{ fontSize: '0.72rem', opacity: 0.8 }}>$1.000</span>
                </button>

                <button
                  type="button"
                  className={`btn ${formData.cardsCount === 3 && !isCustomSelection ? 'btn-primary' : 'btn-secondary'}`}
                  onClick={() => { setIsCustomSelection(false); setFormData({ ...formData, cardsCount: 3 }); }}
                  style={{ 
                    padding: '8px', 
                    fontSize: '0.82rem', 
                    fontWeight: '800',
                    border: formData.cardsCount === 3 && !isCustomSelection ? '2px solid var(--accent-gold)' : undefined,
                    background: formData.cardsCount === 3 && !isCustomSelection ? 'linear-gradient(135deg, #f59e0b, #d97706)' : undefined,
                    color: formData.cardsCount === 3 && !isCustomSelection ? '#111' : undefined
                  }}
                >
                  🎁 PROMO 3+1<br />
                  <span style={{ fontSize: '0.72rem' }}>4 Cartones x $3.000</span>
                </button>

                <button
                  type="button"
                  className={`btn ${formData.cardsCount === 2 && !isCustomSelection ? 'btn-primary' : 'btn-secondary'}`}
                  onClick={() => { setIsCustomSelection(false); setFormData({ ...formData, cardsCount: 2 }); }}
                  style={{ padding: '8px', fontSize: '0.82rem', fontWeight: '800' }}
                >
                  2 Cartones<br />
                  <span style={{ fontSize: '0.72rem', opacity: 0.8 }}>$2.000</span>
                </button>
              </div>

              {/* Botón directo para elegir del catálogo */}
              <button
                type="button"
                className="btn btn-secondary"
                onClick={() => setShowCatalogModal(true)}
                style={{
                  width: '100%',
                  padding: '9px 12px',
                  fontSize: '0.85rem',
                  fontWeight: '800',
                  color: 'var(--accent-gold)',
                  border: '1.5px dashed var(--accent-gold)',
                  background: 'rgba(245, 158, 11, 0.08)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  gap: '8px',
                  marginBottom: '10px'
                }}
              >
                <i className="fa-solid fa-layer-group"></i>
                <span>🗂️ Elegir del Catálogo (Buscar Números del Cliente)</span>
              </button>

              {/* Selector numérico libre si quiere otra cantidad */}
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <span style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}>Otras cantidades:</span>
                <input
                  type="number"
                  min="1"
                  max="50"
                  value={formData.cardsCount}
                  onChange={e => setFormData({ ...formData, cardsCount: parseInt(e.target.value, 10) || 1 })}
                  style={{
                    width: '70px',
                    padding: '6px 8px',
                    borderRadius: 'var(--radius-sm)',
                    border: '1px solid var(--border-subtle)',
                    background: 'rgba(15, 23, 42, 0.6)',
                    color: '#ffffff',
                    textAlign: 'center',
                    fontWeight: '800'
                  }}
                />
                <span style={{ fontSize: '0.82rem', color: 'var(--accent-teal)', fontWeight: '700' }}>
                  Recibe {totalCardsToReceive} cartones en total
                </span>
              </div>
            </div>

            {/* Medio de Pago */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>
              <div>
                <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: '700', marginBottom: '6px', color: 'var(--text-main)' }}>
                  Forma de Pago
                </label>
                <select
                  value={formData.paymentMethod}
                  onChange={e => setFormData({ ...formData, paymentMethod: e.target.value })}
                  style={{
                    width: '100%',
                    padding: '11px 12px',
                    borderRadius: 'var(--radius-md)',
                    border: '1px solid var(--border-subtle)',
                    background: 'rgba(15, 23, 42, 0.6)',
                    color: '#ffffff',
                    fontSize: '0.9rem'
                  }}
                >
                  <option value="Efectivo">Efectivo en Mano</option>
                  <option value="Transferencia / MercadoPago">Transferencia / MP</option>
                  <option value="Fiado / Pendiente">A Cobrar</option>
                </select>
              </div>

              <div>
                <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: '700', marginBottom: '6px', color: 'var(--text-main)' }}>
                  N° Comprobante (Opcional)
                </label>
                <input
                  type="text"
                  placeholder="Ej: 789234"
                  value={formData.operationNumber}
                  onChange={e => setFormData({ ...formData, operationNumber: e.target.value })}
                  style={{
                    width: '100%',
                    padding: '11px 12px',
                    borderRadius: 'var(--radius-md)',
                    border: '1px solid var(--border-subtle)',
                    background: 'rgba(15, 23, 42, 0.6)',
                    color: '#ffffff',
                    fontSize: '0.9rem'
                  }}
                />
              </div>
            </div>

            {/* Resumen del cobro */}
            <div style={{
              background: 'rgba(16, 185, 129, 0.12)',
              border: '1px solid rgba(16, 185, 129, 0.3)',
              borderRadius: 'var(--radius-md)',
              padding: '12px 16px',
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center'
            }}>
              <div>
                <div style={{ fontSize: '0.78rem', color: 'var(--text-muted)' }}>Total a Cobrar al Cliente:</div>
                <div style={{ fontSize: '1.35rem', fontWeight: '900', color: 'var(--accent-green)' }}>
                  ${totalPrice.toLocaleString('es-AR')}
                </div>
              </div>
              <div style={{ textAlign: 'right', fontSize: '0.82rem', color: 'var(--text-main)' }}>
                <strong>{totalCardsToReceive} cartones</strong> oficiales
                {bonusCards > 0 && <div style={{ color: 'var(--accent-gold)', fontSize: '0.75rem', fontWeight: '700' }}>🎁 Incluye {bonusCards} de regalo</div>}
              </div>
            </div>

            {/* Vista Previa de los Cartones a Emitir */}
            <div style={{
              background: 'rgba(15, 23, 42, 0.75)',
              border: isCustomSelection ? '1.5px solid #10b981' : '1px solid var(--border-subtle)',
              borderRadius: 'var(--radius-md)',
              padding: '14px',
              display: 'flex',
              flexDirection: 'column',
              gap: '10px'
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '8px' }}>
                <div style={{ fontSize: '0.85rem', fontWeight: '800', color: '#ffffff', display: 'flex', alignItems: 'center', gap: '6px' }}>
                  <i className="fa-solid fa-ticket" style={{ color: isCustomSelection ? '#10b981' : 'var(--accent-cyan)' }}></i>
                  <span>Cartones a Entregar ({previewCards.length})</span>
                  {isCustomSelection && (
                    <span className="brand-badge" style={{ backgroundColor: 'rgba(16, 185, 129, 0.25)', color: '#10b981', border: '1px solid #10b981', fontWeight: '900', fontSize: '0.7rem' }}>
                      ✓ DEL CATÁLOGO
                    </span>
                  )}
                </div>
                <div style={{ display: 'flex', gap: '6px' }}>
                  <button
                    type="button"
                    className="btn btn-secondary btn-sm"
                    onClick={() => setShowCatalogModal(true)}
                    style={{ padding: '4px 10px', fontSize: '0.75rem', color: 'var(--accent-gold)', border: '1px solid var(--accent-gold)', fontWeight: '800' }}
                    title="Abrir catálogo para elegir números específicos"
                  >
                    <i className="fa-solid fa-layer-group"></i> Catálogo
                  </button>
                  <button
                    type="button"
                    className="btn btn-secondary btn-sm"
                    onClick={handleShufflePreviewCards}
                    style={{ padding: '4px 8px', fontSize: '0.74rem' }}
                    title="Generar números aleatorios"
                  >
                    <i className="fa-solid fa-dice"></i> {isCustomSelection ? 'Aleatorios' : 'Cambiar'}
                  </button>
                </div>
              </div>

              <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', maxHeight: '240px', overflowY: 'auto', paddingRight: '4px' }}>
                {previewCards.map((c, idx) => {
                  const theme = 'card-theme-ruby';
                  return (
                    <div key={idx} className={`bingo-card-3x9-wrapper ${theme}`} style={{ margin: 0, padding: '10px' }}>
                      <div className="card-header-bar" style={{ padding: '2px 4px', marginBottom: '6px' }}>
                        <span className="card-title-text" style={{ fontSize: '0.82rem' }}>
                          {c.es_promo ? `🎁 Cartón #${idx + 1} (PROMO 3+1 REGALO)` : `Cartón #${idx + 1}`}
                        </span>
                        <span className="card-serial-tag" style={{ fontSize: '0.72rem' }}>{c.id}</span>
                      </div>
                      <div className="teal-bingo-ticket" style={{ padding: '5px' }}>
                        <div className="ticket-grid-3x9" style={{ gap: '2px' }}>
                          {c.grid.map((row, rIdx) => (
                            <div key={rIdx} className="ticket-row" style={{ gap: '2px' }}>
                              {row.map((cellNum, cIdx) => (
                                <div key={cIdx} className={`ticket-cell ${cellNum === null ? 'empty' : ''}`} style={{ height: '24px', fontSize: '0.8rem' }}>
                                  {cellNum !== null && <span>{cellNum}</span>}
                                </div>
                              ))}
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Opción de descarga automática de PDF para papel */}
            <div style={{
              background: 'rgba(255, 255, 255, 0.04)',
              border: '1px solid rgba(255, 255, 255, 0.12)',
              borderRadius: 'var(--radius-md)',
              padding: '10px 14px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              marginBottom: '10px'
            }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: '10px', cursor: 'pointer', margin: 0, fontSize: '0.85rem', color: '#ffffff' }}>
                <input
                  type="checkbox"
                  checked={autoDownloadPdf}
                  onChange={(e) => setAutoDownloadPdf(e.target.checked)}
                  style={{ width: '18px', height: '18px', accentColor: 'var(--accent-gold)', cursor: 'pointer' }}
                />
                <span style={{ fontWeight: '700' }}>
                  📥 Descargar PDF automáticamente al emitir
                </span>
              </label>
              <span style={{ fontSize: '0.75rem', color: 'var(--accent-gold)', fontWeight: '800' }}>
                🖨️ Ideal para imprimir en papel
              </span>
            </div>

            {/* Botón de Envío */}
            <button
              type="submit"
              className="btn btn-primary"
              disabled={isSubmitting || !isSalesOpen}
              style={{
                padding: '14px',
                fontSize: '1rem',
                fontWeight: '900',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                gap: '10px',
                background: !isSalesOpen ? 'rgba(100, 116, 139, 0.4)' : 'linear-gradient(135deg, var(--accent-cyan), #0284c7)',
                cursor: !isSalesOpen ? 'not-allowed' : 'pointer',
                opacity: !isSalesOpen ? 0.75 : 1
              }}
            >
              <i className={`fa-solid ${isSubmitting ? 'fa-spinner fa-spin' : (!isSalesOpen ? 'fa-lock' : 'fa-ticket')}`}></i>
              <span>{isSubmitting ? 'Generando Cartones en Supabase...' : (!isSalesOpen ? '🔒 Venta Cerrada por Organizador' : 'Emitir Cartones y Registrar')}</span>
            </button>
          </form>
        </div>

        {/* Panel Derecho: Última Venta / Acciones de Notificación */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
          {lastAssignedResult ? (
            <div style={{
              background: 'linear-gradient(135deg, rgba(16, 185, 129, 0.15), rgba(6, 182, 212, 0.15))',
              border: '1.5px solid rgba(16, 185, 129, 0.5)',
              borderRadius: 'var(--radius-lg)',
              padding: '20px',
              boxShadow: '0 8px 24px rgba(16, 185, 129, 0.1)'
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '12px' }}>
                <div style={{ width: '36px', height: '36px', borderRadius: '50%', backgroundColor: 'var(--accent-green)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '1.1rem' }}>
                  <i className="fa-solid fa-check"></i>
                </div>
                <div>
                  <h4 style={{ margin: 0, fontSize: '1rem', fontWeight: '900', color: '#ffffff' }}>
                    ¡Venta Registrada Exitosamente!
                  </h4>
                  <span style={{ fontSize: '0.8rem', color: 'var(--accent-green)', fontWeight: '700' }}>
                    {lastAssignedResult.playerName} • {lastAssignedResult.totalCards} Cartones
                  </span>
                </div>
              </div>

              <p style={{ fontSize: '0.85rem', color: 'var(--text-main)', marginBottom: '14px' }}>
                Los cartones ya quedaron dados de alta en Supabase y jugarán en vivo en el sorteo oficial. Elige cómo entregárselos al comprador:
              </p>

              {/* Botones de acción principales: Descarga PDF (Papel) y WhatsApp (Online) */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '10px' }}>
                <button
                  type="button"
                  className="btn"
                  onClick={() => window.downloadCardsPDF && window.downloadCardsPDF(lastAssignedResult.cards, lastAssignedResult.playerName)}
                  style={{
                    padding: '12px 10px',
                    background: 'linear-gradient(135deg, #e11d48, #be123c)',
                    borderColor: '#f43f5e',
                    color: '#ffffff',
                    fontWeight: '800',
                    fontSize: '0.86rem',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: '8px',
                    boxShadow: '0 4px 14px rgba(225, 29, 72, 0.35)',
                    borderRadius: 'var(--radius-md)'
                  }}
                  title="Descargar archivo PDF A4 listo para imprimir y entregar en papel"
                >
                  <i className="fa-solid fa-file-pdf" style={{ fontSize: '1.15rem' }}></i>
                  <span>📄 Descargar PDF (Papel)</span>
                </button>

                <button
                  type="button"
                  className="btn"
                  onClick={() => handleSendWhatsApp(lastAssignedResult)}
                  style={{
                    padding: '12px 10px',
                    backgroundColor: '#25D366',
                    borderColor: '#25D366',
                    color: '#ffffff',
                    fontWeight: '800',
                    fontSize: '0.86rem',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: '8px',
                    boxShadow: '0 4px 14px rgba(37, 211, 102, 0.3)',
                    borderRadius: 'var(--radius-md)'
                  }}
                  title="Enviar mensaje por WhatsApp con enlace directo y códigos"
                >
                  <i className="fa-brands fa-whatsapp" style={{ fontSize: '1.2rem' }}></i>
                  <span>📲 Enviar por WhatsApp</span>
                </button>
              </div>

              {/* Botón rápido combo: Descargar e iniciar WhatsApp en 1 solo clic */}
              <button
                type="button"
                className="btn btn-secondary btn-sm"
                onClick={() => {
                  if (window.downloadCardsPDF) {
                    window.downloadCardsPDF(lastAssignedResult.cards, lastAssignedResult.playerName);
                  }
                  setTimeout(() => handleSendWhatsApp(lastAssignedResult), 400);
                }}
                style={{
                  width: '100%',
                  padding: '9px',
                  marginBottom: '14px',
                  fontSize: '0.82rem',
                  fontWeight: '800',
                  color: 'var(--accent-gold)',
                  borderColor: 'rgba(245, 158, 11, 0.5)',
                  background: 'rgba(245, 158, 11, 0.08)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  gap: '6px'
                }}
                title="Descarga el PDF para imprimir y abre WhatsApp para mandarle el link al cliente"
              >
                <i className="fa-solid fa-wand-magic-sparkles"></i>
                <span>Descargar PDF y Enviar WhatsApp (Ambos en 1 Clic)</span>
              </button>

              {/* Cartones recién asignados */}
              <div style={{ marginTop: '14px', borderTop: '1px solid rgba(16, 185, 129, 0.3)', paddingTop: '12px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' }}>
                  <span style={{ fontSize: '0.85rem', fontWeight: '800', color: '#ffffff' }}>
                    🎟️ Cartones Emitidos ({lastAssignedResult.cards?.length || lastAssignedResult.totalCards}):
                  </span>
                  {lastAssignedResult.cards && lastAssignedResult.cards.length > 0 && (
                    <button
                      type="button"
                      className="btn btn-secondary btn-sm"
                      onClick={() => window.downloadCardsPDF && window.downloadCardsPDF(lastAssignedResult.cards, lastAssignedResult.playerName)}
                      style={{ fontSize: '0.75rem', padding: '4px 10px', color: 'var(--accent-gold)', border: '1px solid rgba(245, 158, 11, 0.4)', fontWeight: '700' }}
                      title="Descargar PDF de los cartones para imprimir o guardar"
                    >
                      <i className="fa-solid fa-file-pdf"></i> Descargar PDF
                    </button>
                  )}
                </div>

                <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', maxHeight: '280px', overflowY: 'auto' }}>
                  {(lastAssignedResult.cards || []).map((c, idx) => {
                    const isPromo = c.es_promo || (idx === 3 && lastAssignedResult.cards.length === 4);
                    const theme = 'card-theme-ruby';
                    return (
                      <div key={c.id || idx} className={`bingo-card-3x9-wrapper ${theme}`} style={{ margin: 0, padding: '10px' }}>
                        <div className="card-header-bar" style={{ padding: '2px 4px', marginBottom: '6px' }}>
                          <span className="card-title-text" style={{ fontSize: '0.82rem' }}>
                            Cartón #{idx + 1} ({lastAssignedResult.playerName}) {isPromo ? '🎁 (PROMO 3+1 REGALO)' : ''}
                          </span>
                          <span className="card-serial-tag" style={{ fontSize: '0.72rem' }}>{c.id || c.card_code}</span>
                        </div>
                        <div className="teal-bingo-ticket" style={{ padding: '5px' }}>
                          <div className="ticket-grid-3x9" style={{ gap: '2px' }}>
                            {c.grid && c.grid.map((row, rIdx) => (
                              <div key={rIdx} className="ticket-row" style={{ gap: '2px' }}>
                                {row.map((cellNum, cIdx) => (
                                  <div key={cIdx} className={`ticket-cell ${cellNum === null ? 'empty' : ''}`} style={{ height: '24px', fontSize: '0.8rem' }}>
                                    {cellNum !== null && <span>{cellNum}</span>}
                                  </div>
                                ))}
                              </div>
                            ))}
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              <div style={{ textAlign: 'center', fontSize: '0.75rem', color: 'var(--text-muted)', marginTop: '8px' }}>
                Se enviará el enlace oficial con el que el comprador podrá ver sus cartones y la transmisión.
              </div>
            </div>
          ) : (
            <div style={{
              background: 'var(--bg-surface)',
              border: '1px dashed var(--border-subtle)',
              borderRadius: 'var(--radius-lg)',
              padding: '30px 20px',
              textAlign: 'center'
            }}>
              <i className="fa-solid fa-receipt" style={{ fontSize: '2.5rem', color: 'var(--text-dim)', marginBottom: '12px' }}></i>
              <h4 style={{ fontSize: '0.95rem', fontWeight: '800', margin: '0 0 6px', color: 'var(--text-muted)' }}>
                Esperando registro de venta
              </h4>
              <p style={{ fontSize: '0.8rem', color: 'var(--text-dim)', margin: 0 }}>
                Completa el formulario de la izquierda para emitir cartones oficiales y enviar el comprobante por WhatsApp al instante.
              </p>
            </div>
          )}

          {/* Guía Rápida para el Vendedor */}
          <div style={{
            background: 'rgba(15, 23, 42, 0.6)',
            border: '1px solid var(--border-subtle)',
            borderRadius: 'var(--radius-lg)',
            padding: '16px 20px'
          }}>
            <h5 style={{ margin: '0 0 10px', fontSize: '0.85rem', fontWeight: '800', color: 'var(--accent-gold)' }}>
              📌 Puntos Clave para Vendedores:
            </h5>
            <ul style={{ margin: 0, paddingLeft: '18px', fontSize: '0.8rem', color: 'var(--text-muted)', display: 'flex', flexDirection: 'column', gap: '6px' }}>
              <li><strong>Promo Oficial 3+1:</strong> Por cada 3 cartones que compra el cliente, el sistema le regala el 4to sin costo extra.</li>
              <li><strong>Asignación Automática:</strong> Cada cartón tiene su código único de serie y los 15 números distribuidos de 1 a 90.</li>
              <li><strong>Acceso al Sorteo:</strong> El comprador no necesita instalar nada, simplemente abre el enlace desde su celular para jugar.</li>
            </ul>
          </div>
        </div>
      </div>
      )}

      {/* ========================================================
          VISTA DEL CATÁLOGO DE CARTONES EMBEBIDO
         ======================================================== */}
      {activeViewTab === 'catalog' && (
        <div style={{
          background: 'var(--bg-surface)',
          border: '1.5px solid var(--accent-gold)',
          borderRadius: 'var(--radius-lg)',
          padding: '24px',
          boxShadow: 'var(--shadow-lg)',
          display: 'flex',
          flexDirection: 'column',
          gap: '20px'
        }}>
          {/* Cabecera del Catálogo */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '14px', borderBottom: '1px solid var(--border-subtle)', paddingBottom: '16px' }}>
            <div>
              <h3 style={{ fontSize: '1.3rem', fontWeight: '900', margin: '0 0 6px', color: '#ffffff', display: 'flex', alignItems: 'center', gap: '10px' }}>
                <i className="fa-solid fa-layer-group" style={{ color: 'var(--accent-gold)' }}></i>
                Catálogo de Cartones Oficiales
              </h3>
              <p style={{ margin: 0, fontSize: '0.86rem', color: 'var(--text-muted)' }}>
                Toca cualquier cartón para seleccionarlo o deseleccionarlo. El cliente puede buscar por sus números de la suerte.
              </p>
            </div>

            <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
              <button
                type="button"
                className="btn btn-secondary"
                onClick={handleRefreshSellerCatalog}
                style={{ fontWeight: '800', fontSize: '0.84rem', display: 'flex', alignItems: 'center', gap: '6px' }}
                title="Generar 48 cartones con nuevas combinaciones oficiales"
              >
                <i className="fa-solid fa-arrows-rotate"></i>
                <span>Renovar Catálogo (Nuevos Números)</span>
              </button>

              <button
                type="button"
                className="btn btn-primary"
                onClick={() => setActiveViewTab('sell')}
                style={{ fontWeight: '800', fontSize: '0.84rem', display: 'flex', alignItems: 'center', gap: '6px' }}
              >
                <i className="fa-solid fa-cart-shopping"></i>
                <span>Ir al Formulario de Venta</span>
              </button>
            </div>
          </div>

          {/* Barra de Búsqueda de Números de la Suerte y Cartones Vendidos */}
          <div style={{
            background: 'rgba(15, 23, 42, 0.75)',
            border: '1px solid var(--border-subtle)',
            borderRadius: 'var(--radius-md)',
            padding: '14px 18px',
            display: 'flex',
            gap: '16px',
            alignItems: 'center',
            flexWrap: 'wrap'
          }}>
            <div style={{ flex: 1, minWidth: '240px', position: 'relative' }}>
              <i className="fa-solid fa-magnifying-glass" style={{ position: 'absolute', left: '14px', top: '50%', transform: 'translateY(-50%)', color: 'var(--accent-gold)' }}></i>
              <input
                type="text"
                className="input-field"
                placeholder="Escribe números de la suerte que busca el cliente (ej: 7, 18, 25)..."
                value={catalogSearch}
                onChange={e => setCatalogSearch(e.target.value)}
                style={{ width: '100%', paddingLeft: '40px', fontSize: '0.92rem' }}
              />
            </div>

            {/* Toggle para ocultar cartones ya vendidos */}
            <label style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer', margin: 0, fontSize: '0.85rem', color: '#ffffff', userSelect: 'none' }}>
              <input
                type="checkbox"
                checked={hideSoldCards}
                onChange={e => setHideSoldCards(e.target.checked)}
                style={{ width: '18px', height: '18px', accentColor: '#ef4444', cursor: 'pointer' }}
              />
              <span style={{ fontWeight: '700' }}>
                🔒 Ocultar vendidos
              </span>
            </label>

            <div style={{ display: 'flex', gap: '12px', alignItems: 'center', flexWrap: 'wrap' }}>
              <span style={{ fontSize: '0.85rem', color: '#cbd5e1' }}>
                Disponibles: <strong style={{ color: '#10b981' }}>{availableCount}</strong> | 
                Vendidos: <strong style={{ color: '#ef4444' }}>{soldCount}</strong> ({sellerCatalog.length} en tanda)
              </span>

              {catalogSearch && (
                <button
                  type="button"
                  className="btn btn-secondary btn-sm"
                  onClick={() => setCatalogSearch('')}
                  style={{ fontSize: '0.78rem' }}
                >
                  Limpiar búsqueda
                </button>
              )}
            </div>
          </div>

          {/* Banner Flotante / Fijo de Resumen de Selección Uno por Uno */}
          <div style={{
            background: 'linear-gradient(135deg, rgba(15, 23, 42, 0.95), rgba(30, 41, 59, 0.95))',
            border: '1.5px solid var(--accent-gold)',
            borderRadius: 'var(--radius-md)',
            padding: '16px 20px',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            flexWrap: 'wrap',
            gap: '14px',
            boxShadow: '0 8px 24px rgba(0, 0, 0, 0.4)'
          }}>
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap' }}>
                <span style={{ fontSize: '1.1rem', fontWeight: '900', color: '#ffffff' }}>
                  {catalogCount} {catalogCount === 1 ? 'Cartón seleccionado' : 'Cartones seleccionados'}
                </span>

                {catalogCount === 0 && (
                  <span style={{ fontSize: '0.84rem', color: 'var(--text-muted)' }}>
                    (Toca cualquier cartón abajo para elegirlo uno por uno)
                  </span>
                )}

                {catalogCount === 3 && (
                  <span className="brand-badge" style={{ backgroundColor: 'rgba(245, 158, 11, 0.25)', color: '#fbbf24', border: '1px solid #fbbf24', fontWeight: '800' }}>
                    💡 ¡Elige 1 cartón más GRATIS por la Promo 3+1!
                  </span>
                )}

                {catalogCount >= 4 && (
                  <span className="brand-badge" style={{ backgroundColor: 'var(--accent-gold)', color: '#111', fontWeight: '900' }}>
                    🎁 ¡PROMO 3+1 APLICADA! (1 Cartón de Regalo)
                  </span>
                )}
              </div>

              <div style={{ fontSize: '1.25rem', fontWeight: '900', color: catalogCount > 0 ? 'var(--accent-green)' : 'var(--text-dim)', fontFamily: 'var(--font-numbers)', marginTop: '4px' }}>
                {catalogCount === 0
                  ? 'Total a cobrar: $0 (Sin cartones elegidos)'
                  : `Total a cobrar: $${catalogTotalPrice.toLocaleString('es-AR')} ${catalogCount >= 4 ? '(Ahorro de $1.000)' : ''}`
                }
              </div>
            </div>

            <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap', alignItems: 'center' }}>
              {catalogCount > 0 && (
                <>
                  <button
                    type="button"
                    className="btn btn-secondary"
                    onClick={() => window.downloadCardsPDF && window.downloadCardsPDF(selectedCatalogCards, formData.name || 'Cartones Seleccionados')}
                    style={{ color: 'var(--accent-gold)', border: '1px solid rgba(245, 158, 11, 0.4)', fontWeight: '700' }}
                    title="Descargar PDF de los cartones seleccionados"
                  >
                    <i className="fa-solid fa-file-pdf"></i>
                    <span>Descargar PDF ({catalogCount})</span>
                  </button>

                  <button
                    type="button"
                    className="btn btn-secondary"
                    onClick={handleClearCatalogSelection}
                    style={{ fontSize: '0.82rem', color: '#f87171', border: '1px solid rgba(248, 113, 113, 0.4)' }}
                    title="Limpiar todos los cartones seleccionados y empezar de cero"
                  >
                    <i className="fa-solid fa-trash-can"></i> Limpiar Selección
                  </button>
                </>
              )}

              <button
                type="button"
                className="btn btn-primary"
                onClick={handleApplyCatalogSelectionToForm}
                disabled={catalogCount === 0}
                style={{
                  padding: '10px 22px',
                  fontWeight: '900',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  opacity: catalogCount === 0 ? 0.45 : 1,
                  cursor: catalogCount === 0 ? 'not-allowed' : 'pointer'
                }}
              >
                <i className="fa-solid fa-arrow-right"></i>
                <span>Cargar Venta con estos {catalogCount} Cartones</span>
              </button>
            </div>
          </div>

          {/* Grilla de Cartones del Catálogo */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(360px, 1fr))',
            gap: '18px'
          }}>
            {filteredSellerCatalog.length === 0 ? (
              <div style={{ gridColumn: '1 / -1', textAlign: 'center', padding: '40px 20px', color: 'var(--text-muted)' }}>
                <i className="fa-solid fa-filter-circle-xmark" style={{ fontSize: '2.5rem', color: 'var(--text-dim)', marginBottom: '12px' }}></i>
                <h4 style={{ color: 'var(--text-main)', margin: '0 0 6px' }}>No hay cartones con esa combinación de números</h4>
                <p style={{ fontSize: '0.85rem', margin: '0 0 16px' }}>Prueba buscando menos números o renueva el catálogo.</p>
                <button type="button" className="btn btn-primary btn-sm" onClick={handleRefreshSellerCatalog}>
                  <i className="fa-solid fa-arrows-rotate"></i> Generar Nuevos Cartones
                </button>
              </div>
            ) : (
              filteredSellerCatalog.map((card, idx) => {
                const code = card.id || card.card_code;
                const isSold = Boolean(soldCardsMap[code]);
                const soldInfo = soldCardsMap[code];
                const isSelected = !isSold && selectedCatalogCards.some(c => (c.id === card.id || c.card_code === card.id || c.id === card.card_code));
                const theme = 'card-theme-ruby';

                return (
                  <div
                    key={card.id || idx}
                    onClick={() => toggleSelectCatalogCard(card)}
                    className={`bingo-card-3x9-wrapper ${theme} ${isSelected ? 'is-selected-card' : ''} ${isSold ? 'is-sold-card' : ''}`}
                    style={{
                      cursor: isSold ? 'not-allowed' : 'pointer',
                      transition: 'all 0.2s ease',
                      position: 'relative',
                      opacity: isSold ? 0.62 : 1,
                      filter: isSold ? 'grayscale(45%)' : undefined,
                      border: isSelected 
                        ? '2.5px solid #10b981' 
                        : (isSold ? '1.5px solid rgba(239, 68, 68, 0.45)' : undefined),
                      boxShadow: isSelected 
                        ? '0 0 25px rgba(16, 185, 129, 0.45)' 
                        : (isSold ? 'none' : undefined),
                      background: isSold ? 'rgba(15, 23, 42, 0.85)' : undefined
                    }}
                    title={isSold ? `🔒 Cartón VENDIDO a ${soldInfo?.playerName || 'Comprador'}` : `Clic para seleccionar ${code}`}
                  >
                    {/* Cabecera del Cartón */}
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <i className={`fa-solid ${isSold ? 'fa-lock' : 'fa-ticket'}`} style={{ color: isSold ? '#ef4444' : (isSelected ? '#10b981' : 'var(--tag-color, #fb7185)') }}></i>
                        <div>
                          <span style={{ fontSize: '0.95rem', fontWeight: '800', color: isSold ? '#f87171' : (isSelected ? '#10b981' : '#ffffff'), display: 'block', lineHeight: 1.2 }}>
                            {card.title || `Cartón #${idx + 1}`}
                          </span>
                          <span style={{ fontSize: '0.72rem', color: isSold ? '#fca5a5' : 'var(--text-dim)', fontFamily: 'monospace' }}>
                            N°: {code}
                          </span>
                        </div>
                      </div>

                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        {isSold ? (
                          <span className="brand-badge" style={{ backgroundColor: 'rgba(239, 68, 68, 0.25)', color: '#ef4444', border: '1px solid #ef4444', fontWeight: '900', fontSize: '0.74rem', padding: '3px 9px', display: 'flex', alignItems: 'center', gap: '5px' }}>
                            <i className="fa-solid fa-lock"></i> VENDIDO
                          </span>
                        ) : isSelected ? (
                          <span className="brand-badge" style={{ backgroundColor: 'rgba(16, 185, 129, 0.25)', color: '#10b981', border: '1px solid #10b981', fontWeight: '900', fontSize: '0.72rem', padding: '2px 8px' }}>
                            ✓ ELEGIDO
                          </span>
                        ) : (
                          <span style={{ fontSize: '0.85rem', fontWeight: '800', color: 'var(--accent-gold)' }}>
                            $1.000
                          </span>
                        )}

                        {!isSold && (
                          <div style={{
                            width: '26px',
                            height: '26px',
                            borderRadius: '50%',
                            background: isSelected ? '#10b981' : 'rgba(255, 255, 255, 0.08)',
                            border: isSelected ? 'none' : '1px solid var(--border-subtle)',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            color: isSelected ? '#fff' : 'transparent',
                            fontSize: '0.8rem',
                            fontWeight: '900'
                          }}>
                            <i className="fa-solid fa-check"></i>
                          </div>
                        )}
                      </div>
                    </div>

                    {/* Cuadrícula Física 3x9 Oficial */}
                    <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) => {
                              const isLucky = cellNum !== null && activeCatalogSearchNums.includes(cellNum);
                              return cellNum !== null && cellNum !== undefined ? (
                                <div
                                  key={cIdx}
                                  className={`ticket-cell ${isLucky ? 'lucky-match' : ''}`}
                                  style={{ minHeight: '30px', fontSize: '0.92rem' }}
                                >
                                  <span>{cellNum}</span>
                                </div>
                              ) : (
                                <div key={cIdx} className="ticket-cell empty" style={{ minHeight: '30px' }}>
                                  {rIdx === 2 && cIdx === 7 && (
                                    <span className="watermark-text">Lota Familiar La Mami</span>
                                  )}
                                </div>
                              );
                            })}
                          </div>
                        ))}
                      </div>
                    </div>

                    {/* Pie del Cartón en el Catálogo */}
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '8px', paddingTop: '6px', borderTop: '1px solid rgba(255, 255, 255, 0.06)' }}>
                      {isSold ? (
                        <span style={{ fontSize: '0.74rem', color: '#f87171', fontWeight: '800', display: 'flex', alignItems: 'center', gap: '5px' }}>
                          <i className="fa-solid fa-user-check"></i> Vendido a: <strong>{soldInfo?.playerName || 'Comprador'}</strong>
                        </span>
                      ) : (
                        <span style={{ fontSize: '0.74rem', color: isSelected ? '#10b981' : 'var(--text-muted)', fontWeight: '700' }}>
                          {isSelected ? '✓ Seleccionado para la venta' : 'Clic para seleccionar este cartón'}
                        </span>
                      )}

                      <span style={{ fontSize: '0.72rem', color: 'var(--text-dim)' }}>
                        15 números oficiales
                      </span>
                    </div>
                  </div>
                );
              })
            )}
          </div>
        </div>
      )}

      {/* ========================================================
          3. PESTAÑA: RENDICIÓN DE VENTAS / ARQUEO DE CAJA
         ======================================================== */}
      {activeViewTab === 'settlement' && (
        <div style={{
          display: 'flex',
          flexDirection: 'column',
          gap: '20px'
        }}>
          {/* Header Panel Rendición */}
          <div style={{
            background: 'linear-gradient(135deg, rgba(30, 41, 59, 0.95), rgba(15, 23, 42, 0.95))',
            border: '1.5px solid var(--accent-gold)',
            borderRadius: 'var(--radius-lg)',
            padding: '24px',
            boxShadow: '0 8px 30px rgba(245, 158, 11, 0.15)'
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: '16px' }}>
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                  <span style={{ fontSize: '1.6rem' }}>📊</span>
                  <h3 style={{ fontSize: '1.35rem', fontWeight: '900', margin: 0, color: '#ffffff' }}>
                    Planilla de Rendición de Ventas & Cierre de Caja
                  </h3>
                  <span className="brand-badge" style={{ backgroundColor: 'var(--accent-gold)', color: '#111827', fontWeight: '900' }}>
                    {sellerName}
                  </span>
                </div>
                <p style={{ margin: '8px 0 0', fontSize: '0.88rem', color: 'var(--text-muted)' }}>
                  Arqueo contable oficial de cobros en efectivo y transferencias bancarias para rendir a la administración de Lota Familiar La Mami.
                </p>
              </div>

              {/* Botonera de Acciones Principales */}
              <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
                <button
                  type="button"
                  className="btn btn-secondary"
                  onClick={reloadDatabase}
                  style={{ fontSize: '0.82rem', padding: '8px 14px' }}
                  title="Recargar datos del servidor"
                >
                  <i className="fa-solid fa-arrows-rotate"></i> Actualizar
                </button>

                <button
                  type="button"
                  className="btn btn-secondary"
                  onClick={() => window.print()}
                  style={{ fontSize: '0.82rem', padding: '8px 14px' }}
                  title="Imprimir directamente este reporte"
                >
                  <i className="fa-solid fa-print"></i> Imprimir
                </button>

                <button
                  type="button"
                  className="btn btn-secondary"
                  onClick={handleDownloadSettlementReport}
                  style={{
                    fontSize: '0.82rem',
                    padding: '8px 16px',
                    fontWeight: '800',
                    color: 'var(--accent-gold)',
                    border: '1.5px solid var(--accent-gold)',
                    background: 'rgba(245, 158, 11, 0.12)'
                  }}
                  title="Descargar Planilla Oficial de Rendición en formato PDF A4 listo para firmar"
                >
                  <i className="fa-solid fa-file-pdf"></i> Descargar Planilla PDF (A4)
                </button>

                <button
                  type="button"
                  className="btn btn-secondary"
                  onClick={handleExportSettlementExcel}
                  style={{
                    fontSize: '0.82rem',
                    padding: '8px 16px',
                    fontWeight: '800',
                    color: '#10b981',
                    border: '1.5px solid #10b981',
                    background: 'rgba(16, 185, 129, 0.12)',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px'
                  }}
                  title="Descargar Planilla Oficial de Rendición en formato Excel (.CSV compatible con Excel y Sheets)"
                >
                  <i className="fa-solid fa-file-excel" style={{ fontSize: '1rem', color: '#10b981' }}></i>
                  <span>Descargar Excel</span>
                </button>

                <button
                  type="button"
                  className="btn"
                  onClick={handleSendSettlementWhatsApp}
                  style={{
                    fontSize: '0.82rem',
                    padding: '8px 18px',
                    fontWeight: '900',
                    backgroundColor: '#25D366',
                    color: '#ffffff',
                    border: 'none',
                    borderRadius: 'var(--radius-md)',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '8px',
                    boxShadow: '0 4px 14px rgba(37, 211, 102, 0.35)',
                    cursor: 'pointer'
                  }}
                  title="Enviar el resumen de rendición y detalle de cobros por WhatsApp al organizador"
                >
                  <i className="fa-brands fa-whatsapp" style={{ fontSize: '1.1rem' }}></i>
                  <span>Enviar Rendición por WhatsApp</span>
                </button>
              </div>
            </div>

            {/* Filtros de Período y Configuración de Comisión */}
            <div style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              flexWrap: 'wrap',
              gap: '16px',
              marginTop: '20px',
              paddingTop: '16px',
              borderTop: '1px solid rgba(255, 255, 255, 0.08)'
            }}>
              {/* Filtro por fecha */}
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <span style={{ fontSize: '0.82rem', color: 'var(--text-muted)', fontWeight: '700' }}>
                  Período de Ventas:
                </span>
                <div style={{ display: 'inline-flex', background: 'rgba(15, 23, 42, 0.8)', padding: '3px', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-subtle)' }}>
                  <button
                    type="button"
                    onClick={() => setSettlementFilter('all')}
                    style={{
                      background: settlementFilter === 'all' ? 'var(--accent-cyan)' : 'transparent',
                      color: settlementFilter === 'all' ? '#111' : 'var(--text-muted)',
                      border: 'none',
                      borderRadius: 'var(--radius-sm)',
                      padding: '5px 12px',
                      fontSize: '0.78rem',
                      fontWeight: '800',
                      cursor: 'pointer'
                    }}
                  >
                    Todas las Ventas ({myReceipts.length})
                  </button>
                  <button
                    type="button"
                    onClick={() => setSettlementFilter('today')}
                    style={{
                      background: settlementFilter === 'today' ? 'var(--accent-cyan)' : 'transparent',
                      color: settlementFilter === 'today' ? '#111' : 'var(--text-muted)',
                      border: 'none',
                      borderRadius: 'var(--radius-sm)',
                      padding: '5px 12px',
                      fontSize: '0.78rem',
                      fontWeight: '800',
                      cursor: 'pointer'
                    }}
                  >
                    Solo Ventas de Hoy
                  </button>
                </div>
              </div>
            </div>
          </div>

          {/* KPI Summary Grid (4 Cajas Contables) */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))',
            gap: '16px'
          }}>
            {/* 1. Total Recaudado / a Rendir */}
            <div style={{
              background: 'linear-gradient(135deg, rgba(16, 185, 129, 0.15), rgba(15, 23, 42, 0.8))',
              border: '1.5px solid rgba(16, 185, 129, 0.4)',
              borderRadius: 'var(--radius-lg)',
              padding: '16px 20px',
              display: 'flex',
              flexDirection: 'column',
              gap: '6px'
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ fontSize: '0.78rem', color: 'var(--text-muted)', fontWeight: '800', textTransform: 'uppercase' }}>
                  Total a Rendir
                </span>
                <i className="fa-solid fa-sack-dollar" style={{ color: 'var(--accent-green)', fontSize: '1.2rem' }}></i>
              </div>
              <div style={{ fontSize: '1.75rem', fontWeight: '900', color: 'var(--accent-green)' }}>
                ${settlementStats.totalAmount.toLocaleString('es-AR')}
              </div>
              <span style={{ fontSize: '0.74rem', color: 'var(--text-dim)' }}>
                100% de lo cobrado a compradores
              </span>
            </div>

            {/* 2. Efectivo en Mano */}
            <div style={{
              background: 'linear-gradient(135deg, rgba(245, 158, 11, 0.15), rgba(15, 23, 42, 0.8))',
              border: '1.5px solid rgba(245, 158, 11, 0.4)',
              borderRadius: 'var(--radius-lg)',
              padding: '16px 20px',
              display: 'flex',
              flexDirection: 'column',
              gap: '6px'
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ fontSize: '0.78rem', color: 'var(--text-muted)', fontWeight: '800', textTransform: 'uppercase' }}>
                  Efectivo en Mano
                </span>
                <i className="fa-solid fa-money-bill-wave" style={{ color: 'var(--accent-gold)', fontSize: '1.2rem' }}></i>
              </div>
              <div style={{ fontSize: '1.75rem', fontWeight: '900', color: 'var(--accent-gold)' }}>
                ${settlementStats.cashAmount.toLocaleString('es-AR')}
              </div>
              <span style={{ fontSize: '0.74rem', color: 'var(--text-dim)' }}>
                Billetes físicos a entregar en mano
              </span>
            </div>

            {/* 3. Transferencias / Alias */}
            <div style={{
              background: 'linear-gradient(135deg, rgba(6, 182, 212, 0.15), rgba(15, 23, 42, 0.8))',
              border: '1.5px solid rgba(6, 182, 212, 0.4)',
              borderRadius: 'var(--radius-lg)',
              padding: '16px 20px',
              display: 'flex',
              flexDirection: 'column',
              gap: '6px'
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ fontSize: '0.78rem', color: 'var(--text-muted)', fontWeight: '800', textTransform: 'uppercase' }}>
                  Transferencias / Alias
                </span>
                <i className="fa-solid fa-building-columns" style={{ color: 'var(--accent-cyan)', fontSize: '1.2rem' }}></i>
              </div>
              <div style={{ fontSize: '1.75rem', fontWeight: '900', color: 'var(--accent-cyan)' }}>
                ${settlementStats.transferAmount.toLocaleString('es-AR')}
              </div>
              <span style={{ fontSize: '0.74rem', color: 'var(--text-dim)' }}>
                Directo a cuenta bancaria / MP
              </span>
            </div>

            {/* 4. Cartones Emitidos */}
            <div style={{
              background: 'linear-gradient(135deg, rgba(236, 72, 153, 0.15), rgba(15, 23, 42, 0.8))',
              border: '1.5px solid rgba(236, 72, 153, 0.4)',
              borderRadius: 'var(--radius-lg)',
              padding: '16px 20px',
              display: 'flex',
              flexDirection: 'column',
              gap: '6px'
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ fontSize: '0.78rem', color: 'var(--text-muted)', fontWeight: '800', textTransform: 'uppercase' }}>
                  Cartones Emitidos
                </span>
                <i className="fa-solid fa-ticket" style={{ color: '#ec4899', fontSize: '1.2rem' }}></i>
              </div>
              <div style={{ fontSize: '1.75rem', fontWeight: '900', color: '#ec4899' }}>
                {settlementStats.totalCards}
              </div>
              <span style={{ fontSize: '0.74rem', color: 'var(--text-dim)' }}>
                {settlementStats.paidCards} pagados + {settlementStats.bonusCards} promo regalo 🎁
              </span>
            </div>
          </div>

          {/* Tabla Detallada de Comprobantes de la Rendición */}
          <div style={{
            background: 'var(--bg-surface)',
            border: '1px solid var(--border-subtle)',
            borderRadius: 'var(--radius-lg)',
            padding: '20px 24px',
            boxShadow: 'var(--shadow-md)'
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px', flexWrap: 'wrap', gap: '12px' }}>
              <div>
                <h4 style={{ fontSize: '1.1rem', fontWeight: '900', margin: 0, color: 'var(--text-main)' }}>
                  Detalle de Comprobantes a Rendir ({settlementStats.visibleReceipts.length})
                </h4>
                <span style={{ fontSize: '0.78rem', color: 'var(--text-muted)' }}>
                  Registro individualizado de cada cobro efectuado
                </span>
              </div>

              {/* Buscador en la rendición */}
              <div style={{ position: 'relative', minWidth: '240px' }}>
                <i className="fa-solid fa-magnifying-glass" style={{ position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)', color: 'var(--text-dim)', fontSize: '0.85rem' }}></i>
                <input
                  type="text"
                  placeholder="Buscar por comprador o teléfono..."
                  value={settlementSearch}
                  onChange={(e) => setSettlementSearch(e.target.value)}
                  style={{
                    width: '100%',
                    padding: '8px 12px 8px 34px',
                    borderRadius: 'var(--radius-md)',
                    border: '1px solid var(--border-subtle)',
                    background: 'rgba(15, 23, 42, 0.7)',
                    color: '#ffffff',
                    fontSize: '0.84rem'
                  }}
                />
              </div>
            </div>

            {settlementStats.visibleReceipts.length === 0 ? (
              <div style={{ textAlign: 'center', padding: '36px 20px', color: 'var(--text-muted)' }}>
                <i className="fa-solid fa-folder-open" style={{ fontSize: '2rem', marginBottom: '10px', color: 'var(--text-dim)' }}></i>
                <p style={{ margin: 0, fontSize: '0.88rem' }}>No se encontraron comprobantes para el filtro seleccionado.</p>
              </div>
            ) : (
              <div style={{ overflowX: 'auto' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.86rem' }}>
                  <thead>
                    <tr style={{ borderBottom: '2px solid var(--border-subtle)', textAlign: 'left', color: 'var(--text-muted)', fontSize: '0.75rem', textTransform: 'uppercase' }}>
                      <th style={{ padding: '10px 12px' }}>#</th>
                      <th style={{ padding: '10px 12px' }}>Comprador</th>
                      <th style={{ padding: '10px 12px' }}>WhatsApp / Teléfono</th>
                      <th style={{ padding: '10px 12px', textAlign: 'center' }}>Cartones</th>
                      <th style={{ padding: '10px 12px' }}>Medio de Pago</th>
                      <th style={{ padding: '10px 12px', textAlign: 'right' }}>Total ($)</th>
                      <th style={{ padding: '10px 12px', textAlign: 'center' }}>Acciones</th>
                    </tr>
                  </thead>
                  <tbody>
                    {settlementStats.visibleReceipts.map((r, idx) => {
                      const isTransfer = r.notes && r.notes.toLowerCase().includes('transferencia');
                      return (
                        <tr key={r.id || idx} style={{ borderBottom: '1px solid var(--border-subtle)' }}>
                          <td style={{ padding: '12px', color: 'var(--text-dim)', fontWeight: '700' }}>
                            {idx + 1}
                          </td>
                          <td style={{ padding: '12px', fontWeight: '800', color: 'var(--text-main)' }}>
                            {r.player_name}
                          </td>
                          <td style={{ padding: '12px', color: 'var(--text-muted)', fontFamily: 'monospace' }}>
                            {r.player_phone || '-'}
                          </td>
                          <td style={{ padding: '12px', textAlign: 'center' }}>
                            <span className="brand-badge" style={{ backgroundColor: 'rgba(6, 182, 212, 0.15)', color: 'var(--accent-cyan)', fontWeight: '900' }}>
                              {r.cards_count}
                            </span>
                          </td>
                          <td style={{ padding: '12px' }}>
                            {isTransfer ? (
                              <span style={{ color: 'var(--accent-cyan)', fontWeight: '800', display: 'flex', alignItems: 'center', gap: '6px' }}>
                                <i className="fa-solid fa-building-columns"></i> Transferencia
                              </span>
                            ) : (
                              <span style={{ color: 'var(--accent-gold)', fontWeight: '800', display: 'flex', alignItems: 'center', gap: '6px' }}>
                                <i className="fa-solid fa-money-bill-wave"></i> Efectivo
                              </span>
                            )}
                          </td>
                          <td style={{ padding: '12px', textAlign: 'right', fontWeight: '900', color: 'var(--accent-green)', fontSize: '0.95rem' }}>
                            ${(parseFloat(r.amount) || 0).toLocaleString('es-AR')}
                          </td>
                          <td style={{ padding: '12px', textAlign: 'center' }}>
                            <div style={{ display: 'inline-flex', gap: '6px' }}>
                              <button
                                className="btn btn-secondary btn-sm"
                                onClick={() => handleOpenReceiptCards(r)}
                                title="Ver cartones de este comprobante"
                                style={{ padding: '4px 8px', fontSize: '0.75rem' }}
                              >
                                <i className="fa-solid fa-eye"></i> Cartones
                              </button>
                              <button
                                className="btn btn-secondary btn-sm"
                                onClick={() => handleDownloadReceiptPDF(r)}
                                title="Descargar PDF de cartones"
                                style={{ padding: '4px 8px', fontSize: '0.75rem', color: 'var(--accent-gold)' }}
                              >
                                <i className="fa-solid fa-file-pdf"></i> PDF
                              </button>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                  <tfoot>
                    <tr style={{ borderTop: '2px solid rgba(255, 255, 255, 0.15)', fontWeight: '900', background: 'rgba(15, 23, 42, 0.6)' }}>
                      <td colSpan="3" style={{ padding: '12px', textTransform: 'uppercase', color: 'var(--text-main)' }}>
                        TOTALES DE ESTA PLANILLA
                      </td>
                      <td style={{ padding: '12px', textAlign: 'center', color: '#ec4899', fontSize: '1rem' }}>
                        {settlementStats.totalCards}
                      </td>
                      <td style={{ padding: '12px', fontSize: '0.8rem', color: 'var(--text-muted)' }}>
                        Efec: ${settlementStats.cashAmount.toLocaleString('es-AR')} | Transf: ${settlementStats.transferAmount.toLocaleString('es-AR')}
                      </td>
                      <td style={{ padding: '12px', textAlign: 'right', color: 'var(--accent-green)', fontSize: '1.15rem' }}>
                        ${settlementStats.totalAmount.toLocaleString('es-AR')}
                      </td>
                      <td></td>
                    </tr>
                  </tfoot>
                </table>
              </div>
            )}
          </div>

          {/* Acta de Cierre y Firmas de Conformidad */}
          <div style={{
            background: 'rgba(15, 23, 42, 0.7)',
            border: '1.5px dashed var(--border-subtle)',
            borderRadius: 'var(--radius-lg)',
            padding: '24px',
            display: 'flex',
            flexDirection: 'column',
            gap: '16px'
          }}>
            <div style={{ fontSize: '0.85rem', color: 'var(--text-muted)', fontStyle: 'italic', textAlign: 'center' }}>
              "Declaro bajo fe de juramento que la presente rendición refleja con total exactitud las sumas percibidas y los cartones emitidos correspondientes a la jugada oficial de Lota Familiar La Mami."
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: '30px', marginTop: '16px' }}>
              {/* Firma Vendedora */}
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '8px' }}>
                <div style={{ width: '80%', borderBottom: '1.5px solid var(--text-dim)', height: '40px' }}></div>
                <span style={{ fontSize: '0.82rem', fontWeight: '800', color: '#ffffff' }}>Firma de la Vendedora</span>
                <span style={{ fontSize: '0.74rem', color: 'var(--text-dim)' }}>{sellerName}</span>
              </div>

              {/* Firma Organizador */}
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '8px' }}>
                <div style={{ width: '80%', borderBottom: '1.5px solid var(--text-dim)', height: '40px' }}></div>
                <span style={{ fontSize: '0.82rem', fontWeight: '800', color: '#ffffff' }}>Recibido Conforme (Organización / Tesorería)</span>
                <span style={{ fontSize: '0.74rem', color: 'var(--text-dim)' }}>Lota Familiar La Mami</span>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ========================================================
          4. HISTORIAL DE VENTAS DEL VENDEDOR
         ======================================================== */}
      {activeViewTab !== 'settlement' && (
      <div style={{
        background: 'var(--bg-surface)',
        border: '1px solid var(--border-subtle)',
        borderRadius: 'var(--radius-lg)',
        padding: '20px 24px',
        boxShadow: 'var(--shadow-md)'
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px', flexWrap: 'wrap', gap: '10px' }}>
          <div>
            <h3 style={{ fontSize: '1.1rem', fontWeight: '900', margin: 0, color: 'var(--text-main)' }}>
              Mis Jugadores Registrados ({myReceipts.length})
            </h3>
            <span style={{ fontSize: '0.78rem', color: 'var(--text-muted)' }}>
              Listado de compradores cargados desde esta cuenta
            </span>
          </div>

          <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
            <button 
              type="button"
              className="btn btn-secondary btn-sm"
              onClick={() => {
                if (window.exportSalesToExcel) {
                  window.exportSalesToExcel({
                    sellerName,
                    sellerPhone,
                    receipts: myReceipts,
                    totalAmount: stats.totalAmount,
                    totalCards: stats.totalCards,
                    title: `Ventas Totales - ${sellerName}`
                  });
                }
              }}
              style={{ fontSize: '0.78rem', color: '#10b981', borderColor: 'rgba(16, 185, 129, 0.4)' }}
              title="Descargar lista completa de mis compradores en formato Excel"
            >
              <i className="fa-solid fa-file-excel"></i> Exportar Excel
            </button>
            <button 
              className="btn btn-secondary btn-sm"
              onClick={reloadDatabase}
              style={{ fontSize: '0.78rem' }}
            >
              <i className="fa-solid fa-arrows-rotate"></i> Actualizar
            </button>
          </div>
        </div>

        {myReceipts.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '30px 20px', color: 'var(--text-muted)' }}>
            <p style={{ margin: 0, fontSize: '0.88rem' }}>Aún no has registrado compradores en esta sesión.</p>
          </div>
        ) : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.86rem' }}>
              <thead>
                <tr style={{ borderBottom: '1.5px solid var(--border-subtle)', textAlign: 'left', color: 'var(--text-muted)' }}>
                  <th style={{ padding: '10px 8px' }}>Comprador</th>
                  <th style={{ padding: '10px 8px' }}>WhatsApp / Tel</th>
                  <th style={{ padding: '10px 8px' }}>Cartones</th>
                  <th style={{ padding: '10px 8px' }}>Monto</th>
                  <th style={{ padding: '10px 8px' }}>Fecha</th>
                  <th style={{ padding: '10px 8px', textAlign: 'right' }}>Acciones</th>
                </tr>
              </thead>
              <tbody>
                {myReceipts.map(r => (
                  <tr key={r.id} style={{ borderBottom: '1px solid var(--border-subtle)' }}>
                    <td style={{ padding: '12px 8px', fontWeight: '800', color: 'var(--text-main)' }}>
                      {r.player_name}
                    </td>
                    <td style={{ padding: '12px 8px', color: 'var(--accent-teal)' }}>
                      {r.player_phone}
                    </td>
                    <td style={{ padding: '12px 8px' }}>
                      <span className="brand-badge" style={{ backgroundColor: 'rgba(6, 182, 212, 0.15)', color: 'var(--accent-cyan)' }}>
                        {r.cards_count} cartones
                      </span>
                    </td>
                    <td style={{ padding: '12px 8px', fontWeight: '800', color: 'var(--accent-green)' }}>
                      ${(parseFloat(r.amount) || 0).toLocaleString('es-AR')}
                    </td>
                    <td style={{ padding: '12px 8px', fontSize: '0.76rem', color: 'var(--text-muted)' }}>
                      {r.created_at ? new Date(r.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : 'Hoy'}
                    </td>
                    <td style={{ padding: '12px 8px', textAlign: 'right' }}>
                      <div style={{ display: 'flex', gap: '6px', justifyContent: 'flex-end', flexWrap: 'wrap' }}>
                        <button
                          className="btn btn-secondary btn-sm"
                          onClick={() => handleDownloadReceiptPDF(r)}
                          disabled={downloadingReceiptId === r.id}
                          title="Descargar PDF imprimible (A4) con los cartones de este comprador"
                          style={{
                            padding: '5px 10px',
                            fontSize: '0.78rem',
                            fontWeight: '800',
                            color: 'var(--accent-gold)',
                            border: '1px solid rgba(245, 158, 11, 0.5)',
                            background: 'rgba(245, 158, 11, 0.12)',
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '5px'
                          }}
                        >
                          {downloadingReceiptId === r.id ? (
                            <><i className="fa-solid fa-spinner fa-spin"></i> Generando...</>
                          ) : (
                            <><i className="fa-solid fa-file-pdf"></i> PDF</>
                          )}
                        </button>
                        <button
                          className="btn btn-primary btn-sm"
                          onClick={() => handleOpenReceiptCards(r)}
                          title="Ver los cartones asignados a este comprador"
                          style={{ padding: '5px 10px', fontSize: '0.78rem', fontWeight: '800', background: 'linear-gradient(135deg, var(--accent-cyan), #0284c7)' }}
                        >
                          <i className="fa-solid fa-eye"></i> Cartones ({r.cards_count})
                        </button>
                        <button
                          className="btn btn-secondary btn-sm"
                          onClick={() => handleSendWhatsApp({ id: r.id, playerName: r.player_name, phone: r.player_phone, totalCards: r.cards_count })}
                          title="Reenviar WhatsApp con link del sorteo y códigos"
                          style={{ padding: '5px 8px', color: '#25D366' }}
                        >
                          <i className="fa-brands fa-whatsapp"></i> WhatsApp
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
      )}

      {/* ========================================================
          5. MODAL: VISUALIZACIÓN DE CARTONES DE VENTA ANTERIOR
         ======================================================== */}
      {viewingReceipt && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.85)',
          backdropFilter: 'blur(6px)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          zIndex: 999999,
          padding: '16px'
        }}>
          <div className="app-card" style={{
            maxWidth: '850px',
            width: '100%',
            maxHeight: '90vh',
            display: 'flex',
            flexDirection: 'column',
            overflow: 'hidden',
            border: '1.5px solid var(--accent-cyan)',
            boxShadow: '0 12px 40px rgba(0,0,0,0.6)'
          }}>
            {/* Header Modal */}
            <div style={{
              padding: '16px 20px',
              borderBottom: '1px solid var(--border-subtle)',
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              background: 'rgba(15, 23, 42, 0.9)'
            }}>
              <div>
                <h3 style={{ margin: 0, fontSize: '1.1rem', fontWeight: '900', color: '#ffffff', display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <i className="fa-solid fa-ticket" style={{ color: 'var(--accent-cyan)' }}></i>
                  Cartones de {viewingReceipt.player_name}
                </h3>
                <span style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}>
                  {viewingReceipt.cards_count} cartones registrados • ${parseFloat(viewingReceipt.amount || 0).toLocaleString('es-AR')}
                </span>
              </div>

              <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                {viewingCards.length > 0 && (
                  <button
                    className="btn btn-secondary btn-sm"
                    onClick={() => window.downloadCardsPDF && window.downloadCardsPDF(viewingCards, viewingReceipt.player_name)}
                    style={{ color: 'var(--accent-gold)', border: '1px solid rgba(245, 158, 11, 0.4)', fontWeight: '700', fontSize: '0.8rem', padding: '6px 12px' }}
                    title="Descargar todos los cartones en PDF imprimible formato A4"
                  >
                    <i className="fa-solid fa-file-pdf"></i> Descargar PDF
                  </button>
                )}

                <button
                  className="btn btn-secondary btn-sm"
                  onClick={() => setViewingReceipt(null)}
                  style={{ padding: '6px 10px' }}
                >
                  <i className="fa-solid fa-xmark"></i>
                </button>
              </div>
            </div>

            {/* Body Modal con listado de cartones */}
            <div style={{ padding: '20px', overflowY: 'auto', flex: 1, display: 'flex', flexDirection: 'column', gap: '16px' }}>
              {loadingViewingCards ? (
                <div style={{ textAlign: 'center', padding: '40px', color: 'var(--text-muted)' }}>
                  <i className="fa-solid fa-spinner fa-spin" style={{ fontSize: '2rem', marginBottom: '12px' }}></i>
                  <div>Cargando cartones desde Supabase...</div>
                </div>
              ) : viewingCards.length === 0 ? (
                <div style={{ textAlign: 'center', padding: '30px', color: 'var(--text-dim)' }}>
                  No se encontraron cartones asociados a este comprobante.
                </div>
              ) : (
                viewingCards.map((c, idx) => {
                  const isPromo = c.es_promo || (idx === 3 && viewingCards.length === 4);
                  const theme = 'card-theme-ruby';
                  return (
                    <div key={c.id || idx} className={`bingo-card-3x9-wrapper ${theme}`}>
                      <div className="card-header-bar">
                        <span className="card-title-text">
                          <i className="fa-solid fa-ticket" style={{ color: 'var(--tag-color, var(--accent-cyan))' }}></i>
                          Cartón #{idx + 1} ({viewingReceipt.player_name}) {isPromo ? '🎁 (PROMO 3+1 REGALO)' : ''}
                        </span>
                        <span className="card-serial-tag">N°: {c.card_code || c.id}</span>
                      </div>
                      <div className="teal-bingo-ticket">
                        <div className="ticket-grid-3x9">
                          {c.grid && c.grid.map((row, rIdx) => (
                            <div key={rIdx} className="ticket-row">
                              {row.map((cellNum, cIdx) => (
                                <div key={cIdx} className={`ticket-cell ${cellNum === null ? 'empty' : ''}`}>
                                  {cellNum !== null && <span>{cellNum}</span>}
                                </div>
                              ))}
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  );
                })
              )}
            </div>
          </div>
        </div>
      )}

      {/* Modal Emergente Interactivo de Selección de Cartones del Catálogo */}
      {showCatalogModal && window.CardSelectorModal && (
        <window.CardSelectorModal
          isOpen={showCatalogModal}
          onClose={() => setShowCatalogModal(false)}
          onConfirmSelection={handleCatalogConfirm}
          initialSelectedCards={selectedCatalogCards}
          availableCatalog={sellerCatalog}
        />
      )}
    </div>
  );
}

window.SellerView = SellerView;
