// Cobrança Pix de uma parcela de aluguel (integração com o Worker mybroker-pix via API).
// A API gera a cobrança no BB com o valor da parcela gravado no banco e devolve o copia-e-cola.
// Esta janela mostra o QR, permite copiar / baixar / mandar no WhatsApp e acompanha o pagamento:
// quando o Pix cai, a parcela vira "Pago" sozinha (a baixa é feita no servidor).
const PIX_API = 'https://api.mybrokerpantanal.com.br';

// Carimbo de pagamento/repasse: data e hora exatas + forma + quem marcou (vai para relatórios).
window.mbCarimbo = function (forma) {
  const u = (window.MB_DATA && window.MB_DATA.user) || {};
  return { em: new Date().toISOString(), forma: forma || 'Dinheiro', por: u.nome || u.name || u.email || null };
};
window.mbFmtDataHora = function (iso) {
  if (!iso) return '';
  const d = new Date(iso);
  if (isNaN(d)) return String(iso);
  return d.toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' });
};

function pixFmtMoney(v) {
  return Number(v || 0).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
}
function pixFmtData(iso) {
  if (!iso) return '';
  const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(iso);
  return m ? `${m[3]}/${m[2]}/${m[1]}` : iso;
}
function pixFmtDataHora(iso) {
  if (!iso) return '';
  const d = new Date(iso);
  if (isNaN(d)) return iso;
  return d.toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' });
}
function pixQrDataUrl(texto) {
  try {
    const qr = window.qrcode(0, 'M');
    qr.addData(texto);
    qr.make();
    return qr.createDataURL(8, 16);
  } catch (e) {
    return null;
  }
}
async function pixPost(caminho, corpo) {
  const r = await fetch(PIX_API + caminho, {
    method: 'POST', credentials: 'include',
    headers: { 'content-type': 'application/json' }, body: JSON.stringify(corpo),
  });
  const j = await r.json().catch(() => ({}));
  if (!r.ok) throw new Error(j.erro || `Erro ${r.status}`);
  return j;
}
function pixTelefoneInquilino(loc) {
  const pessoas = (window.MB_DATA && window.MB_DATA.people) || [];
  const p = pessoas.find((x) => x.id === loc.inquilinoPersonId) || pessoas.find((x) => x.nome && loc.inquilino && x.nome.trim().toLowerCase() === loc.inquilino.trim().toLowerCase());
  if (!p) return '';
  const tel = String(p.telefoneCelular || p.celular || p.phone || p.telefoneResidencia || p.telefoneComercial || '').replace(/\D/g, '');
  if (!tel) return '';
  return tel.length <= 11 ? '55' + tel : tel;
}

