// Tráfego interno → Pedidos (spec 2026-11-24-gestao-trafego-comissao-design §8.2).
// Pedidos internos com as parcelas já resolvidas pela base: a tela só formata, não soma nada.
// Filtro, busca, ordem e página rodam no servidor e ficam no hash (#trafego-pedidos?…), então
// recarregar, mandar o link e voltar/avançar abrem o mesmo recorte. Parcela desconhecida é null:
// aparece como "pendente" e a margem como "Parcial", nunca zero. Conta de gestor só recebe os
// próprios pedidos (o recorte é do servidor); aqui o filtro Gestor some.
// Molde ui-fenix: LoadingScreen no 1º load, FullLoadingOverlay na troca de filtro, offline
// honesto com useAutoRetry, SEM mock. Reusa tf/gtx (TrafegoVisao, GestaoConfig), kd (KpiDrawer),
// fb (FilterBar) e ac (Acompanhamento). Prefixo top-level: gt/Gt/GT_.

const GT_PED_TAMANHO = 50;
const GT_PED_VALORES_MAX = 100;   // valores por filtro e caracteres por valor: limites da API
const GT_PED_VALOR_MAX = 200;
const GT_PED_BUSCA_MAX = 100;
const GT_PED_OPCOES_VISIVEIS = 200;   // o resto se acha pela busca do filtro
const GT_PED_DIMENSOES = [
  { key: 'status',     label: 'Status',     icon: 'filter' },
  { key: 'canal',      label: 'Canal',      icon: 'globe' },
  { key: 'gestor',     label: 'Gestor',     icon: 'users' },
  { key: 'conta',      label: 'Conta',      icon: 'layers' },
  { key: 'campanha',   label: 'Campanha',   icon: 'target' },
  { key: 'anuncio',    label: 'Anúncio',    icon: 'chart' },
  { key: 'copy',       label: 'Copywriter', icon: 'list' },
  { key: 'editor',     label: 'Editor',     icon: 'list' },
  { key: 'produto',    label: 'Produto',    icon: 'cart' },
  { key: 'plataforma', label: 'Plataforma', icon: 'dollar' },
];
const GT_PED_MARGEM = 'Margem antes do tráfego e da reserva';
const GT_PED_MARGEM_NOTA = 'A margem não desconta o tráfego nem a reserva de reembolso; a reserva aparece em Gestores e em Resultado por canal.';
// Ordens que a API aceita e a direção do 1º clique.
const GT_PED_ORDENS = { data: 'desc', bruta: 'desc', devolvido: 'desc', margem: 'desc',
  produto: 'asc', campanha: 'asc', gestor: 'asc', status: 'asc' };
const GT_PED_STATUS = {   // chaves do filtro da API
  completed: { label: 'Concluído', color: 'var(--positive)', background: 'var(--positive-bg)' },
  parcial: { label: 'Reembolso parcial', color: 'var(--warning)', background: 'var(--warning-bg)' },
  refunded: { label: 'Reembolsado', color: 'var(--negative)', background: 'var(--negative-bg)' },
  chargeback: { label: 'Chargeback', color: 'var(--negative)', background: 'var(--negative-bg)' },
  canceled: { label: 'Cancelado', color: 'var(--fg-3)', background: 'var(--bg-sunken)' },
};
// Rótulos que não dependem do período: situação sem gestor e valor vazio de cada filtro.
const GT_PED_SEM_GESTOR = { sem_dono: 'Sem dono', interno_sem_gestor: 'Interno sem gestor' };
const GT_PED_VAZIO = { canal: 'Sem canal', conta: 'Sem conta', campanha: 'Sem campanha', anuncio: 'Sem anúncio',
  copy: 'Sem código', editor: 'Sem código', produto: 'Sem produto', plataforma: 'Sem plataforma' };
// Parcela nula da linha → como a tela a chama (as três primeiras são as que a base deixa pendentes).
const GT_PED_PARCELAS = [['custoProduto', 'custo'], ['frete', 'frete'], ['taxa', 'taxa'], ['imposto', 'imposto'],
  ['comissaoAfiliado', 'comissão'], ['devolvido', 'devolvido'], ['bruta', 'receita']];

