// Order list / history
function OrdersListScreen({ pedidos, onOpen, onBack, onNew }) {
  const T = window.T;
  const { Icon, ProductTile, StatusPill } = window;
  const [filter, setFilter] = React.useState('Todos');

  const filtered = pedidos.filter(p => {
    if (filter === 'Todos') return true;
    if (filter === 'Pendientes') return p.estado === 'pendiente';
    if (filter === 'Completados') return p.estado === 'completado';
    return true;
  });

  return (
    <div style={{ width: '100%', height: '100%', background: T.paper, display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '58px 24px 4px', 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 }}>
          {pedidos.length} pedidos
        </div>
        <button onClick={onNew} style={{
          width: 36, height: 36, borderRadius: 999, background: T.ink,
          border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
        }}><Icon name="plus" size={16} color={T.paper} /></button>
      </div>

      <div style={{ padding: '14px 24px 18px' }}>
        <div style={{ fontFamily: T.serif, fontSize: 34, color: T.ink, letterSpacing: -0.8, lineHeight: 1 }}>
          Mis pedidos
        </div>
      </div>

      {/* filters */}
      <div style={{ padding: '0 24px 12px', display: 'flex', gap: 6 }}>
        {['Todos', 'Pendientes', 'Completados'].map(f => (
          <button key={f} onClick={() => setFilter(f)} style={{
            padding: '7px 14px', borderRadius: 999,
            border: `1px solid ${filter === f ? T.ink : T.hairline}`,
            background: filter === f ? T.ink : 'transparent',
            color: filter === f ? T.paper : T.inkSoft,
            fontFamily: T.sans, fontSize: 12, fontWeight: 500, cursor: 'pointer',
          }}>{f}</button>
        ))}
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '4px 24px 40px' }}>
        {filtered.length === 0 ? (
          <div style={{ padding: '60px 20px', textAlign: 'center' }}>
            <div style={{ fontFamily: T.serif, fontStyle: 'italic', fontSize: 22, color: T.inkSoft, marginBottom: 8 }}>
              Aún nada por aquí
            </div>
            <div style={{ fontFamily: T.sans, fontSize: 13, color: T.inkMute }}>
              Cuando armes tu primer pedido aparecerá en esta lista.
            </div>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {filtered.map(p => {
              const total = p.productos.reduce((s, x) => s + x.precio * x.cantidad, 0);
              const items = p.productos.reduce((s, x) => s + x.cantidad, 0);
              const catalogos = [...new Set(p.productos.map(x => x.catalogo))];
              return (
                <button key={p.id} onClick={() => onOpen(p)} style={{
                  width: '100%', padding: 16, borderRadius: 20,
                  background: T.paperAlt, border: `1px solid ${T.hairline}`,
                  cursor: 'pointer', textAlign: 'left',
                }}>
                  <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 12 }}>
                    <div>
                      <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1, color: T.inkMute, marginBottom: 3 }}>
                        {p.codigo}
                      </div>
                      <div style={{ fontFamily: T.serif, fontSize: 22, color: T.ink, letterSpacing: -0.4, lineHeight: 1 }}>
                        ${total.toFixed(2)}
                      </div>
                    </div>
                    <StatusPill estado={p.estado} enviado={p.enviado} size="sm" />
                  </div>

                  <div style={{ display: 'flex', gap: 6, marginBottom: 12, flexWrap: 'wrap' }}>
                    {p.productos.slice(0, 4).map((pr, i) => (
                      <ProductTile key={i} tono={pr.tono} catalogo={pr.catalogo} imagen={pr.imagen} size={36} radius={6} />
                    ))}
                    {p.productos.length > 4 && (
                      <div style={{
                        width: 36, height: 36, borderRadius: 6, background: T.paper,
                        border: `1px solid ${T.hairline}`,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        fontFamily: T.mono, fontSize: 11, color: T.inkSoft,
                      }}>+{p.productos.length - 4}</div>
                    )}
                  </div>

                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingTop: 10, borderTop: `1px solid ${T.hairline}` }}>
                    <div style={{ fontFamily: T.sans, fontSize: 12, color: T.inkSoft }}>
                      {items} ítems · {catalogos.slice(0, 2).join(', ')}{catalogos.length > 2 ? '…' : ''}
                    </div>
                    <div style={{ fontFamily: T.mono, fontSize: 10, color: T.inkMute, letterSpacing: 0.5 }}>
                      {p.fechaCreacion.toLocaleDateString('es', { day: '2-digit', month: 'short' })}
                    </div>
                  </div>
                </button>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

window.OrdersListScreen = OrdersListScreen;