function PixCobrancaDialog({ property, loc, cobranca, setProperties, onClose }) {
  const { Dialog, Button, Badge } = DSpl;
  const [fase, setFase] = React.useState('gerando'); // gerando | pronto | pago | erro
  const [pix, setPix] = React.useState(null);
  const [erro, setErro] = React.useState('');
  const [aviso, setAviso] = React.useState('');
  const [simulando, setSimulando] = React.useState(false);
  const vivo = React.useRef(true);
  React.useEffect(() => () => { vivo.current = false; }, []);

  // Troca o imóvel na tela pela versão do servidor (já com o bloco "pix" e, se for o caso, o "Pago").
  const aplicarImovel = (imovel) => {
    if (!imovel || !setProperties) return;
    setProperties((cur) => cur.map((p) => p.id === imovel.id ? imovel : p));
  };
  const recarregarImovel = async () => {
    try {
      const r = await fetch(PIX_API + '/api/imoveis', { credentials: 'include' });
      if (!r.ok) return;
      const lista = await r.json();
      aplicarImovel(lista.find((p) => p.id === property.id));
    } catch (e) { /* a tela continua; o F5 traz o dado certo */ }
  };

  const gerar = async (tentativa = 1) => {
    setFase('gerando'); setErro('');
    try {
      const j = await pixPost('/api/pix/cobrar', { imovelId: property.id, locacaoId: loc.id, mes: cobranca.mes });
      if (!vivo.current) return;
      setPix(j.pix);
      setFase('pronto');
      aplicarImovel(j.imovel);
    } catch (e) {
      // Parcelas recém-criadas na tela podem levar um instante para chegar ao servidor.
      if (tentativa < 3 && /não encontrad/i.test(e.message)) {
        setTimeout(() => vivo.current && gerar(tentativa + 1), 1500);
        return;
      }
      if (!vivo.current) return;
      setErro(e.message); setFase('erro');
    }
  };

  React.useEffect(() => {
    if (cobranca.pix && cobranca.pix.status === 'PAGA') { setPix(cobranca.pix); setFase('pago'); return; }
    gerar();
  }, []);

  // Acompanha o pagamento a cada 5 s enquanto a janela estiver aberta.
  React.useEffect(() => {
    if (fase !== 'pronto' || !pix || !pix.txid) return;
    const t = setInterval(async () => {
      try {
        const j = await pixPost('/api/pix/consultar', { txid: pix.txid });
        const r = j.resultado || {};
        if (r.status === 'PAGA') {
          clearInterval(t);
          if (!vivo.current) return;
          setPix((p) => ({ ...p, status: 'PAGA', e2eid: r.pago && r.pago.e2eid, pagoEm: r.pago && r.pago.horario, valorPago: r.pago && Number(r.pago.valor), pagadorNome: r.pago && r.pago.pagador && r.pago.pagador.nome }));
          setFase('pago');
          setTimeout(recarregarImovel, 1500);
        } else if (r.status === 'EXPIRADA' || r.status === 'CANCELADA') {
          clearInterval(t);
          if (vivo.current) { setErro(`A cobrança ficou ${r.status.toLowerCase()}. Gere uma nova.`); setFase('erro'); }
        }
      } catch (e) { /* tenta de novo no próximo ciclo */ }
    }, 5000);
    return () => clearInterval(t);
  }, [fase, pix && pix.txid]);

  const copiar = async () => {
    try { await navigator.clipboard.writeText(pix.copiaECola); setAviso('Pix Copia e Cola copiado!'); }
    catch (e) { setAviso('Não consegui copiar — selecione o código e copie manualmente.'); }
    setTimeout(() => vivo.current && setAviso(''), 3000);
  };
  const qrUrl = pix && pix.copiaECola ? pixQrDataUrl(pix.copiaECola) : null;
  const baixarQr = () => {
    if (!qrUrl) return;
    const a = document.createElement('a');
    a.href = qrUrl;
    a.download = `pix-${(property.name || 'imovel').replace(/[^\w-]+/g, '_')}-${String(cobranca.mes).replace('/', '-')}.gif`;
    document.body.appendChild(a); a.click(); a.remove();
  };
  const tel = pixTelefoneInquilino(loc);
  const enc = pix && pix.encargos;
  const valorCobrado = pix && pix.valor ? Number(pix.valor) : cobranca.valor;
  const enviarWhats = () => {
    const msg = `Olá${loc.inquilino ? ', ' + loc.inquilino.split(' ')[0] : ''}! Segue o Pix do aluguel de ${cobranca.mes} (${property.name}), no valor de ${pixFmtMoney(valorCobrado)}${enc ? ` (aluguel ${pixFmtMoney(enc.original)} + multa ${pixFmtMoney(enc.multa)} + juros ${pixFmtMoney(enc.juros)} por ${enc.dias} dia(s) de atraso)` : ''}, vencimento ${pixFmtData(cobranca.vencimento)}.\n\nPix Copia e Cola:\n${pix.copiaECola}\n\nAssim que o pagamento cair, a baixa é automática. MyBroker Pantanal`;
    window.open(`https://wa.me/${tel}?text=${encodeURIComponent(msg)}`, '_blank', 'noopener');
  };
  const simular = async () => {
    setSimulando(true);
    try { await pixPost('/api/pix/simular', { txid: pix.txid }); setAviso('Pagamento de teste enviado ao BB — aguarde alguns segundos.'); }
    catch (e) { setAviso('Simulação: ' + e.message); }
    setSimulando(false);
  };

  const sandbox = pix && pix.ambiente === 'sandbox';
  return (
    <Dialog open onClose={onClose} size="sm" strategy="absolute" placement="center" icon="qr-code" tone={fase === 'pago' ? 'success' : 'accent'}
      title={fase === 'pago' ? 'Aluguel pago via Pix' : 'Cobrança por Pix'}
      description={`${property.name} · ${cobranca.mes} · ${loc.inquilino || 'Inquilino'}`}
      footer={<Button variant="secondary" onClick={onClose}>Fechar</Button>}>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12, textAlign: 'center' }}>
        <div style={{ display: 'flex', gap: 18, justifyContent: 'center' }}>
          <div><div style={{ fontSize: 11, color: 'var(--text-muted)' }}>{enc ? 'Valor com encargos' : 'Valor'}</div><div style={{ fontSize: 20, fontWeight: 700, color: enc ? 'var(--status-danger-text)' : 'var(--text-strong)' }}>{pixFmtMoney(valorCobrado)}</div></div>
          <div><div style={{ fontSize: 11, color: 'var(--text-muted)' }}>Vencimento</div><div style={{ fontSize: 20, fontWeight: 700, color: 'var(--text-strong)' }}>{pixFmtData(cobranca.vencimento)}</div></div>
        </div>
        {enc && <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>Aluguel {pixFmtMoney(enc.original)} + multa {enc.multaPerc}% {pixFmtMoney(enc.multa)} + juros {enc.jurosMesPerc}% a.m. ({enc.dias} dia{enc.dias === 1 ? '' : 's'}) {pixFmtMoney(enc.juros)}. Este QR vale até o fim de hoje; amanhã os juros mudam.</span>}

        {fase === 'gerando' && <div style={{ padding: '60px 0', fontSize: 13, color: 'var(--text-muted)' }}>Gerando a cobrança no Banco do Brasil…</div>}

        {fase === 'erro' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, alignItems: 'center', padding: '24px 0' }}>
            <span style={{ fontSize: 13, color: 'var(--status-danger-text)' }}>{erro}</span>
            <Button icon="refresh-cw" onClick={() => gerar()}>Tentar de novo</Button>
          </div>
        )}

        {fase === 'pronto' && pix && (
          <>
            {sandbox && <Badge tone="warning" size="sm">Ambiente de teste do BB — não use para cobrança real</Badge>}
            {qrUrl
              ? <img src={qrUrl} alt="QR Code Pix" style={{ width: 240, height: 240, imageRendering: 'pixelated', borderRadius: 12, background: '#fff', padding: 8, border: '1px solid var(--border-subtle, #e5e7eb)' }} />
              : <span style={{ fontSize: 12, color: 'var(--status-warning-text)' }}>Não consegui desenhar o QR — use o Copia e Cola abaixo.</span>}
            <span style={{ fontSize: 12, color: 'var(--status-info-text)' }}>Aguardando pagamento… a baixa é automática.</span>
            <textarea readOnly value={pix.copiaECola} onFocus={(e) => e.target.select()}
              style={{ width: '100%', height: 64, fontSize: 11, fontFamily: 'ui-monospace, monospace', borderRadius: 10, padding: 8, border: '1px solid var(--border-subtle, #e5e7eb)', background: 'var(--surface-sunken)', resize: 'none' }} />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, width: '100%' }}>
              <Button icon="check" onClick={copiar}>Copiar Pix</Button>
              <Button variant="secondary" icon="download" onClick={baixarQr} disabled={!qrUrl}>Baixar QR</Button>
            </div>
            <Button variant="secondary" icon="external-link" onClick={enviarWhats} style={{ width: '100%' }}>
              {tel ? 'Enviar no WhatsApp do inquilino' : 'Enviar no WhatsApp (escolher contato)'}
            </Button>
            {sandbox && <Button variant="ghost" size="sm" onClick={simular} disabled={simulando}>{simulando ? 'Simulando…' : 'Simular pagamento (apenas teste)'}</Button>}
            {aviso && <span style={{ fontSize: 12, color: 'var(--status-success-text)' }}>{aviso}</span>}
            <span style={{ fontSize: 10, color: 'var(--text-subtle)' }}>Válido até {pixFmtDataHora(pix.expiraEm)} · id {pix.txid}</span>
          </>
        )}

        {fase === 'pago' && pix && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'center', padding: '16px 0' }}>
            <div style={{ fontSize: 44, lineHeight: 1, color: 'var(--status-success-text)' }}>✓</div>
            <span style={{ fontSize: 15, fontWeight: 600, color: 'var(--status-success-text)' }}>Pagamento confirmado pelo banco</span>
            <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{pixFmtDataHora(pix.pagoEm)}{pix.valorPago ? ' · ' + pixFmtMoney(pix.valorPago) : ''}</span>
            {pix.pagadorNome && <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>Pago por {pix.pagadorNome}{pix.pagadorDoc ? ' (' + pix.pagadorDoc + ')' : ''}</span>}
            {pix.divergente && <span style={{ fontSize: 12, color: 'var(--status-warning-text)' }}>Atenção: valor pago diferente do cobrado.</span>}
            {pix.e2eid && <span style={{ fontSize: 10, color: 'var(--text-subtle)', fontFamily: 'ui-monospace, monospace' }}>E2E {pix.e2eid}</span>}
            <span style={{ fontSize: 11, color: 'var(--text-subtle)' }}>A parcela já foi marcada como paga no sistema.</span>
          </div>
        )}
      </div>
    </Dialog>
  );
}
window.PixCobrancaDialog = PixCobrancaDialog;