// ---- Recorte: estado da tela <-> hash ----
const gtPedPadrao = () => ({ period: '30d', customRange: null, filtros: {}, q: '', ordem: 'data', direcao: 'desc', pagina: 1 });
const gtPedDiaValido = (iso) => /^\d{4}-\d{2}-\d{2}$/.test(iso || '') && iso >= '2000-01-01' && gtIso(gtDia(iso)) === iso;
// Qualquer parte inválida do endereço cai no padrão dela, sem tela de erro.
const gtPedLeHash = () => {
  const m = String(location.hash || '').match(/^#trafego-pedidos\?(.*)$/);
  const p = new URLSearchParams(m ? m[1] : '');
  const e = gtPedPadrao();
  const limpo = (v) => v.length <= GT_PED_VALOR_MAX && v !== '' && !v.includes('\u0000');
  const period = p.get('period'), start = p.get('start'), end = p.get('end');
  if (period === 'custom') {
    if (gtPedDiaValido(start) && gtPedDiaValido(end) && start <= end) Object.assign(e, { period, customRange: { start, end } });
  } else if (PERIOD_OPTIONS.some(o => o.key === period)) e.period = period;
  GT_PED_FILTROS.forEach(nome => {
    const vals = [...new Set(p.getAll(nome))].filter(limpo).slice(0, GT_PED_VALORES_MAX);
    if (vals.length) e.filtros[nome] = vals;
  });
  e.q = (p.get('q') || '').replace(/\u0000/g, '').trim().slice(0, GT_PED_BUSCA_MAX).trim();
  if (Object.keys(GT_PED_ORDENS).includes(p.get('ordem'))) e.ordem = p.get('ordem');
  if (['asc', 'desc'].includes(p.get('direcao'))) e.direcao = p.get('direcao');
  if (/^[1-9]\d{0,5}$/.test(p.get('pagina') || '')) e.pagina = Number(p.get('pagina'));
  return e;
};
const gtPedHash = (e) => {
  const p = new URLSearchParams({ period: e.period });
  if (e.period === 'custom' && e.customRange) { p.set('start', e.customRange.start); p.set('end', e.customRange.end); }
  GT_PED_FILTROS.forEach(nome => (e.filtros[nome] || []).forEach(v => p.append(nome, v)));
  if (e.q) p.set('q', e.q);
  p.set('ordem', e.ordem); p.set('direcao', e.direcao); p.set('pagina', e.pagina);
  return '#trafego-pedidos?' + p;
};
const gtPedGravaHash = (e) => { try { history.replaceState(null, '', gtPedHash(e)); } catch (_e) { /* sem history */ } };

// ---- Formatos ----
// Valor de um pedido leva centavos (a cascata precisa fechar a olho); total do recorte, não.
const gtPedSinal = (fmt) => (v) => (v == null ? 'n/d' : Number(v) < 0 ? '−' + fmt(-v) : fmt(Number(v)));
const gtPedUsd = gtPedSinal(gtUsd);
const gtPedCents = gtPedSinal(tfCents);
const gtPedLista = (xs) => (xs.length > 1 ? xs.slice(0, -1).join(', ') + ' e ' + xs[xs.length - 1] : xs[0] || '');
const gtPedFaltam = (r) => GT_PED_PARCELAS.filter(([k]) => r[k] == null).map(([, nome]) => nome);
const gtPedPlataforma = (k) => (Object.hasOwn(PLATFORM, k) ? PLATFORM[k].label : k);
const gtPedCanal = (k) => TF_CANAL_LABELS[k] || k;
const gtPedGestor = (r) => r.gestor || GT_PED_SEM_GESTOR[r.situacao] || 'Sem dono';
const gtPedStatus = (r) => {
  const s = String(r.status || '');
  if (r.parcial) return GT_PED_STATUS.parcial;
  if (s === 'Completed') return GT_PED_STATUS.completed;
  if (s === 'Refunded') return GT_PED_STATUS.refunded;
  if (/^(cgbk|chargeback)$/i.test(s)) return GT_PED_STATUS.chargeback;
  if (/^canceled/i.test(s)) return GT_PED_STATUS.canceled;
  return { label: s || 'sem status', color: 'var(--fg-2)', background: 'var(--bg-sunken)' };
};
const gtPedTags = (r) => [
  r.upsell && ['Upsell', 'var(--fenix-blue)', 'var(--fenix-blue-100)'],
  r.sms && ['SMS', 'var(--fenix-blue)', 'var(--fenix-blue-100)', 'Venda por SMS interno'],
  r.origem === 'sessao' && ['Sessão', 'var(--fenix-blue)', 'var(--fenix-blue-100)', 'Herdou a origem de outro pedido da mesma pessoa no mesmo dia'],
  r.taxaEstimada && ['Taxa estimada', 'var(--fg-2)', 'var(--gray-200)', 'A taxa da plataforma neste pedido é estimada'],
  r.custoPendente && ['Custo pendente', 'var(--warning)', 'var(--warning-bg)', 'Custo de produto ainda desconhecido'],
  r.fretePendente && ['Frete pendente', 'var(--warning)', 'var(--warning-bg)', 'Frete ainda desconhecido'],
].filter(Boolean);
const GtPedTags = ({ r }) => {
  const tags = gtPedTags(r);
  return tags.length > 0 && (
    <span style={gtpd.tags}>
      {tags.map(([t, color, background, title]) => <span key={t} style={{ ...gtpd.tag, color, background }} title={title}>{t}</span>)}
    </span>
  );
};
// Data da venda já vem em hora de Nova York, sem fuso: corta o texto, sem passar por Date.
const gtPedHora = (iso) => String(iso || '').slice(11, 16);

// Rótulo de um valor de filtro: o fixo da tela; senão o último que a API deu para ele, mesmo em
// outro período (vistos: Map 'filtro·valor' → rótulo, ver gtPedGuardaRotulos); senão o valor cru.
const gtPedRotulo = (nome, valor, vistos) => {
  const fixo = (mapa) => (Object.hasOwn(mapa, valor) ? mapa[valor] : null);   // o valor vem do link
  return (valor === '__vazio__' && GT_PED_VAZIO[nome])
    || (nome === 'status' && fixo(GT_PED_STATUS)?.label)
    || (nome === 'gestor' && fixo(GT_PED_SEM_GESTOR))
    || (nome === 'canal' && fixo(TF_CANAL_LABELS))
    || (nome === 'plataforma' && fixo(PLATFORM)?.label)
    || vistos.get(nome + '·' + valor)
    || (nome === 'anuncio' && valor.startsWith(GT_PED_ID) && (valor === GT_PED_ID + '__vazio__' ? 'Sem id de anúncio' : `Anúncio (id ${valor.slice(GT_PED_ID.length)})`))
    || valor;
};
const gtPedGuardaRotulos = (vistos, opcoes) => GT_PED_FILTROS.forEach(nome =>
  (opcoes[nome] || []).forEach(o => vistos.set(nome + '·' + o.key, o.label)));

// ---- Múltipla escolha com busca, contagem por opção e Limpar. Vazio = todos. ----
// options: [{key, label, pedidos}], ou null enquanto não há opções (aviso diz por quê).
// Valor marcado que não está nas opções continua na lista, com o rótulo de rotulo(valor).
const GtMultiBusca = ({ icon, label, values, options, rotulo, onChange, aviso }) => {
  const [open, setOpen] = React.useState(false);
  const [q, setQ] = React.useState('');
  const [desloc, setDesloc] = React.useState(0);
  const ref = React.useRef(null), botao = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const fora = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const esc = (e) => { if (e.key === 'Escape') { setOpen(false); botao.current && botao.current.focus(); } };
    document.addEventListener('mousedown', fora);
    document.addEventListener('keydown', esc);
    return () => { document.removeEventListener('mousedown', fora); document.removeEventListener('keydown', esc); };
  }, [open]);
  const abre = () => {
    const r = ref.current.getBoundingClientRect();
    const larg = Math.min(320, window.innerWidth - 32);
    setDesloc(Math.min(0, window.innerWidth - 16 - larg - r.left));   // nunca passa da borda direita
    setQ(''); setOpen(o => !o);
  };
  const sel = new Set(values);
  const cheio = values.length >= GT_PED_VALORES_MAX;
  const toggle = (k) => {
    if (sel.has(k)) onChange(values.filter(v => v !== k));
    else if (!cheio) onChange([...values, k]);
  };
  const tem = new Set((options || []).map(o => o.key));
  const todas = [...values.filter(v => !tem.has(v)).map(v => ({ key: v, label: rotulo(v), pedidos: null })), ...(options || [])];
  const t = acNorm(q.trim());
  const achadas = t ? todas.filter(o => acNorm(o.label).includes(t) || acNorm(o.key).includes(t)) : todas;
  const vis = open ? achadas.slice(0, GT_PED_OPCOES_VISIVEIS) : [];
  return (
    <div ref={ref} style={fb.ddWrap}>
      <button type="button" ref={botao} style={{ ...fb.dd, ...(open ? fb.ddOpen : {}) }} aria-expanded={open} aria-haspopup="dialog" onClick={abre}>
        {icon && <Icon name={icon} size={15} color="var(--fg-3)" />}
        <span style={fb.ddLabel}>{label}</span>
        {values.length === 0 ? <span style={fb.ddValue}>Todos</span>
          : <span style={{ ...fb.mdChip, ...gtpd.conta }} className="fenix-num">{values.length}</span>}
        <Icon name="chevronDown" size={15} color="var(--fg-3)" style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .18s' }} />
      </button>
      {open && (
        <div style={{ ...fb.menu, ...gtpd.menu, left: desloc }} role="dialog" aria-label={`Filtro ${label}`}>
          <input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder={`Buscar em ${label}`} aria-label={`Buscar em ${label}`} style={gtpd.menuBusca} />
          <div style={gtpd.menuLista}>
            {vis.map(o => {
              const on = sel.has(o.key);
              return (
                <button type="button" key={o.key} role="checkbox" aria-checked={on} disabled={!on && cheio} title={o.label}
                  style={{ ...fb.opt, ...gtpd.opt, ...(on ? fb.optOn : {}) }} onClick={() => toggle(o.key)}
                  onMouseEnter={e => { if (!on) e.currentTarget.style.background = 'var(--gray-50)'; }}
                  onMouseLeave={e => { if (!on) e.currentTarget.style.background = 'transparent'; }}>
                  <span style={{ ...fb.mdBox, ...(on ? gtpd.caixaOn : {}) }}>{on && <span style={fb.mdCheck} />}</span>
                  <span style={gtpd.optTxt}>{o.label}</span>
                  <span style={gtpd.optNum} className="fenix-num" title={o.pedidos == null ? undefined : 'Pedidos no período'}>
                    {o.pedidos == null ? (options ? 'fora do período' : '') : NUM(o.pedidos)}</span>
                </button>
              );
            })}
            {vis.length === 0 && options && <div style={fb.mdEmpty}>{t ? 'Nada encontrado.' : 'Sem opções no período.'}</div>}
          </div>
          {aviso && <div style={gtpd.menuNota}>{aviso}</div>}
          {achadas.length > vis.length && <div style={gtpd.menuNota}>Mostrando {NUM(vis.length)} de {NUM(achadas.length)}. Use a busca para achar o resto.</div>}
          {cheio && <div style={gtpd.menuNota}>Limite de {GT_PED_VALORES_MAX} valores por filtro.</div>}
          {values.length > 0 && <button type="button" style={fb.mdClear} onClick={() => onChange([])}>Limpar ({values.length})</button>}
        </div>
      )}
    </div>
  );
};

