// Catálogo visual — hojear el PDF real del catálogo L'Bel C07, con chips de productos
// de la página para agregar al pedido directo desde la imagen.
function CatalogoViewerScreen({ draft, onAddProduct, onClose, onReviewOrder }) {
  const T = window.T;
  const { Icon, ProductTile } = window;

  const TOTAL = 21;
  const [idx, setIdx] = React.useState(() => {
    try { return parseInt(localStorage.getItem('inova-cat-page') || '1'); } catch { return 1; }
  });
  const [added, setAdded] = React.useState({});
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    try { localStorage.setItem('inova-cat-page', String(idx)); } catch {}
    // scroll to top when page changes
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  }, [idx]);

  // Products visible on THIS spread
  const pageProducts = React.useMemo(() => {
    const map = window.LBEL_C07_PAGE_MAP || {};
    const codes = Object.keys(map).filter(c => map[c] === idx);
    return codes
      .map(c => window.CATALOGO_DATA.find(p => p.codigo === c))
      .filter(Boolean);
  }, [idx]);

  const draftCount = draft.reduce((s, p) => s + p.cantidad, 0);
  const draftTotal = draft.reduce((s, p) => s + p.precio * p.cantidad, 0);

  const handlePedir = (p) => {
    onAddProduct({
      id: Date.now() + Math.random(), codigo: p.codigo, catalogo: p.catalogo,
      nombre: p.nombre, descripcion: p.descripcion,
      precio: p.precio, cantidad: 1, empaque: p.tipo, tono: p.tono,
      imagen: p.imagen,
    });
    setAdded(prev => ({ ...prev, [p.codigo]: (prev[p.codigo] || 0) + 1 }));
  };

  const go = (delta) => setIdx(i => Math.max(1, Math.min(TOTAL, i + delta)));

  // Soft paper background — less morgue, more boutique
  const bg = '#1a1618';

  return (
    <div style={{
      width: '100%', height: '100%', background: bg,
      display: 'flex', flexDirection: 'column',
      position: 'relative', overflow: 'hidden',
    }}>
      {/* Top bar */}
      <div style={{
        padding: '58px 20px 12px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        background: `linear-gradient(180deg, ${bg} 0%, ${bg}ee 70%, transparent 100%)`,
        position: 'absolute', top: 0, left: 0, right: 0, zIndex: 5,
      }}>
        <button onClick={onClose} style={{
          width: 38, height: 38, borderRadius: 999,
          background: 'rgba(255,255,255,0.12)', backdropFilter: 'blur(20px)',
          border: '1px solid rgba(255,255,255,0.18)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
        }}><Icon name="chevronL" size={16} color="#fff" /></button>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontFamily: T.mono, fontSize: 9, letterSpacing: 1.5, textTransform: 'uppercase', color: 'rgba(255,255,255,0.5)' }}>
            L'Bel · C07 / 2026
          </div>
          <div style={{ fontFamily: T.serif, fontSize: 15, color: '#fff', marginTop: 2, letterSpacing: -0.1 }}>
            Página {idx} <span style={{ color: 'rgba(255,255,255,0.4)' }}>/ {TOTAL}</span>
          </div>
        </div>
        <div style={{ width: 38 }} />
      </div>

      {/* Scrollable content: image then chips, stacked naturally */}
      <div ref={scrollRef} style={{
        flex: 1, overflow: 'auto',
        paddingTop: 96, paddingBottom: draftCount > 0 ? 100 : 24,
      }}>
        {/* Full-width spread */}
        <div style={{ width: '100%', background: '#fff', position: 'relative' }}>
          <img
            src={`catalogos/lbel-c07/page-${String(idx).padStart(2, '0')}.jpg`}
            alt={`Página ${idx}`}
            style={{ width: '100%', display: 'block' }}
          />
          {/* Arrows overlaid on image */}
          {idx > 1 && (
            <button onClick={() => go(-1)} style={imgArrow('left')}>
              <Icon name="chevronL" size={18} color="#fff" />
            </button>
          )}
          {idx < TOTAL && (
            <button onClick={() => go(1)} style={imgArrow('right')}>
              <Icon name="chevronR" size={18} color="#fff" />
            </button>
          )}
        </div>

        {/* Products section — directly below, visually linked to page */}
        {pageProducts.length > 0 ? (
          <div style={{ padding: '18px 20px 8px' }}>
            <div style={{
              display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
              marginBottom: 12,
            }}>
              <div>
                <div style={{ fontFamily: T.mono, fontSize: 9, letterSpacing: 1.4, textTransform: 'uppercase', color: 'rgba(255,255,255,0.45)' }}>
                  En esta página
                </div>
                <div style={{ fontFamily: T.serif, fontSize: 20, color: '#fff', letterSpacing: -0.3, marginTop: 2 }}>
                  {pageProducts.length} producto{pageProducts.length === 1 ? '' : 's'}
                </div>
              </div>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {pageProducts.map(p => {
                const qty = added[p.codigo] || 0;
                const priceStr = '$' + p.precio.toFixed(p.precio % 1 === 0 ? 0 : 1);
                return (
                  <div key={p.codigo} style={{
                    display: 'flex', alignItems: 'center', gap: 12,
                    padding: 10, borderRadius: 14,
                    background: 'rgba(255,255,255,0.06)',
                    border: '1px solid rgba(255,255,255,0.08)',
                  }}>
                    <ProductTile tono={p.tono} catalogo={p.catalogo} imagen={p.imagen} size={48} radius={10} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <span style={{ fontFamily: T.mono, fontSize: 9, color: 'rgba(255,255,255,0.5)', letterSpacing: 0.5 }}>
                          {p.codigo}
                        </span>
                        {!p.precioReal && (
                          <span style={{ fontFamily: T.mono, fontSize: 8, color: 'rgba(255,255,255,0.35)', textTransform: 'uppercase', letterSpacing: 1 }}>
                            est.
                          </span>
                        )}
                      </div>
                      <div style={{
                        fontFamily: T.serif, fontSize: 15, color: '#fff',
                        letterSpacing: -0.2, lineHeight: 1.15, marginTop: 1,
                        overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                      }}>
                        {p.nombre}
                      </div>
                      <div style={{ fontFamily: T.sans, fontSize: 12, color: 'rgba(255,255,255,0.6)', marginTop: 2 }}>
                        {priceStr}
                      </div>
                    </div>
                    <button onClick={() => handlePedir(p)} style={{
                      padding: '10px 14px', borderRadius: 999,
                      background: qty > 0 ? T.accent : '#fff',
                      color: qty > 0 ? '#fff' : T.ink,
                      border: 'none', cursor: 'pointer', flexShrink: 0,
                      fontFamily: T.sans, fontSize: 12, fontWeight: 500,
                      display: 'flex', alignItems: 'center', gap: 5,
                      minWidth: 72, justifyContent: 'center',
                    }}>
                      {qty > 0 ? <><span style={{ fontFamily: T.mono }}>×{qty}</span><span>+</span></> : <>+ Pedir</>}
                    </button>
                  </div>
                );
              })}
            </div>

            {/* Flip to next page affordance */}
            {idx < TOTAL && (
              <button onClick={() => go(1)} style={{
                width: '100%', marginTop: 18, padding: '14px',
                borderRadius: 14, background: 'transparent',
                border: '1px dashed rgba(255,255,255,0.18)',
                color: 'rgba(255,255,255,0.7)', cursor: 'pointer',
                fontFamily: T.serif, fontStyle: 'italic', fontSize: 14,
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                letterSpacing: -0.2,
              }}>
                Pasar a página {idx + 1}
                <Icon name="arrowR" size={14} color="rgba(255,255,255,0.7)" />
              </button>
            )}
          </div>
        ) : (
          <div style={{
            textAlign: 'center', color: 'rgba(255,255,255,0.5)',
            fontFamily: T.serif, fontStyle: 'italic', fontSize: 14,
            padding: '24px 20px 8px',
          }}>
            Portada — sin productos para pedir en esta página.
            {idx < TOTAL && (
              <div style={{ marginTop: 12 }}>
                <button onClick={() => go(1)} style={{
                  padding: '10px 18px', borderRadius: 999,
                  background: '#fff', color: T.ink, border: 'none', cursor: 'pointer',
                  fontFamily: T.sans, fontSize: 12, fontWeight: 500,
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                }}>
                  Empezar a hojear <Icon name="arrowR" size={12} color={T.ink} />
                </button>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Floating cart bar */}
      {draftCount > 0 && (
        <div style={{
          position: 'absolute', left: 16, right: 16, bottom: 16,
          padding: '10px 12px 10px 14px', borderRadius: 999,
          background: T.ink, color: T.paper,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          boxShadow: '0 14px 30px rgba(0,0,0,0.5)', zIndex: 6,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{
              width: 28, height: 28, borderRadius: 999, background: T.accent,
              fontFamily: T.mono, fontSize: 12, display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>{draftCount}</span>
            <div>
              <div style={{ fontFamily: T.mono, fontSize: 9, letterSpacing: 1, color: 'rgba(255,253,248,0.55)', textTransform: 'uppercase' }}>
                En el pedido
              </div>
              <div style={{ fontFamily: T.serif, fontSize: 15, letterSpacing: -0.2, marginTop: 1 }}>
                ${draftTotal.toFixed(2)}
              </div>
            </div>
          </div>
          <button onClick={onReviewOrder} style={{
            padding: '10px 16px', borderRadius: 999, background: T.paper,
            color: T.ink, border: 'none', cursor: 'pointer',
            fontFamily: T.sans, fontSize: 13, fontWeight: 500,
            display: 'flex', alignItems: 'center', gap: 4,
          }}>
            Revisar <Icon name="chevronR" size={12} color={T.ink} />
          </button>
        </div>
      )}
    </div>
  );
}

function imgArrow(side) {
  return {
    position: 'absolute', top: '50%', transform: 'translateY(-50%)',
    [side]: 8, width: 40, height: 40, borderRadius: 999,
    background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(12px)',
    border: '1px solid rgba(255,255,255,0.25)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    cursor: 'pointer', zIndex: 2,
  };
}

window.CatalogoViewerScreen = CatalogoViewerScreen;