// ---------------------------------------------------------------------------------------------
// Repasse ao proprietário: QR Code "estático" (padrão BR Code do Banco Central) com a chave Pix
// do proprietário cadastrada em Pessoas e o valor do repasse — você escaneia no app do banco da
// imobiliária e paga. Saída de dinheiro não tem confirmação automática: depois de pagar, use
// "Já paguei — marcar como repassado".
function pixSemAcento(s) {
  return String(s || '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[^A-Za-z0-9 .\-]/g, ' ').replace(/\s+/g, ' ').trim().toUpperCase();
}
function pixCpfValido(c) {
  if (!/^\d{11}$/.test(c) || /^(\d)\1{10}$/.test(c)) return false;
  for (let t = 9; t < 11; t++) {
    let s = 0;
    for (let i = 0; i < t; i++) s += Number(c[i]) * (t + 1 - i);
    if (((s * 10) % 11) % 10 !== Number(c[t])) return false;
  }
  return true;
}
// Normaliza a chave como o Pix espera e diz de que tipo ela é.
function pixNormalizarChave(bruta) {
  const k = String(bruta || '').trim();
  if (!k) return null;
  if (k.includes('@')) return { chave: k.toLowerCase(), tipo: 'E-mail' };
  if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(k)) return { chave: k.toLowerCase(), tipo: 'Chave aleatória' };
  const d = k.replace(/\D/g, '');
  if (k.startsWith('+')) return { chave: '+' + d, tipo: 'Celular' };
  if (d.length === 14) return { chave: d, tipo: 'CNPJ' };
  if (d.length === 11 && pixCpfValido(d)) return { chave: d, tipo: 'CPF' };
  if (d.length === 10 || d.length === 11) return { chave: '+55' + d, tipo: 'Celular' };
  if (d.length === 12 || d.length === 13) return { chave: '+' + d, tipo: 'Celular' };
  return { chave: k, tipo: 'Não reconhecida — confira' };
}
function pixCrc16(str) {
  let crc = 0xffff;
  for (let i = 0; i < str.length; i++) {
    crc ^= str.charCodeAt(i) << 8;
    for (let j = 0; j < 8; j++) crc = (crc & 0x8000) ? ((crc << 1) ^ 0x1021) & 0xffff : (crc << 1) & 0xffff;
  }
  return crc.toString(16).toUpperCase().padStart(4, '0');
}
function pixCampo(id, valor) {
  const v = String(valor);
  return id + String(v.length).padStart(2, '0') + v;
}
function pixBrCodeEstatico({ chave, nome, cidade, valor, txid, descricao }) {
  const conta = pixCampo('00', 'br.gov.bcb.pix') + pixCampo('01', chave) + (descricao ? pixCampo('02', descricao.slice(0, 40)) : '');
  const corpo = pixCampo('00', '01') + pixCampo('26', conta) + pixCampo('52', '0000') + pixCampo('53', '986') +
    (valor ? pixCampo('54', Number(valor).toFixed(2)) : '') + pixCampo('58', 'BR') +
    pixCampo('59', pixSemAcento(nome).slice(0, 25) || 'RECEBEDOR') + pixCampo('60', pixSemAcento(cidade).slice(0, 15) || 'CACERES') +
    pixCampo('62', pixCampo('05', (txid || '***').replace(/[^A-Za-z0-9]/g, '').slice(0, 25) || '***')) + '6304';
  return corpo + pixCrc16(corpo);
}
window.pixBrCodeEstatico = pixBrCodeEstatico;
window.pixCrc16 = pixCrc16;