// ---- Gaveta do pedido: cascata das parcelas, origem e clique ----
const GtPedLinha = ({ rotulo, valor, mono }) => (
  <div style={gtpd.kv}>
    <span style={gtpd.k}>{rotulo}</span>
    <span style={{ ...gtpd.v, ...(mono ? gtpd.vMono : {}) }}>{valor == null || valor === '' ? <span style={{ color: 'var(--fg-3)' }}>não informado</span> : valor}</span>
  </div>
);
// Dedução vem positiva da API: o sinal de menos é da tela. Zero não leva sinal.
const gtPedDeducao = (v) => (Number(v) === 0 ? tfCents(0) : (Number(v) > 0 ? '−' : '+') + tfCents(Math.abs(Number(v))));
const GtPedCascata = ({ parcelas }) => (
  <div style={kd.compCard}>
    <div style={kd.compEye}>Da receita à margem</div>
    {parcelas.map(p => {
      const total = p.chave === 'margem', base = p.chave === 'bruta';
      return (
        <div key={p.chave} style={{ ...kd.compRow, alignItems: 'center', ...(total ? gtpd.linhaTotal : {}) }} data-parcela={p.chave}>
          <div style={kd.compMain}>
            <div style={{ ...kd.compLabel, ...(total || base ? { fontWeight: 700 } : {}) }}>{p.rotulo}</div>
            {p.estimada && <div style={kd.compSub}>estimada</div>}
          </div>
          {p.pendente || p.valor == null
            ? <GtPill color="var(--warning)" background="var(--warning-bg)">{total ? 'Parcial' : 'pendente'}</GtPill>
            : <span style={{ ...kd.compVal, ...(total ? { color: Number(p.valor) < 0 ? 'var(--negative)' : 'var(--positive)', fontWeight: 800 } : {}) }} className="fenix-num">
                {total || base ? gtPedCents(p.valor) : gtPedDeducao(p.valor)}</span>}
        </div>
      );
    })}
    <div style={kd.compNote}>Não é o lucro do pedido. {GT_PED_MARGEM_NOTA}</div>
  </div>
);
const GtPedGaveta = ({ plataforma, orderId, onClose }) => {
  const [d, setD] = React.useState(null);
  const [err, setErr] = React.useState(null);
  const [vez, setVez] = React.useState(0);
  const painel = React.useRef(null);
  const fechar = React.useRef(onClose);
  fechar.current = onClose;
  React.useEffect(() => {
    const c = new AbortController();
    setD(null); setErr(null);
    gtFetchPedido(plataforma, orderId, c.signal)
      .then(x => { if (!c.signal.aborted) setD(x); })
      .catch(e => { if (!c.signal.aborted) setErr(e); });
    return () => c.abort();
  }, [plataforma, orderId, vez]);
  // Foco no painel ao abrir e de volta na linha ao fechar; Escape fecha; Tab não sai do painel.
  React.useEffect(() => {
    const antes = document.activeElement;
    if (painel.current) painel.current.focus();
    const tecla = (e) => {
      if (e.key === 'Escape') fechar.current();
      if (e.key !== 'Tab' || !painel.current) return;
      const f = painel.current.querySelectorAll('button');
      const prim = f[0], ult = f[f.length - 1], at = document.activeElement;
      if (e.shiftKey ? at === prim || at === painel.current : at === ult) { e.preventDefault(); (e.shiftKey ? ult : prim).focus(); }
    };
    document.addEventListener('keydown', tecla);
    return () => { document.removeEventListener('keydown', tecla); if (antes && antes.isConnected) antes.focus(); };
  }, []);
  const r = d && d.pedido, c = d && d.clique;
  const status = r && gtPedStatus(r);
  const margem = d && d.parcelas.find(p => p.chave === 'margem');
  const faltam = d ? d.parcelas.filter(p => p.pendente && p.chave !== 'margem').map(p => p.rotulo) : [];
  return (
    <div style={gtpd.fundo} onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <aside ref={painel} tabIndex={-1} role="dialog" aria-modal="true" aria-label={`Pedido ${orderId}`} style={gtpd.painel}>
        <div style={kd.head}>
          <button type="button" style={kd.close} onClick={onClose} aria-label="Fechar"><Icon name="x" size={18} color="var(--fg-2)" /></button>
          <div style={{ paddingRight: 44, minWidth: 0 }}>
            <div style={kd.eyebrow}>Pedido · {gtPedPlataforma(plataforma)}</div>
            <div style={{ ...kd.title, overflowWrap: 'anywhere' }}>{orderId}</div>
          </div>
        </div>
        <div style={kd.body}>
          {!d && !err && <div style={gtpd.gavetaMsg} role="status"><Spinner color="var(--fenix-orange)" size={28} bw={3} />Carregando o pedido…</div>}
          {err && (
            <div style={gtpd.gavetaMsg} role="alert">
              <Icon name="alert" size={24} color="var(--warning)" />
              <span>{err.message.replace(/\.$/, '')}.</span>
              {err.status !== 404 && err.status !== 403 && (
                <button type="button" style={gtx.btnGhost} onClick={() => setVez(v => v + 1)}>Tentar de novo</button>)}
            </div>
          )}
          {d && (
            <>
              <div style={kd.totalCard}>
                <span style={kd.totalEye}>{GT_PED_MARGEM}</span>
                <div style={{ ...kd.totalVal, font: '800 30px/1 var(--font-num)' }} className="fenix-num">
                  {margem.valor == null ? 'Parcial' : gtPedCents(margem.valor)}</div>
                {margem.valor == null && <div style={kd.totalSub}>Falta: {gtPedLista(faltam)}</div>}
              </div>
              <GtPedCascata parcelas={d.parcelas} />
              <div style={kd.compCard}>
                <div style={kd.compEye}>Venda</div>
                <GtPedLinha rotulo="Data" valor={r.data && `${gtDia(r.data)} ${gtPedHora(r.data)} (Nova York)`} />
                <GtPedLinha rotulo="Produto" valor={r.produto} />
                <GtPedLinha rotulo="Frascos" valor={r.frascos} />
                <GtPedLinha rotulo="Tipo" valor={r.upsell ? 'Upsell' : 'Principal'} />
                <GtPedLinha rotulo="Status" valor={<GtPill color={status.color} background={status.background} title={r.status || undefined}>{status.label}</GtPill>} />
                <GtPedLinha rotulo="Gestor" valor={gtPedGestor(r)} />
                <GtPedTags r={r} />
              </div>
              <div style={kd.compCard}>
                <div style={kd.compEye}>Origem</div>
                <GtPedLinha rotulo="Canal" valor={r.canal && gtPedCanal(r.canal)} />
                <GtPedLinha rotulo="Conta" valor={r.conta} />
                <GtPedLinha rotulo="Campanha" valor={r.campanha} />
                <GtPedLinha rotulo="Anúncio" valor={r.anuncio} />
                <GtPedLinha rotulo="Copywriter" valor={r.copy} mono />
                <GtPedLinha rotulo="Editor" valor={r.editor} mono />
              </div>
              <div style={kd.compCard}>
                <div style={kd.compEye}>Clique no RedTrack</div>
                {!c ? <div style={gtpd.k}>Pedido sem conversão no RedTrack.</div> : (
                  <>
                    <GtPedLinha rotulo="Click ID" valor={c.clickid} mono />
                    <GtPedLinha rotulo="Conversão" valor={c.conversaoEm && new Date(c.conversaoEm).toLocaleString('pt-BR',
                      { timeZone: 'America/New_York', day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }) + ' (Nova York)'} />
                    <GtPedLinha rotulo="Fonte" valor={c.sourceAlias} />
                    <GtPedLinha rotulo="ID da campanha" valor={c.rtCampaignId} mono />
                    <GtPedLinha rotulo="ID do conjunto" valor={c.rtAdgroupId} mono />
                    <GtPedLinha rotulo="ID do anúncio" valor={c.rtAdId} mono />
                  </>
                )}
              </div>
            </>
          )}
        </div>
      </aside>
    </div>
  );
};

