// js/components/pages/EntradaDecantes.jsx
// [v224.216 ENTRADA-DECANTES 20260728] Tela dedicada do Munir pra lançar envase de decante.
// Terceira perna do conserto de 28/07 (fix_guard_pws_on_conflict + guard_decante_so_no_deposito_alfonso):
// o estoquista NÃO escolhe depósito, então o erro do "SO CANDID no Senador" não nasce.
//
// Backend JÁ NO AR (migration entrada_decantes_munir_backend_v1, prod xjjtwpnhlstnfvqjzojk):
//   - VIEW public.znx_decants_for_entry (id, name, saldo_alfonso) · security_invoker · só authenticated
//   - RPC  public.register_decant_entry_v1(payload jsonb) · SECURITY DEFINER · tudo-ou-nada
// Depósito Alfonso e unit_cost são decididos pelo SERVIDOR — esta tela nunca manda os dois.
//
// PRIVACIDADE (regra da tela): zero avg_cost, zero sale_price, zero margem, zero total em R$.
// Por isso lemos SÓ a view — nunca store['products'], que carrega custo no cache global e
// apareceria no DevTools do Munir.
//
// Roles: admin, estoquista. O gate real é a RPC (role lido de app_users no servidor);
// znxGuard aqui é defesa em profundidade, não a trava.
//
// [v224.217] +bloco "Últimos lançamentos" no rodapé: le znx_decant_entry_batches (7d, 20 lotes).
// So leitura — sem desfazer/editar/apagar. Se a query falhar, o bloco some e a tela de LANCAR
// continua funcionando; ele nunca pode ser motivo de nao dar entrada.
//
// Deps runtime: sb, toast, znxGuard, Icon (globals)
(function() {
  'use strict';
  const {useState, useEffect, useRef, useCallback} = React;

  // Guard de clique síncrono (module-scope, igual Clientes.jsx/Orcamentos.jsx).
  // useState não serve: setState é assíncrono e 2 cliques no mesmo tick passariam os dois.
  let _inFlightDecantEntry = false;

  const MAX_ITENS = 50;   // espelha invalid_payload da RPC
  const MAX_QTY   = 500;  // espelha invalid_item da RPC
  const MAX_RESULTS = 10;

  // LIKE tem curinga próprio: '%' e '_' digitados na busca precisam virar literais,
  // senão "5_ML" casa com qualquer caractere e o Munir vê resultado que não pediu.
  function escapeLike(s) {
    return String(s || '').replace(/[\\%_]/g, function(ch) { return '\\' + ch; });
  }

  // Mockup usa menos-real (U+2212) nos saldos negativos — '-' fica fino demais no meio da tabela.
  function fmtSaldo(n) {
    const v = Number(n) || 0;
    return v < 0 ? '−' + Math.abs(v) : String(v);
  }

  // [v224.217] "28/07 18:05" — helper local de propósito: este arquivo não depende de
  // nenhum lib externo, e puxar fmtShortDate do freight-helpers criaria dependência de
  // ordem de <script> pra um bloco que é só informativo.
  function fmtQuando(ts) {
    if (!ts) return '—';
    try {
      const d = new Date(ts);
      if (isNaN(d.getTime())) return '—';
      const p = n => String(n).padStart(2, '0');
      return p(d.getDate()) + '/' + p(d.getMonth() + 1) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes());
    } catch (_) { return '—'; }
  }

  function plural(n, sing, plur) { return n + ' ' + (Math.abs(n) === 1 ? sing : plur); }

  function EntradaDecantes({ user }) {
    const [term, setTerm]         = useState('');
    const [results, setResults]   = useState([]);
    const [searching, setSearching] = useState(false);
    const [highlight, setHighlight] = useState(0);
    const [qty, setQty]           = useState(6);
    const [selected, setSelected] = useState(null); // {id,name,saldo_alfonso}
    const [lote, setLote]         = useState([]);   // [{product_id,name,saldo,qty}]
    const [submitting, setSubmitting] = useState(false);

    // [v224.217] Últimos lançamentos. `lotesOk=false` faz o bloco inteiro sumir:
    // é informativo, e não pode derrubar a tela de LANÇAR se a query falhar.
    const [lotes, setLotes]     = useState([]);
    const [lotesOk, setLotesOk] = useState(true);

    const searchRef = useRef(null);
    const seqRef    = useRef(0);     // descarta resposta de busca fora de ordem
    // Chave de idempotência POR LOTE, não por clique: se a rede cair depois do servidor
    // já ter gravado, o retry manda a MESMA chave e a RPC devolve replay em vez de somar
    // as unidades de novo. Só rotaciona depois de um sucesso confirmado (ou no Limpar).
    const idemRef   = useRef(null);

    const canUse = user && (user.role === 'admin' || user.role === 'estoquista');

    useEffect(() => { if (searchRef.current) searchRef.current.focus(); }, []);

    // ── Últimos lançamentos (7 dias, 20 lotes) ───────────────────────────────
    // Lê znx_decant_entry_batches direto: a RLS já libera só admin/estoquista e a tabela
    // não guarda custo nenhum. Nunca faz throw pra fora — no pior caso o bloco some.
    const loadLotes = useCallback(async () => {
      if (typeof sb === 'undefined' || !sb.from) { setLotesOk(false); return; }
      try {
        const desde = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString();
        const { data, error } = await sb
          .from('znx_decant_entry_batches')
          .select('idempotency_key,user_name,itens,unidades,created_at,detalhe')
          .gte('created_at', desde)
          .order('created_at', { ascending: false })
          .limit(20);
        if (error) throw error;
        setLotes(Array.isArray(data) ? data : []);
        setLotesOk(true);
      } catch (e) {
        console.error('[EntradaDecantes] últimos lançamentos:', e);
        setLotesOk(false);
        if (typeof Sentry !== 'undefined') Sentry.captureException(e, { extra: { context: 'EntradaDecantes.loadLotes' } });
      }
    }, []);

    useEffect(() => { if (canUse) loadLotes(); }, [canUse, loadLotes]);

    // ── Busca (server-side ILIKE, debounce 250ms) ────────────────────────────
    const runSearch = useCallback(async (raw) => {
      const q = String(raw || '').trim();
      if (q.length < 2) { setResults([]); setSearching(false); return; }
      if (typeof sb === 'undefined' || !sb.from) return;
      const mySeq = ++seqRef.current;
      setSearching(true);
      try {
        const { data, error } = await sb
          .from('znx_decants_for_entry')
          .select('id,name,saldo_alfonso')
          .ilike('name', '%' + escapeLike(q) + '%')
          .order('name')
          .limit(MAX_RESULTS);
        if (mySeq !== seqRef.current) return; // chegou tarde — já tem busca mais nova
        if (error) throw error;
        setResults(data || []);
        setHighlight(0);
      } catch (e) {
        if (mySeq !== seqRef.current) return;
        console.error('[EntradaDecantes] busca:', e);
        setResults([]);
        toast('Não consegui buscar os decantes: ' + (e && e.message ? e.message : e), 'error');
        if (typeof Sentry !== 'undefined') Sentry.captureException(e, { extra: { context: 'EntradaDecantes.runSearch' } });
      } finally {
        if (mySeq === seqRef.current) setSearching(false);
      }
    }, []);

    useEffect(() => {
      const t = setTimeout(() => { runSearch(term); }, 250);
      return () => clearTimeout(t);
    }, [term, runSearch]);

    // ── Lote ─────────────────────────────────────────────────────────────────
    function addItem(prod, n) {
      const p = prod || selected;
      if (!p) { toast('Escolha um decante na busca primeiro.', 'warning'); return; }
      const q = Math.trunc(Number(n != null ? n : qty) || 0);
      if (q < 1 || q > MAX_QTY) { toast('Quantidade deve ser de 1 a ' + MAX_QTY + '.', 'warning'); return; }

      setLote(prev => {
        const idx = prev.findIndex(it => it.product_id === p.id);
        // Mesmo decante 2× vira uma linha só: manda 1 item na RPC (contagem de "itens"
        // não infla) e o Munir vê um "Fica com" que fecha com a realidade.
        if (idx >= 0) {
          const merged = Math.min(prev[idx].qty + q, MAX_QTY);
          if (merged === prev[idx].qty) { toast('Já está no máximo de ' + MAX_QTY + ' unidades pra esse decante.', 'warning'); return prev; }
          return prev.map((it, i) => i === idx ? Object.assign({}, it, { qty: merged }) : it);
        }
        if (prev.length >= MAX_ITENS) { toast('Máximo de ' + MAX_ITENS + ' decantes por lançamento.', 'warning'); return prev; }
        return prev.concat([{ product_id: p.id, name: p.name, saldo: Number(p.saldo_alfonso) || 0, qty: q }]);
      });

      setTerm(''); setResults([]); setSelected(null); setQty(6);
      if (searchRef.current) searchRef.current.focus();
    }

    function removeItem(pid) { setLote(prev => prev.filter(it => it.product_id !== pid)); }

    function limpar() {
      setLote([]); setTerm(''); setResults([]); setSelected(null); setQty(6);
      idemRef.current = null; // lote novo, chave nova
      if (searchRef.current) searchRef.current.focus();
    }

    // ── Confirmar ────────────────────────────────────────────────────────────
    async function confirmar() {
      if (_inFlightDecantEntry) { toast('⏳ Processando...'); return; }
      if (!lote.length) { toast('Adicione pelo menos um decante.', 'warning'); return; }

      // A trava tem que fechar ANTES do primeiro await. Com o znxGuard acima dela, dois
      // cliques no mesmo tick passavam os dois pelo `if` antes de qualquer um marcar a
      // flag — e saíam 2 chamadas à RPC (a idempotência segurava o estoque, mas o
      // lançamento ia duas vezes na rede). Provado no smoke de clique duplo em 28/07.
      _inFlightDecantEntry = true;
      setSubmitting(true);

      try {
        if (!await znxGuard(['admin', 'estoquista'])) return;
        if (!idemRef.current) {
          idemRef.current = (window.ZNX && window.ZNX.lib && window.ZNX.lib.genIdUUID)
            ? window.ZNX.lib.genIdUUID()
            : (window.crypto && window.crypto.randomUUID ? window.crypto.randomUUID() : null);
        }

        const { data, error } = await sb.rpc('register_decant_entry_v1', {
          payload: {
            items: lote.map(it => ({ product_id: it.product_id, qty: it.qty })),
            idempotency_key: idemRef.current
          }
        });
        if (error) throw error;

        // replay:true = clique duplo / reenvio. Nada de novo entrou, mas o lançamento
        // ESTÁ gravado — então o Munir vê o mesmo toast verde, não um erro.
        const det = (data && data.detalhe) || [];
        const linhas = det.map(d => d.name + ' ' + fmtSaldo(d.antes) + ' → ' + fmtSaldo(d.depois));
        toast(
          '✓ Entrada registrada — ' + (data && data.itens) + ' decantes, ' +
          (data && data.unidades) + ' unidades no depósito Alfonso.' +
          (linhas.length ? '\n' + linhas.join('\n') : ''),
          'success'
        );

        idemRef.current = null; // sucesso confirmado → próximo lote começa com chave nova
        // Limpa tudo e devolve o foco pra busca — o Munir já emenda o próximo envase.
        // Os saldos não precisam de refresh aqui: a lista de resultados sai da tela junto,
        // e a próxima busca lê a view de novo (já com o saldo pós-lançamento).
        setLote([]); setTerm(''); setResults([]); setSelected(null); setQty(6);
        loadLotes(); // [v224.217] o lote recém-gravado sobe pro topo de "Últimos lançamentos"
        if (searchRef.current) searchRef.current.focus();
      } catch (e) {
        // A RPC RAISE EXCEPTION já traz o NOME do produto na mensagem
        // (nao_e_decante / sem_custo_cadastrado / invalid_item). Mostrar INTEIRA, sem cortar.
        const msg = (e && e.message) ? e.message : String(e);
        console.error('[EntradaDecantes] confirmar:', e);
        toast(msg, 'error');
        if (typeof Sentry !== 'undefined') Sentry.captureException(e, { extra: { context: 'EntradaDecantes.confirmar', itens: lote.length } });
      } finally {
        _inFlightDecantEntry = false;
        setSubmitting(false);
      }
    }

    // ── Teclado na busca ─────────────────────────────────────────────────────
    function onSearchKey(e) {
      if (!results.length) return;
      if (e.key === 'ArrowDown') { e.preventDefault(); setHighlight(h => Math.min(h + 1, results.length - 1)); }
      else if (e.key === 'ArrowUp') { e.preventDefault(); setHighlight(h => Math.max(h - 1, 0)); }
      else if (e.key === 'Enter') { e.preventDefault(); const p = results[highlight]; if (p) addItem(p, qty); }
      else if (e.key === 'Escape') { setResults([]); }
    }

    if (!canUse) {
      return (
        <div className="page-content">
          <div className="card" style={{ borderLeft: '4px solid #DC2626' }}>
            <div style={{ fontWeight: 700, color: '#DC2626', marginBottom: 4 }}>Acesso restrito</div>
            <div style={{ color: '#6B7280' }}>Só admin e estoquista lançam entrada de decante.</div>
          </div>
        </div>
      );
    }

    const totalUnidades = lote.reduce((s, it) => s + it.qty, 0);

    return (
      <div className="page-content">
        <div style={{ marginBottom: 18 }}>
          <h2 style={{ fontSize: 22, fontWeight: 800, color: '#111827' }}>Entrada de Decantes</h2>
          <div style={{ color: '#6B7280', marginTop: 2 }}>Escolha o decante, informe quantas unidades foram envasadas e confirme.</div>
        </div>

        {/* Depósito FIXO — não existe seletor de depósito em lugar nenhum desta tela. */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px', marginBottom: 16,
          background: '#EFF6FF', border: '1px solid #BFDBFE', borderLeft: '4px solid #2563EB', borderRadius: 10
        }}>
          <span style={{ fontSize: 18 }} aria-hidden="true">📦</span>
          <span style={{ color: '#1E3A8A' }}>
            Depósito de destino: <strong>ALFONSO</strong> — todo decante entra aqui.
          </span>
          <span className="badge badge-blue" style={{ marginLeft: 'auto', background: '#2563EB', color: '#fff' }}>🔒 FIXO</span>
        </div>

        {/* Busca + stepper + adicionar */}
        <div style={{ display: 'flex', gap: 10, alignItems: 'stretch', flexWrap: 'wrap' }}>
          <div style={{ position: 'relative', flex: '1 1 320px', minWidth: 240 }}>
            <input
              ref={searchRef}
              value={term}
              onChange={e => setTerm(e.target.value)}
              onKeyDown={onSearchKey}
              placeholder="🔍 Buscar decante pelo nome..."
              style={{ fontSize: 15, padding: '11px 14px' }}
            />
          </div>
          <div style={{ display: 'flex', alignItems: 'center', border: '1px solid #E4E7EC', borderRadius: 6, background: '#fff', overflow: 'hidden' }}>
            <button type="button" onClick={() => setQty(q => Math.max(1, (Number(q) || 1) - 1))}
              style={{ background: '#F9FAFB', border: 'none', padding: '10px 16px', fontSize: 18, color: '#374151' }} aria-label="Diminuir">−</button>
            <input
              type="number" min="1" max={MAX_QTY} value={qty}
              onChange={e => {
                const v = e.target.value;
                if (v === '') { setQty(''); return; }
                setQty(Math.min(MAX_QTY, Math.max(1, Math.trunc(Number(v) || 1))));
              }}
              onBlur={() => { if (qty === '' || Number(qty) < 1) setQty(1); }}
              style={{ width: 78, textAlign: 'center', border: 'none', borderRadius: 0, fontSize: 16, fontWeight: 700 }}
            />
            <button type="button" onClick={() => setQty(q => Math.min(MAX_QTY, (Number(q) || 0) + 1))}
              style={{ background: '#F9FAFB', border: 'none', padding: '10px 16px', fontSize: 18, color: '#374151' }} aria-label="Aumentar">+</button>
          </div>
          <button className="btn-gold" onClick={() => addItem(null, qty)} disabled={!selected}
            style={{ padding: '10px 22px', fontSize: 14 }}>+ Adicionar</button>
        </div>

        {/* Resultados — só decantes, a view não devolve outra coisa */}
        {term.trim().length >= 2 && (
          <div className="card" style={{ marginTop: 10, padding: 0, overflow: 'hidden' }}>
            <div style={{ padding: '9px 14px', background: '#F9FAFB', borderBottom: '1px solid #F3F4F6', fontSize: 11, fontWeight: 700, color: '#6B7280', letterSpacing: '.06em' }}>
              SÓ DECANTES · {searching ? 'buscando...' : results.length + (results.length === MAX_RESULTS ? '+' : '') + ' resultado' + (results.length === 1 ? '' : 's') + ' para "' + term.trim() + '"'}
            </div>
            {!searching && results.length === 0 && (
              <div style={{ padding: '16px 14px', color: '#9CA3AF' }}>Nenhum decante com esse nome.</div>
            )}
            {results.map((p, i) => (
              <div key={p.id}
                onMouseEnter={() => setHighlight(i)}
                onClick={() => { setSelected(p); setHighlight(i); }}
                onDoubleClick={() => addItem(p, qty)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 12, padding: '11px 14px', cursor: 'pointer',
                  borderBottom: i < results.length - 1 ? '1px solid #F3F4F6' : 'none',
                  background: (selected && selected.id === p.id) ? '#DBEAFE' : (highlight === i ? '#EFF6FF' : '#fff')
                }}>
                <span style={{ background: '#1F2937', color: '#fff', fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 4, letterSpacing: '.05em' }}>DECANTE</span>
                <span style={{ fontWeight: 600, color: '#111827' }}>{p.name}</span>
                <span style={{ marginLeft: 'auto', fontSize: 12, color: '#6B7280', whiteSpace: 'nowrap' }}>
                  saldo hoje: <strong style={{ color: Number(p.saldo_alfonso) < 0 ? '#DC2626' : '#374151' }}>{fmtSaldo(p.saldo_alfonso)}</strong>
                </span>
              </div>
            ))}
          </div>
        )}

        {/* Lote — NENHUMA coluna de valor, NENHUM total em R$ */}
        <div className="card" style={{ marginTop: 16, padding: 0, overflow: 'hidden' }}>
          <table>
            <thead>
              <tr>
                <th>Decante</th>
                <th style={{ textAlign: 'right' }}>Saldo hoje</th>
                <th style={{ textAlign: 'right' }}>Entrando</th>
                <th style={{ textAlign: 'right' }}>Fica com</th>
                <th style={{ width: 44 }}></th>
              </tr>
            </thead>
            <tbody>
              {lote.length === 0 && (
                <tr><td colSpan="5" style={{ color: '#9CA3AF', padding: '22px 12px', textAlign: 'center' }}>
                  Nenhum decante no lote ainda — busque pelo nome acima.
                </td></tr>
              )}
              {lote.map(it => (
                <tr key={it.product_id}>
                  <td style={{ fontWeight: 500 }}>{it.name}</td>
                  <td style={{ textAlign: 'right', color: it.saldo < 0 ? '#DC2626' : '#9CA3AF' }}>{fmtSaldo(it.saldo)}</td>
                  <td style={{ textAlign: 'right', color: '#16A34A', fontWeight: 700 }}>+{it.qty}</td>
                  <td style={{ textAlign: 'right', fontWeight: 700 }}>→ {fmtSaldo(it.saldo + it.qty)}</td>
                  <td style={{ textAlign: 'right' }}>
                    <button className="btn-danger btn-sm" onClick={() => removeItem(it.product_id)} title="Remover" aria-label={'Remover ' + it.name}>🗑</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div style={{
          marginTop: 12, padding: '11px 14px', border: '1px dashed #D1D5DB', borderRadius: 8,
          background: '#F9FAFB', color: '#6B7280', fontSize: 13
        }}>
          🔒 Esta tela não mostra preço de custo, preço de venda nem valor total. Só nome e quantidade.
        </div>

        <div style={{ marginTop: 16, display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
          <div style={{ color: '#6B7280' }}>
            {lote.length} decante{lote.length === 1 ? '' : 's'} · <strong style={{ color: '#111827', fontSize: 16 }}>{totalUnidades}</strong> unidades entrando
          </div>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 10 }}>
            <button className="btn-outline" onClick={limpar} disabled={submitting || !lote.length} style={{ padding: '10px 22px' }}>Limpar</button>
            <button
              onClick={confirmar}
              disabled={submitting || !lote.length}
              style={{
                padding: '10px 26px', fontSize: 14, fontWeight: 700, color: '#fff',
                background: (submitting || !lote.length) ? '#9CA3AF' : '#16A34A',
                cursor: (submitting || !lote.length) ? 'not-allowed' : 'pointer'
              }}>
              {submitting ? 'Registrando...' : '✓ Confirmar entrada'}
            </button>
          </div>
        </div>

        {/* [v224.217] Últimos lançamentos — só leitura. Sem valor, sem desfazer/editar/apagar:
            correção de lançamento continua sendo só do admin, por fora desta tela.
            Se a query falhar (lotesOk=false) o bloco inteiro some e a tela segue funcionando. */}
        {lotesOk && (
          <div style={{ marginTop: 28 }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: '#6B7280', letterSpacing: '.07em', marginBottom: 10 }}>
              ÚLTIMOS LANÇAMENTOS <span style={{ fontWeight: 500, color: '#9CA3AF' }}>· 7 dias</span>
            </div>

            {lotes.length === 0 && (
              <div className="card" style={{ color: '#9CA3AF' }}>Nenhum lançamento nos últimos 7 dias.</div>
            )}

            {lotes.map(b => {
              // `detalhe` é jsonb; defensivo porque lote antigo/torto não pode derrubar a lista.
              const itens = Array.isArray(b && b.detalhe) ? b.detalhe : [];
              return (
                <div key={b.idempotency_key} className="card" style={{ marginBottom: 10, padding: 0, overflow: 'hidden' }}>
                  <div style={{
                    display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap',
                    padding: '10px 14px', background: '#F9FAFB', borderBottom: '1px solid #F3F4F6',
                    fontSize: 13, color: '#374151'
                  }}>
                    <strong style={{ color: '#111827' }}>{fmtQuando(b.created_at)}</strong>
                    <span style={{ color: '#D1D5DB' }}>·</span>
                    <span>{b.user_name || '—'}</span>
                    <span style={{ color: '#D1D5DB' }}>·</span>
                    <span>{plural(Number(b.itens) || 0, 'decante', 'decantes')}</span>
                    <span style={{ color: '#D1D5DB' }}>·</span>
                    <span>{plural(Number(b.unidades) || 0, 'unidade', 'unidades')}</span>
                  </div>
                  <div>
                    {itens.map((d, i) => (
                      // key por índice: `detalhe` pode ter o mesmo product_id repetido em lote antigo
                      <div key={i} style={{
                        display: 'flex', alignItems: 'center', gap: 12,
                        padding: '9px 14px', fontSize: 13,
                        borderBottom: i < itens.length - 1 ? '1px solid #F9FAFB' : 'none'
                      }}>
                        {/* nome CONGELADO no lançamento — o produto pode ter sido renomeado depois */}
                        <span style={{ color: '#374151' }}>{d && d.name ? d.name : '(sem nome)'}</span>
                        <span style={{ marginLeft: 'auto', color: '#6B7280', whiteSpace: 'nowrap' }}>
                          {fmtSaldo(d && d.antes)} <span style={{ color: '#9CA3AF' }}>→</span> <strong style={{ color: '#374151' }}>{fmtSaldo(d && d.depois)}</strong>
                        </span>
                        <span style={{ color: '#16A34A', fontWeight: 700, minWidth: 46, textAlign: 'right', whiteSpace: 'nowrap' }}>
                          +{Number(d && d.entrou) || 0}
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════
  // EXPORT
  // ══════════════════════════════════════════════════════════════
  window.ZNX = window.ZNX || {};
  window.ZNX.components = window.ZNX.components || {};
  window.ZNX.components.EntradaDecantes = EntradaDecantes;
  window.EntradaDecantes = EntradaDecantes;
})();