// Auditoria 17/11/2026 (A1): se a chave Pix de quem recebe foi alterada há pouco, avisa antes de pagar.
function pixAlertaChaveRecente(p) {
  if (!p || !p.chavePixAlteradaEm) return null;
  const t = Date.parse(p.chavePixAlteradaEm);
  if (!t || Date.now() - t > 30 * 86400000) return null;
  return `Atenção: a chave Pix de ${p.nome || 'quem recebe'} foi alterada em ${new Date(t).toLocaleString('pt-BR')}${p.chavePixAlteradaPor ? ' por ' + p.chavePixAlteradaPor : ''}. Confirme a chave com a pessoa (por telefone) antes de pagar.`;
}
window.pixAlertaChaveRecente = pixAlertaChaveRecente;

function PixRepasseDialog({ property, loc, repasse, onMarcarRepassado, onClose }) {
  const { Dialog, Button, Badge } = DSpl;
  const [aviso, setAviso] = React.useState('');
  const pessoas = (window.MB_DATA && window.MB_DATA.people) || [];
  const owners = ((property._form && property._form.owners) || []).filter((o) => o.nome || o.personId);
  const lista = (owners.length ? owners : [{ nome: property.owner || 'Proprietário', personId: null, percentual: '100' }]).map((o) => {
    const p = pessoas.find((x) => x.id === o.personId) || pessoas.find((x) => x.nome && o.nome && x.nome.trim().toLowerCase() === o.nome.trim().toLowerCase());
    const pct = parseFloat(String(o.percentual || '').replace(',', '.'));
    const valor = owners.length > 1 && pct > 0 ? Math.round(repasse.valor * pct) / 100 : repasse.valor;
    const k = pixNormalizarChave(p && p.chavePix);
    const nome = (p && p.nome) || o.nome || 'Proprietário';
    const cidade = (p && p.endereco && p.endereco.cidade) || 'Caceres';
    const codigo = k ? pixBrCodeEstatico({ chave: k.chave, nome, cidade, valor, txid: 'REP' + String(repasse.mes).replace(/\W/g, ''), descricao: `Repasse ${repasse.mes}` }) : null;
    return { nome, pct: owners.length > 1 ? pct : null, valor, k, codigo, qr: codigo ? pixQrDataUrl(codigo) : null, alerta: pixAlertaChaveRecente(p) };
  });
  const copiar = async (t) => {
    try { await navigator.clipboard.writeText(t); setAviso('Pix Copia e Cola copiado!'); } catch (e) { setAviso('Selecione o código e copie manualmente.'); }
    setTimeout(() => setAviso(''), 3000);
  };
  const jaRepassado = repasse.status === 'Repassado';
  return (
    <Dialog open onClose={onClose} size="sm" strategy="absolute" placement="center" icon="qr-code" tone={jaRepassado ? 'success' : 'accent'}
      title={jaRepassado ? `Repassado${repasse.dataRepasse ? ' em ' + window.mbFmtDataHora(repasse.dataRepasse) : ''}` : 'Pagar repasse por Pix'}
      description={`${property.name} · ${repasse.mes} · venc. ${pixFmtData(repasse.vencimento)}`}
      footer={<>
        <Button variant="secondary" onClick={onClose}>Fechar</Button>
        {!jaRepassado && onMarcarRepassado && <Button icon="check" onClick={() => { onMarcarRepassado('Pix'); onClose(); }}>Pago agora</Button>}
      </>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <span style={{ fontSize: 12, color: 'var(--text-muted)', textAlign: 'center' }}>
          {jaRepassado ? `Repasse já registrado${repasse.formaRepasse ? ' via ' + repasse.formaRepasse : ''}${repasse.repassadoPor ? ' por ' + repasse.repassadoPor : ''}.` : 'Escaneie no app do banco da imobiliária (ou use o Copia e Cola), confira nome e valor e pague. Depois clique em "Pago agora".'}
        </span>
        {lista.map((o, idx) => (
          <div key={idx} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, padding: 12, borderRadius: 12, background: 'var(--surface-sunken)', textAlign: 'center' }}>
            <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-strong)' }}>{o.nome}{o.pct ? ` · ${o.pct}%` : ''}</span>
            <span style={{ fontSize: 20, fontWeight: 700, color: 'var(--text-strong)' }}>{pixFmtMoney(o.valor)}</span>
            {o.k ? (
              <>
                <span style={{ fontSize: 11, color: 'var(--text-subtle)' }}>Chave Pix ({o.k.tipo}): {o.k.chave}</span>
                {o.alerta && <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--status-danger-text)', background: 'var(--status-danger-bg, #fde8e8)', padding: '6px 10px', borderRadius: 8 }}>⚠ {o.alerta}</span>}
                {o.qr && <img src={o.qr} alt={`QR Pix ${o.nome}`} style={{ width: 210, height: 210, imageRendering: 'pixelated', borderRadius: 12, background: '#fff', padding: 8 }} />}
                <Button variant="secondary" icon="check" onClick={() => copiar(o.codigo)}>Copiar Pix Copia e Cola</Button>
              </>
            ) : (
              <span style={{ fontSize: 12, color: 'var(--status-warning-text)' }}>Este proprietário não tem chave Pix cadastrada. Cadastre em Pessoas → editar → "Chave Pix" e abra de novo.</span>
            )}
          </div>
        ))}
        {aviso && <span style={{ fontSize: 12, color: 'var(--status-success-text)', textAlign: 'center' }}>{aviso}</span>}
      </div>
    </Dialog>
  );
}
window.PixRepasseDialog = PixRepasseDialog;