// ---- Tabela: ordem e página são do servidor. Dinheiro antes da origem: cabe sem rolar em 1280. ----
const GtPedNome = ({ nome, vazio, sub }) => (
  <div style={gtx.nomeWrap}>
    <span style={{ ...gtx.ell, ...(nome ? {} : { color: 'var(--fg-3)', fontWeight: 500 }) }} title={nome || undefined}>{nome || vazio}</span>
    <span style={gtpd.ellSub} title={sub}>{sub}</span>
  </div>
);
const GT_PED_COLS = [
  { key: 'data', ordem: 'data', label: 'Data', style: { whiteSpace: 'nowrap' }, cel: r => (
    <div style={gtx.nomeWrap}><span className="fenix-num" style={gtpd.num}>{gtDia(r.data)}</span><span style={gtx.sub} className="fenix-num">{gtPedHora(r.data)}</span></div>) },
  { key: 'pedido', label: 'Pedido', cel: (r, abrir) => (
    <div style={gtx.nomeWrap}>
      <button type="button" style={gtpd.id} onClick={e => { e.stopPropagation(); abrir(r); }} title="Ver as parcelas do pedido">{r.orderId}</button>
      <span style={gtx.sub}>{gtPedPlataforma(r.plataforma)}</span>
    </div>) },
  { key: 'produto', ordem: 'produto', label: 'Produto', style: { width: '23%', maxWidth: 0 }, cel: r => (
    <div style={gtx.nomeWrap}><span style={gtx.ell} title={r.produto || undefined}>{r.produto || 'Produto sem nome'}</span><GtPedTags r={r} /></div>) },
  { key: 'status', ordem: 'status', label: 'Status', cel: r => {
    const s = gtPedStatus(r);
    return <GtPill color={s.color} background={s.background} title={r.status || undefined}>{s.label}</GtPill>;
  } },
  { key: 'bruta', ordem: 'bruta', label: 'Receita bruta', num: true, style: { fontWeight: 700 }, cel: r => gtPedCents(r.bruta) },
  { key: 'devolvido', ordem: 'devolvido', label: 'Devolvido', num: true,
    cel: r => (Number(r.devolvido) > 0 ? <span style={{ color: 'var(--negative)' }}>{gtPedCents(r.devolvido)}</span> : gtPedCents(r.devolvido)) },
  { key: 'margem', ordem: 'margem', label: GT_PED_MARGEM, num: true, th: { whiteSpace: 'normal', minWidth: 150, lineHeight: 1.25 }, cel: r => (r.margem != null
    ? <span style={{ fontWeight: 700, color: Number(r.margem) < 0 ? 'var(--negative)' : 'var(--fg-1)' }}>{gtPedCents(r.margem)}</span>
    : <span style={gtpd.parcial}><GtPill color="var(--warning)" background="var(--warning-bg)">Parcial</GtPill><span style={gtx.sub}>falta {gtPedLista(gtPedFaltam(r))}</span></span>) },
  { key: 'gestor', ordem: 'gestor', label: 'Gestor', style: { whiteSpace: 'nowrap' }, cel: r => (r.gestor
    ? r.gestor : <span style={{ color: 'var(--fg-3)' }}>{gtPedGestor(r)}</span>) },
  { key: 'campanha', ordem: 'campanha', label: 'Campanha', style: { width: '23%', maxWidth: 0 }, cel: r => (
    <GtPedNome nome={r.campanha} vazio="Sem campanha" sub={[r.canal && gtPedCanal(r.canal), r.conta].filter(Boolean).join(' · ') || 'sem canal'} />) },
  { key: 'anuncio', label: 'Anúncio', style: { width: '15%', maxWidth: 0 }, cel: r => (
    <GtPedNome nome={r.anuncio} vazio="Sem anúncio"
      sub={[r.copy && `Copy ${r.copy}`, r.editor && `Editor ${r.editor}`].filter(Boolean).join(' · ') || 'sem código'} />) },
];
const GtPedTabela = ({ data, est, loading, filtrado, onOrdem, onPagina, onAbrir, onLimpar }) => {
  const rolagem = React.useRef(null);
  const { rows, total, pagina, tamanho } = data;
  const paginas = Math.max(1, Math.ceil(total / tamanho));
  React.useEffect(() => { if (rolagem.current) rolagem.current.scrollTop = 0; }, [pagina, est.ordem, est.direcao]);
  const de = (pagina - 1) * tamanho;
  // Respiro das pontas e entre número (à direita) e texto, como no GtTabela.
  const borda = (i) => ({
    ...(i === 0 ? { paddingLeft: 16 } : !GT_PED_COLS[i].num && GT_PED_COLS[i - 1].num ? { paddingLeft: 26 } : {}),
    ...(i === GT_PED_COLS.length - 1 ? { paddingRight: 16 } : {}),
  });
  const pula = (rotulo, alvo, texto, off) => (
    <button type="button" aria-label={rotulo} disabled={off} onClick={() => onPagina(alvo)}
      style={{ ...tf.toolBtn, ...(off ? { opacity: .45, cursor: 'default' } : {}) }}>{texto}</button>
  );
  return (
    <div style={tf.tableCard}>
      <div style={tf.tblHead}>
        <div style={{ minWidth: 0, flex: '1 1 240px' }}>
          <div style={tf.panelTitle}>Lista de pedidos</div>
          <div style={tf.panelSub}>{data.kpis.cancelados > 0 ? 'Principais, upsells e cancelados' : 'Principais e upsells'}. Clique num pedido para ver as parcelas.</div>
        </div>
        <span style={tf.count} className="fenix-num" role="status">
          {loading ? 'Atualizando…' : total === 0 ? 'nenhum pedido' : `${NUM(de + 1)} a ${NUM(de + rows.length)} de ${NUM(total)}`}
        </span>
      </div>
      <div ref={rolagem} style={{ ...tf.scroll, maxHeight: 640, opacity: loading ? .55 : 1, transition: 'opacity .15s' }} aria-busy={loading}>
        <table style={{ ...tf.table, minWidth: 1320 }}>
          <thead><tr>
            {GT_PED_COLS.map((c, i) => {
              const on = c.ordem && est.ordem === c.ordem;
              return (
                <th key={c.key} aria-sort={on ? (est.direcao === 'asc' ? 'ascending' : 'descending') : undefined}
                  style={{ ...tf.th, textAlign: c.num ? 'right' : 'left', cursor: 'default', ...borda(i), ...c.th }}>
                  {c.ordem ? (
                    <button type="button" style={gtpd.thBtn} onClick={() => onOrdem(c.ordem)}>
                      {c.label}{on ? (est.direcao === 'desc' ? ' ▾' : ' ▴') : ''}</button>
                  ) : c.label}
                </th>
              );
            })}
          </tr></thead>
          <tbody>
            {rows.map(r => (
              <tr key={r.plataforma + '·' + r.orderId} style={{ cursor: 'pointer' }} onClick={() => onAbrir(r)}
                onMouseEnter={e => { e.currentTarget.style.background = 'var(--gray-50)'; }}
                onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; }}>
                {GT_PED_COLS.map((c, i) => (
                  <td key={c.key} className={c.num ? 'fenix-num' : undefined}
                    style={{ ...(c.num ? tf.tdNum : gtx.td), ...borda(i), ...c.style }}>{c.cel(r, onAbrir)}</td>
                ))}
              </tr>
            ))}
            {rows.length === 0 && (
              <tr><td colSpan={GT_PED_COLS.length} style={tf.empty}>
                {filtrado ? <>Nenhum pedido com estes filtros no período. <button type="button" onClick={onLimpar} style={tf.linkBtn}>Limpar filtros</button></>
                  : 'Nenhum pedido interno no período.'}
              </td></tr>
            )}
          </tbody>
        </table>
      </div>
      {paginas > 1 && (
        <div style={{ ...tf.more, flexWrap: 'wrap' }}>
          {pula('Primeira página', 1, '«', pagina <= 1)}
          {pula('Página anterior', pagina - 1, '‹', pagina <= 1)}
          <span className="fenix-num">Página {NUM(pagina)} de {NUM(paginas)}</span>
          {pula('Próxima página', pagina + 1, '›', pagina >= paginas)}
          {pula('Última página', paginas, '»', pagina >= paginas)}
        </div>
      )}
    </div>
  );
};

