// New order builder — smart search with live results, quick-add, running cart
function NewOrderScreen({ vendedora, draft, onAddProduct, onUpdateQty, onRemove, onConfirm, onBack, onOpenScan }) {
  const T = window.T;
  const { Icon, ProductTile } = window;
  const [query, setQuery] = React.useState('');
  const [catalogoFilter, setCatalogoFilter] = React.useState('Todos');
  const [selected, setSelected] = React.useState(null); // product obj being added
  const [qty, setQty] = React.useState(1);

  const filtered = React.useMemo(() => {
    const q = query.trim().toLowerCase();
    return window.CATALOGO_DATA.filter(p => {
      if (catalogoFilter !== 'Todos' && p.catalogo !== catalogoFilter) return false;
      if (!q) return false;
      return p.codigo.includes(q) || p.nombre.toLowerCase().includes(q) || p.descripcion.toLowerCase().includes(q);
    }).slice(0, 8);
  }, [query, catalogoFilter]);

  // quick-add chips — most used codes
  const quickCodes = ['40821', '32207', '20618', '55031'];
  const quickItems = quickCodes.map(c => window.CATALOGO_DATA.find(p => p.codigo === c)).filter(Boolean);

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

  const handlePick = (prod) => { setSelected(prod); setQty(1); };
  const handleAddSelected = () => {
    if (!selected) return;
    onAddProduct({
      id: Date.now(), codigo: selected.codigo, catalogo: selected.catalogo,
      nombre: selected.nombre, descripcion: selected.descripcion,
      precio: selected.precio, cantidad: qty, empaque: selected.tipo, tono: selected.tono,
      imagen: selected.imagen,
    });
    setSelected(null); setQuery(''); setQty(1);
  };

  return (
    <div style={{ width: '100%', height: '100%', background: T.paper, display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <div style={{ padding: '58px 24px 14px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <button onClick={onBack} style={{
          width: 36, height: 36, borderRadius: 999, background: T.paperAlt,
          border: `1px solid ${T.hairline}`, display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer',
        }}><Icon name="chevronL" size={16} color={T.ink} /></button>
        <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.4, textTransform: 'uppercase', color: T.inkMute }}>
          Borrador · {vendedora?.zona}
        </div>
        <div style={{ width: 36 }} />
      </div>

      <div style={{ padding: '4px 24px 16px' }}>
        <div style={{ fontFamily: T.serif, fontSize: 32, lineHeight: 1, color: T.ink, letterSpacing: -0.8 }}>
          Nuevo pedido
        </div>
      </div>

      {/* Search row */}
      <div style={{ padding: '0 24px 12px' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '4px 6px 4px 14px', background: T.paperAlt,
          border: `1px solid ${T.hairline}`, borderRadius: 16,
        }}>
          <Icon name="search" size={16} color={T.inkMute} />
          <input
            value={query} onChange={(e) => setQuery(e.target.value)}
            placeholder="Código o nombre…"
            style={{
              flex: 1, border: 'none', outline: 'none', background: 'transparent',
              fontFamily: T.sans, fontSize: 14, color: T.ink, padding: '10px 0',
            }}
          />
          <button onClick={onOpenScan} style={{
            width: 36, height: 36, borderRadius: 12, background: T.paper,
            border: `1px solid ${T.hairline}`, cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><Icon name="scan" size={16} color={T.ink} /></button>
        </div>
      </div>

      {/* Catalog filter chips */}
      <div style={{ padding: '0 24px 4px', display: 'flex', gap: 6, overflowX: 'auto', scrollbarWidth: 'none' }}>
        {['Todos', ...window.CATALOGOS].map(c => (
          <button key={c} onClick={() => setCatalogoFilter(c)} style={{
            padding: '7px 12px', borderRadius: 999, whiteSpace: 'nowrap',
            border: `1px solid ${catalogoFilter === c ? T.ink : T.hairline}`,
            background: catalogoFilter === c ? T.ink : 'transparent',
            color: catalogoFilter === c ? T.paper : T.inkSoft,
            fontFamily: T.sans, fontSize: 12, fontWeight: 500, cursor: 'pointer',
          }}>{c}</button>
        ))}
      </div>

      {/* Scrollable body */}
      <div style={{ flex: 1, overflow: 'auto', paddingBottom: draft.length > 0 ? 140 : 40 }}>
        {/* Search results */}
        {query.trim() ? (
          <div style={{ padding: '16px 24px 8px' }}>
            {filtered.length === 0 ? (
              <div style={{ padding: '40px 0', textAlign: 'center' }}>
                <div style={{ fontFamily: T.serif, fontStyle: 'italic', fontSize: 18, color: T.inkSoft, marginBottom: 4 }}>
                  Sin resultados
                </div>
                <div style={{ fontFamily: T.sans, fontSize: 12, color: T.inkMute }}>
                  Revisa el código o cambia de catálogo
                </div>
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {filtered.map(p => (
                  <button key={p.codigo} onClick={() => handlePick(p)} style={{
                    width: '100%', padding: 10, borderRadius: 14,
                    background: T.paperAlt, border: `1px solid ${T.hairline}`,
                    display: 'flex', alignItems: 'center', gap: 12,
                    cursor: 'pointer', textAlign: 'left',
                  }}>
                    <ProductTile tono={p.tono} catalogo={p.catalogo} imagen={p.imagen} size={44} radius={8} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 2 }}>
                        <span style={{ fontFamily: T.mono, fontSize: 10, color: T.inkMute, letterSpacing: 0.5 }}>{p.codigo}</span>
                        <span style={{ fontFamily: T.mono, fontSize: 10, color: T.inkMute }}>·</span>
                        <span style={{ fontFamily: T.mono, fontSize: 10, color: T.accent, letterSpacing: 0.5 }}>{p.catalogo}</span>
                      </div>
                      <div style={{ fontFamily: T.serif, fontSize: 15, color: T.ink, lineHeight: 1.15, letterSpacing: -0.2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {p.nombre}
                      </div>
                    </div>
                    <div style={{ fontFamily: T.serif, fontSize: 17, color: T.ink, letterSpacing: -0.2 }}>
                      ${p.precio.toFixed(2)}
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>
        ) : (
          <>
            {/* Quick add */}
            <div style={{ padding: '16px 0 8px' }}>
              <window.SectionHead eyebrow="Atajo" title="Tus más usados" />
              <div style={{ padding: '0 24px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                {quickItems.map(p => (
                  <button key={p.codigo} onClick={() => handlePick(p)} style={{
                    padding: 12, borderRadius: 14,
                    background: T.paperAlt, border: `1px solid ${T.hairline}`,
                    display: 'flex', gap: 10, alignItems: 'flex-start',
                    cursor: 'pointer', textAlign: 'left',
                  }}>
                    <ProductTile tono={p.tono} catalogo={p.catalogo} imagen={p.imagen} size={40} radius={8} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontFamily: T.mono, fontSize: 9, color: T.inkMute, letterSpacing: 0.6 }}>{p.codigo}</div>
                      <div style={{ fontFamily: T.serif, fontSize: 13, color: T.ink, letterSpacing: -0.1, lineHeight: 1.15, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {p.nombre}
                      </div>
                      <div style={{ fontFamily: T.sans, fontSize: 11, color: T.inkSoft, marginTop: 3 }}>
                        ${p.precio.toFixed(2)}
                      </div>
                    </div>
                  </button>
                ))}
              </div>
            </div>

            {/* Current draft items */}
            {draft.length > 0 && (
              <div style={{ padding: '24px 0 0' }}>
                <window.SectionHead eyebrow="En el pedido" title={`${items} ${items === 1 ? 'ítem' : 'ítems'}`} />
                <div style={{ padding: '0 24px', display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {draft.map(p => (
                    <div key={p.id} style={{
                      padding: 12, borderRadius: 14,
                      background: T.paperAlt, border: `1px solid ${T.hairline}`,
                      display: 'flex', alignItems: 'center', gap: 12,
                    }}>
                      <ProductTile tono={p.tono} catalogo={p.catalogo} imagen={p.imagen} size={44} radius={8} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontFamily: T.mono, fontSize: 10, color: T.inkMute, letterSpacing: 0.5 }}>{p.codigo} · {p.catalogo}</div>
                        <div style={{ fontFamily: T.serif, fontSize: 15, color: T.ink, lineHeight: 1.15, letterSpacing: -0.2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                          {p.nombre}
                        </div>
                      </div>
                      {/* stepper */}
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: T.paper, borderRadius: 999, padding: 3, border: `1px solid ${T.hairline}` }}>
                        <button onClick={() => p.cantidad > 1 ? onUpdateQty(p.id, p.cantidad - 1) : onRemove(p.id)} style={{
                          width: 26, height: 26, borderRadius: 999, border: 'none', background: 'transparent', cursor: 'pointer',
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                        }}>
                          {p.cantidad > 1
                            ? <Icon name="minus" size={12} color={T.ink} />
                            : <Icon name="trash" size={12} color={T.danger} />}
                        </button>
                        <span style={{ fontFamily: T.mono, fontSize: 13, color: T.ink, minWidth: 14, textAlign: 'center' }}>{p.cantidad}</span>
                        <button onClick={() => onUpdateQty(p.id, p.cantidad + 1)} style={{
                          width: 26, height: 26, borderRadius: 999, border: 'none', background: T.ink, cursor: 'pointer',
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                        }}><Icon name="plus" size={12} color={T.paper} /></button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </>
        )}
      </div>

      {/* Floating confirm bar */}
      {draft.length > 0 && (
        <div style={{
          position: 'absolute', bottom: 0, left: 0, right: 0, padding: '12px 20px 28px',
          background: `linear-gradient(180deg, rgba(255,253,248,0) 0%, ${T.paper} 40%)`,
        }}>
          <button onClick={onConfirm} style={{
            width: '100%', padding: '14px 20px', borderRadius: 999,
            background: T.ink, color: T.paper, border: 'none', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            fontFamily: T.sans, fontSize: 14, fontWeight: 500,
          }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{
                width: 22, height: 22, borderRadius: 999, background: T.accent,
                fontFamily: T.mono, fontSize: 11, display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{items}</span>
              Revisar pedido
            </span>
            <span style={{ fontFamily: T.serif, fontSize: 18, letterSpacing: -0.2 }}>${total.toFixed(2)}</span>
          </button>
        </div>
      )}

      {/* Product picker sheet (after selecting from search) */}
      {selected && (
        <div style={{
          position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.3)',
          display: 'flex', alignItems: 'flex-end', zIndex: 20,
        }} onClick={() => setSelected(null)}>
          <div onClick={(e) => e.stopPropagation()} style={{
            width: '100%', background: T.paper, borderRadius: '28px 28px 0 0',
            padding: '12px 24px 32px',
          }}>
            <div style={{ width: 40, height: 4, background: T.hairlineStrong, borderRadius: 999, margin: '4px auto 18px' }} />
            <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start', marginBottom: 20 }}>
              <ProductTile tono={selected.tono} catalogo={selected.catalogo} imagen={selected.imagen} size={72} radius={12} />
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: T.mono, fontSize: 10, color: T.inkMute, letterSpacing: 0.6, marginBottom: 3 }}>
                  {selected.codigo} · {selected.catalogo} · pág. {selected.pagina}
                </div>
                <div style={{ fontFamily: T.serif, fontSize: 20, color: T.ink, lineHeight: 1.1, letterSpacing: -0.3 }}>
                  {selected.nombre}
                </div>
                <div style={{ fontFamily: T.sans, fontSize: 13, color: T.inkSoft, marginTop: 4 }}>
                  {selected.descripcion}
                </div>
              </div>
            </div>

            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
              <div>
                <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.4, textTransform: 'uppercase', color: T.inkMute }}>Precio unitario</div>
                <div style={{ fontFamily: T.serif, fontSize: 28, color: T.ink, letterSpacing: -0.5 }}>${selected.precio.toFixed(2)}</div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, background: T.paperAlt, borderRadius: 999, padding: 6, border: `1px solid ${T.hairline}` }}>
                <button onClick={() => setQty(Math.max(1, qty - 1))} style={{
                  width: 36, height: 36, borderRadius: 999, border: 'none', background: T.paper, cursor: 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}><Icon name="minus" size={14} color={T.ink} /></button>
                <span style={{ fontFamily: T.serif, fontSize: 20, color: T.ink, minWidth: 24, textAlign: 'center' }}>{qty}</span>
                <button onClick={() => setQty(qty + 1)} style={{
                  width: 36, height: 36, borderRadius: 999, border: 'none', background: T.ink, cursor: 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}><Icon name="plus" size={14} color={T.paper} /></button>
              </div>
            </div>

            <window.PrimaryBtn onClick={handleAddSelected}>
              Agregar al pedido · ${(selected.precio * qty).toFixed(2)}
            </window.PrimaryBtn>
          </div>
        </div>
      )}
    </div>
  );
}

window.NewOrderScreen = NewOrderScreen;