// ---------------------------------------------------------------------------------------------
// Pagamento de despesa (movimentação) a um terceiro: QR estático com a chave Pix de quem recebe.
function PixPagarDialog({ titulo, descricao, valor, nomeBeneficiario, personId, txidRef, textoPix, pago, pagoEm, onPago, onClose }) {
  const { Dialog, Button } = DSpl;
  const [aviso, setAviso] = React.useState('');
  const pessoas = (window.MB_DATA && window.MB_DATA.people) || [];
  const p = pessoas.find((x) => x.id === personId) || pessoas.find((x) => x.nome && nomeBeneficiario && x.nome.trim().toLowerCase() === nomeBeneficiario.trim().toLowerCase());
  const k = pixNormalizarChave(p && p.chavePix);
  const nome = (p && p.nome) || nomeBeneficiario || 'Beneficiário';
  const codigo = k ? pixBrCodeEstatico({ chave: k.chave, nome, cidade: (p && p.endereco && p.endereco.cidade) || 'Caceres', valor, txid: txidRef, descricao: textoPix }) : null;
  const qr = codigo ? pixQrDataUrl(codigo) : null;
  const copiar = async () => {
    try { await navigator.clipboard.writeText(codigo); setAviso('Pix Copia e Cola copiado!'); } catch (e) { setAviso('Selecione o código e copie manualmente.'); }
    setTimeout(() => setAviso(''), 3000);
  };
  return (
    <Dialog open onClose={onClose} size="sm" strategy="absolute" placement="center" icon="qr-code" tone={pago ? 'success' : 'accent'}
      title={pago ? `Pago${pagoEm ? ' em ' + window.mbFmtDataHora(pagoEm) : ''}` : titulo} description={descricao}
      footer={<>
        <Button variant="secondary" onClick={onClose}>Fechar</Button>
        {!pago && onPago && <Button icon="check" onClick={() => { onPago('Pix'); onClose(); }}>Pago agora</Button>}
      </>}>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, textAlign: 'center' }}>
        <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{pago ? 'Pagamento já registrado.' : 'Escaneie no app do banco da imobiliária (ou use o Copia e Cola), confira nome e valor e pague. Depois clique em "Pago agora".'}</span>
        <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-strong)' }}>{nome}</span>
        <span style={{ fontSize: 20, fontWeight: 700, color: 'var(--text-strong)' }}>{pixFmtMoney(valor)}</span>
        {k ? (
          <>
            <span style={{ fontSize: 11, color: 'var(--text-subtle)' }}>Chave Pix ({k.tipo}): {k.chave}</span>
            {pixAlertaChaveRecente(p) && <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--status-danger-text)', background: 'var(--status-danger-bg, #fde8e8)', padding: '6px 10px', borderRadius: 8 }}>⚠ {pixAlertaChaveRecente(p)}</span>}
            {qr && <img src={qr} alt={`QR Pix ${nome}`} style={{ width: 210, height: 210, imageRendering: 'pixelated', borderRadius: 12, background: '#fff', padding: 8 }} />}
            <Button variant="secondary" icon="check" onClick={copiar}>Copiar Pix Copia e Cola</Button>
          </>
        ) : (
          <span style={{ fontSize: 12, color: 'var(--status-warning-text)' }}>
            {p ? 'Esta pessoa não tem chave Pix cadastrada. Cadastre em Pessoas → editar → "Chave Pix" e abra de novo.' : 'Quem recebe esta despesa não está vinculado a um cadastro em Pessoas — vincule a pessoa na movimentação ou cadastre a chave Pix.'}
          </span>
        )}
        {aviso && <span style={{ fontSize: 12, color: 'var(--status-success-text)' }}>{aviso}</span>}
      </div>
    </Dialog>
  );
}
window.PixPagarDialog = PixPagarDialog;