// ---- Página ----
// Pedido recusado (4xx) não se resolve sozinho; sessão renovada (401), tempo (408), 5xx e rede sim.
const gtPedRetenta = (e) => !!e && (!(e.status >= 400 && e.status < 500) || e.status === 401 || e.status === 408);
const GestaoPedidosView = () => {
  const pode = !!window.FenixAuth?.canNav('trafego-pedidos');
  const podeExportar = !!window.FenixAuth?.can('exportar');
  const [est, setEst] = React.useState(gtPedLeHash);
  const [texto, setTexto] = React.useState(() => est.q);   // o que está digitado; est.q é o que foi pedido
  const [resp, setResp] = React.useState(null);            // {data, start, end}: a janela do que está na tela
  const [err, setErr] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [opc, setOpc] = React.useState({ data: null, start: null, end: null, err: null });
  const [aberto, setAberto] = React.useState(null);
  const [baixando, setBaixando] = React.useState(false);
  const [erroBaixar, setErroBaixar] = React.useState(null);
  const estAtual = React.useRef(est);
  estAtual.current = est;
  const fullLoading = useFullLoading();
  const withLoad = (fn) => (...a) => { fullLoading.mark(); fn(...a); };
  const retry = useAutoRetry(gtPedRetenta(err));
  const retryOpc = useAutoRetry(gtPedRetenta(opc.err));
  const tick = useTfTick();
  const [vez, setVez] = React.useState(0);   // +1 relê mesmo com o recorte igual
  const vistos = React.useRef(new Map());

  // Toda mudança volta à página 1, menos a da própria página.
  const muda = (patch) => setEst(e => ({ ...e, pagina: 1, ...patch }));
  const filtra = (nome, valores) => setEst(e => {
    const filtros = { ...e.filtros };
    if (valores.length) filtros[nome] = valores; else delete filtros[nome];
    return { ...e, filtros, pagina: 1 };
  });
  const limpar = withLoad(() => { setTexto(''); muda({ filtros: {}, q: '' }); });
  const voltarAoPadrao = () => { setTexto(''); setEst(gtPedPadrao()); setVez(v => v + 1); };

  // Busca: espera 400 ms sem digitar. Sem overlay, que cobriria o próprio campo.
  React.useEffect(() => {
    const q = texto.trim();
    const id = setTimeout(() => setEst(e => (e.q === q ? e : { ...e, q, pagina: 1 })), 400);
    return () => clearTimeout(id);
  }, [texto]);

  React.useEffect(() => { if (pode) gtPedGravaHash(est); }, [est, pode]);
  // Voltar/avançar, link editado ou clique no menu com a página aberta (o App limpa o hash:
  // volta ao padrão). Outra tela do tráfego: quem troca é o App, ou o endereço volta se for negada.
  React.useEffect(() => {
    if (!pode) return;
    const onHash = () => {
      if (gtHashLimpo('trafego-pedidos') || /^#trafego-pedidos(\?|$)/.test(location.hash)) {
        const novo = gtPedLeHash();
        setTexto(novo.q);
        if (gtPedHash(novo) === gtPedHash(estAtual.current)) { gtPedGravaHash(novo); return; }
        fullLoading.mark();
        setAberto(null);
        setEst(novo);
      } else if (/^#trafego-/.test(location.hash) && !tfNavDoHash()) gtPedGravaHash(estAtual.current);
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, [pode]);

  const jan = gtJanela(est.period, est.customRange);
  const rec = { ...jan, filtros: est.filtros, q: est.q, ordem: est.ordem, direcao: est.direcao };
  const busca = gtPedidosParams(rec);
  busca.set('pagina', est.pagina); busca.set('tamanho', GT_PED_TAMANHO);
  const params = busca.toString();

  React.useEffect(() => {
    if (!pode) return;
    const began = fullLoading.begin();
    const c = new AbortController();
    setLoading(true);
    gtFetchPedidos(params, c.signal)
      .then(data => {
        if (c.signal.aborted) return;
        setErr(null);
        const ultima = Math.max(1, Math.ceil(data.total / data.tamanho));
        // Página que não existe mais (link antigo, recorte que encolheu): vai para a última.
        if (data.pagina > ultima) setEst(e => ({ ...e, pagina: ultima }));
        else setResp({ data, ...jan });
      })
      .catch(e => { if (!c.signal.aborted) setErr(e); })
      .finally(() => { if (!c.signal.aborted) setLoading(false); fullLoading.end(began); });
    return () => c.abort();
  }, [pode, params, retry, tick, vez]);

  const idsAnuncio = (est.filtros.anuncio || []).filter(v => v.startsWith(GT_PED_ID));
  React.useEffect(() => {
    if (!pode) return;
    const c = new AbortController();
    gtFetchPedidosFiltros(jan, idsAnuncio, c.signal)
      .then(data => {
        if (c.signal.aborted) return;
        gtPedGuardaRotulos(vistos.current, data);
        setOpc({ data, err: null, ...jan });
      })
      .catch(e => { if (!c.signal.aborted) setOpc(o => ({ ...o, err: e })); });
    return () => c.abort();
  }, [pode, jan.start, jan.end, idsAnuncio.join('·'), retryOpc, tick]);

  React.useEffect(() => { setErroBaixar(null); }, [params]);

  if (!pode) return <GtFalha err={{ detalhe: true, status: 403, message: 'Seu perfil não tem acesso aos pedidos do tráfego' }} />;
  if (err && (!resp || err.status === 403)) return (
    <GtFalha err={err} titulo="Pedidos indisponíveis" nota="Pedidos do tráfego interno." retenta={gtPedRetenta(err)}>
      {!gtPedRetenta(err) && err.status !== 403 && <button type="button" style={gtx.btnGhost} onClick={voltarAoPadrao}>Voltar ao padrão</button>}
    </GtFalha>
  );
  if (!resp) return <LoadingScreen conn="connecting" />;

  const { data } = resp;
  const k = data.kpis;
  const dimensoes = GT_PED_DIMENSOES.filter(d => d.key !== 'gestor' || data.verTodos);
  // Opções de outro período têm contagem errada: até as novas chegarem, só o aviso.
  const opcAtuais = opc.data && opc.start === jan.start && opc.end === jan.end ? opc.data : null;
  const opcAviso = opcAtuais ? null : opc.err
    ? `Não foi possível carregar as opções: ${opc.err.message.replace(/\.$/, '')}.` : 'Carregando opções…';
  // Chips saem de todos os filtros ativos, mesmo do que não tem seletor nesta conta.
  const chips = GT_PED_DIMENSOES.flatMap(d => (est.filtros[d.key] || []).map(v => ({ ...d, valor: v, texto: gtPedRotulo(d.key, v, vistos.current) })));
  const filtrado = chips.length > 0 || !!est.q;
  const vazio = data.total === 0;
  const baixar = () => {
    if (vazio || baixando) return;
    setBaixando(true); setErroBaixar(null);
    window.FenixAuth.download(gtPedidosExportUrl(rec))
      .catch(e => setErroBaixar(e.detail ? gtTextoDetalhe(e.detail)
        : e.status ? `O download falhou (erro ${e.status} na API).` : 'O download falhou: a API não respondeu.'))
      .finally(() => setBaixando(false));
  };
  const ordena = (o) => muda(est.ordem === o ? { direcao: est.direcao === 'desc' ? 'asc' : 'desc' } : { ordem: o, direcao: GT_PED_ORDENS[o] });
  const semMargem = k.parciais > 0 && k.parciais >= data.total;   // nenhuma linha completa: a soma 0 não é margem
  const cobertura = Number(k.bruta) ? ` (${PCT(k.brutaCompleta / k.bruta * 100)})` : '';   // receita com margem conhecida

  return (
    <div style={{ position: 'relative' }}>
      <div style={tf.header}>
        <div style={tf.headTop}>
          <div style={tf.titleWrap}>
            <h2 style={tf.title}>Pedidos</h2>
            <span style={tf.stamp} className="fenix-num">{gtDia(resp.start)} a {gtDia(resp.end)}</span>
            <span style={gtx.sub}>dias de Nova York, pela data da venda</span>
          </div>
          {podeExportar && (
            <button type="button" onClick={baixar} disabled={vazio || baixando}
              title={vazio ? 'Sem pedidos para baixar' : 'Baixar XLSX de todos os pedidos deste recorte'}
              style={{ ...ac.exportBtn, ...(vazio || baixando ? { opacity: .45, cursor: 'default' } : {}) }}>
              <Icon name="download" size={15} color="currentColor" /> {baixando ? 'Baixando…' : 'Baixar relatório'}
            </button>
          )}
        </div>
        <div style={tf.filterRow}>
          <PeriodSelector period={est.period} setPeriod={withLoad(v => muda({ period: v }))}
            customRange={est.customRange} setCustomRange={withLoad(v => muda({ customRange: v }))} />
          {dimensoes.map(d => (
            <GtMultiBusca key={d.key} icon={d.icon} label={d.label} values={est.filtros[d.key] || []}
              options={opcAtuais && (opcAtuais[d.key] || []).map(o => ({ ...o, label: gtPedRotulo(d.key, o.key, vistos.current) }))}
              rotulo={v => gtPedRotulo(d.key, v, vistos.current)} aviso={opcAviso} onChange={withLoad(v => filtra(d.key, v))} />
          ))}
          <label style={{ ...tf.search, width: 300 }}>
            <Icon name="search" size={15} color="var(--fg-3)" />
            <input value={texto} onChange={e => setTexto(e.target.value)} maxLength={GT_PED_BUSCA_MAX}
              placeholder="Pedido, campanha, anúncio ou produto" aria-label="Buscar pedido, campanha, anúncio ou produto" style={tf.searchInput} />
            {texto && <button type="button" style={tf.clearBtn} aria-label="Limpar busca" onClick={() => setTexto('')}><Icon name="x" size={12} /></button>}
          </label>
        </div>
        {filtrado && (
          <div style={gtpd.chips}>
            {chips.map(c => (
              <button type="button" key={c.key + '·' + c.valor} style={gtpd.chip} title={`${c.label}: ${c.texto}`} aria-label={`Remover filtro ${c.label}: ${c.texto}`}
                onClick={withLoad(() => filtra(c.key, est.filtros[c.key].filter(v => v !== c.valor)))}>
                <span style={gtpd.chipTxt}><span style={gtpd.chipDim}>{c.label}:</span> {c.texto}</span><Icon name="x" size={12} style={{ flex: 'none' }} />
              </button>
            ))}
            {est.q && (
              <button type="button" style={gtpd.chip} title={`Busca: ${est.q}`} aria-label={`Remover busca: ${est.q}`} onClick={() => { setTexto(''); muda({ q: '' }); }}>
                <span style={gtpd.chipTxt}><span style={gtpd.chipDim}>Busca:</span> {est.q}</span><Icon name="x" size={12} style={{ flex: 'none' }} />
              </button>
            )}
            <button type="button" style={{ ...tf.linkBtn, fontSize: 12 }} onClick={limpar}>Limpar filtros</button>
          </div>
        )}
        {err && (
          <div role="status" style={gtx.aviso}>
            <Icon name="alert" size={14} color="currentColor" style={{ flex: 'none' }} />
            <span>Falha ao atualizar: {err.message.replace(/\.$/, '')}. Os números abaixo são os da última consulta que deu certo,
              de {gtDia(resp.start)} a {gtDia(resp.end)}{gtPedRetenta(err) ? '; a tela tenta de novo sozinha a cada 15 s.' : '. Mude ou limpe os filtros.'}</span>
          </div>
        )}
        {erroBaixar && (
          <div role="alert" style={{ ...gtx.erro, display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ flex: 1, minWidth: 0, overflowWrap: 'anywhere' }}>{erroBaixar}</span>
            <button type="button" style={tf.clearBtn} aria-label="Fechar aviso" onClick={() => setErroBaixar(null)}><Icon name="x" size={12} /></button>
          </div>
        )}
      </div>

      <div style={gtpd.kpis}>
        <div style={gtpd.kpiPar}>
          <DotKpi eye="Pedidos" color="var(--fenix-blue)" value={NUM(k.pedidos)}
            sub={`${gtPlural(k.principais, 'principal', 'principais')}, ${gtPlural(k.upsells, 'upsell', 'upsells')}${k.cancelados ? `. Fora ${gtPlural(k.cancelados, 'cancelado', 'cancelados')}` : ''}`} />
          <DotKpi eye="Receita bruta" color="var(--fenix-orange)" value={gtPedUsd(k.bruta)} sub="Pedidos principais e upsells" />
        </div>
        <div style={gtpd.kpiPar}>
          <DotKpi eye="Devolvido" color="var(--negative)" value={gtPedUsd(k.devolvido)}
            sub={k.taxaReembolso == null ? 'Sem receita no recorte' : `${PCT(k.taxaReembolso * 100)} da receita bruta`} />
          <DotKpi eye={k.parciais ? 'Margem conhecida' : GT_PED_MARGEM} color={k.parciais ? 'var(--warning)' : 'var(--positive)'} value={semMargem ? 'n/d' : gtPedUsd(k.margem)}
            sub={k.parciais ? `de ${gtPedUsd(k.brutaCompleta)} de receita${cobertura}; ${k.parciais === 1 ? 'falta' : 'faltam'} ${gtPlural(k.parciais, 'pedido', 'pedidos')} com parcela pendente` : 'Todas as parcelas conhecidas'}
            subColor={k.parciais ? 'var(--warning)' : undefined} />
        </div>
      </div>

      <div style={gtpd.notaMargem}>{GT_PED_MARGEM_NOTA}</div>

      <GtPedTabela data={data} est={est} loading={loading} filtrado={filtrado} onOrdem={ordena} onLimpar={limpar}
        onPagina={n => muda({ pagina: n })} onAbrir={r => setAberto({ plataforma: r.plataforma, orderId: r.orderId })} />

      {aberto && <GtPedGaveta {...aberto} onClose={() => setAberto(null)} />}
      <FullLoadingOverlay show={fullLoading.show} conn="connecting" />
    </div>
  );
};

const gtpd = {
  // Em pares: 4 na linha, 2 + 2 ou 1 por linha, nunca 3 + 1.
  kpis: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 420px), 1fr))', gap: 14, marginBottom: 10 },
  notaMargem: { margin: '0 2px 16px', font: '500 11.5px/1.4 var(--font-sans)', color: 'var(--fg-3)' },
  kpiPar: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 180px), 1fr))', gap: 14 },
  conta: { padding: '1px 8px', lineHeight: '13px' },
  // O alinhamento vem do `left` calculado ao abrir; a largura casa com a conta de lá.
  menu: { right: 'auto', width: 320, maxWidth: 'calc(100vw - 32px)', maxHeight: 'none', overflow: 'visible' },
  menuBusca: { width: '100%', boxSizing: 'border-box', padding: '8px 10px', marginBottom: 5, border: '1px solid var(--border-1)', borderRadius: 'var(--r-sm)', font: 'var(--text-body-sm)', color: 'var(--fg-1)', outline: 'none' },
  menuLista: { maxHeight: 260, overflowY: 'auto' },
  menuNota: { padding: '8px 10px', font: '500 11.5px/1.4 var(--font-sans)', color: 'var(--fg-3)' },
  opt: { font: '600 12.5px/1.3 var(--font-sans)', padding: '7px 10px' },
  // Só shorthand: fb.mdBoxOn mistura com o `border` de fb.mdBox e o React avisa no console.
  caixaOn: { background: 'var(--fenix-orange)', border: '1.5px solid var(--fenix-orange)' },
  optTxt: { flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
  optNum: { font: '600 11.5px/1 var(--font-num)', color: 'var(--fg-3)', flex: 'none' },
  chips: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' },
  chip: { display: 'inline-flex', alignItems: 'center', gap: 6, maxWidth: 'min(100%, 340px)', border: 0, cursor: 'pointer', font: '600 12px/1.2 var(--font-sans)', color: 'var(--fenix-orange-600)', background: 'var(--fenix-orange-100)', borderRadius: 'var(--r-pill)', padding: '6px 10px' },
  chipTxt: { minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
  chipDim: { fontWeight: 500, color: 'var(--fg-2)' },
  thBtn: { border: 0, background: 'transparent', padding: 0, font: 'inherit', letterSpacing: 'inherit', textTransform: 'inherit', textAlign: 'inherit', color: 'inherit', cursor: 'pointer' },
  num: { fontFamily: 'var(--font-num)', fontVariantNumeric: 'tabular-nums' },
  id: { border: 0, background: 'transparent', padding: 0, cursor: 'pointer', font: '600 12px/1.3 var(--font-mono)', color: 'var(--fenix-blue)', textAlign: 'left', whiteSpace: 'nowrap' },
  ellSub: { font: '500 11.5px/1.3 var(--font-sans)', color: 'var(--fg-3)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
  tags: { display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 2 },
  tag: { font: '600 10.5px/1 var(--font-sans)', borderRadius: 'var(--r-pill)', padding: '4px 7px', whiteSpace: 'nowrap' },
  parcial: { display: 'inline-flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4 },

  fundo: { position: 'fixed', inset: 0, background: 'rgba(1,27,54,.45)', zIndex: 80, display: 'flex', justifyContent: 'flex-end' },
  painel: { width: 'min(440px, 100vw)', height: '100%', background: '#fff', boxShadow: 'var(--shadow-lg)', display: 'flex', flexDirection: 'column', outline: 'none' },
  gavetaMsg: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14, padding: '60px 10px', textAlign: 'center', font: 'var(--text-body-sm)', color: 'var(--fg-2)' },
  linhaTotal: { borderBottom: 0, paddingTop: 12 },
  kv: { display: 'flex', justifyContent: 'space-between', gap: 14, padding: '7px 0', borderBottom: '1px solid var(--border-1)' },
  k: { font: '500 12.5px/1.4 var(--font-sans)', color: 'var(--fg-3)', flex: 'none' },
  v: { font: '600 12.5px/1.4 var(--font-sans)', color: 'var(--fg-1)', textAlign: 'right', minWidth: 0, overflowWrap: 'anywhere' },
  vMono: { font: '500 12px/1.4 var(--font-mono)' },
};

window.GestaoPedidosView = GestaoPedidosView;
