const DSb = window.MyBrokerPantanalDesignSystem_2460cb;

function todayISOb() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
// Soma meses travando no último dia do mês de destino (dia 31 + 1 mês em fevereiro vira 28/29,
// nunca estoura pra março) — mesma lógica usada no resto do sistema pra data de vencimento.
function addMonthsISOb(iso, months) {
  if (!iso) return '';
  const [y, mo, d] = iso.split('-').map(Number);
  const totalMonths = mo - 1 + Number(months);
  const targetYear = y + Math.floor(totalMonths / 12);
  const targetMonth = ((totalMonths % 12) + 12) % 12;
  const lastDay = new Date(targetYear, targetMonth + 1, 0).getDate();
  const dt = new Date(targetYear, targetMonth, Math.min(d, lastDay));
  return `${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, '0')}-${String(dt.getDate()).padStart(2, '0')}`;
}
function addDaysISOb(iso, days) {
  if (!iso) return '';
  const [y, mo, d] = iso.split('-').map(Number);
  const dt = new Date(y, mo - 1, d + Number(days));
  return `${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, '0')}-${String(dt.getDate()).padStart(2, '0')}`;
}
function fmtDateBRb(iso) {
  if (!iso) return '';
  const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(iso);
  return m ? `${m[3]}/${m[2]}/${m[1]}` : iso;
}
function parseBRb(v) {
  if (!v) return 0;
  const n = parseFloat(String(v).replace(/\./g, '').replace(',', '.').replace(/[^\d.-]/g, ''));
  return isNaN(n) ? 0 : n;
}
function fmtMoneyB(n) {
  return (n || 0).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
}

// Gera (sem salvar em lugar nenhum) as cobranças mensais de uma locação, pra conseguir somar
// "recebido/a receber/vencido" aqui mesmo quando a locação nunca foi aberta — buildParcelas
// (em PropertyLocacoes.jsx) faz a mesma coisa, mas persistindo; aqui é só leitura.
function gerarCobrancasB(loc, aluguel) {
  if (loc.cobrancas) return loc.cobrancas;
  let base = loc.dataInicio || todayISOb();
  if (loc.diaVencimento) {
    const [y, mo] = base.split('-');
    base = `${y}-${mo}-${String(loc.diaVencimento).padStart(2, '0')}`;
  }
  const hoje = todayISOb();
  const nParcelas = loc.prazoMeses && loc.prazoMeses > 0 ? loc.prazoMeses : 12;
  const cobrancas = [];
  for (let i = 0; i < nParcelas; i++) {
    const venc = addMonthsISOb(base, i) || base;
    const isPrimeiraComCaucao = i === 0 && loc.garantia === 'Caução';
    const valor = isPrimeiraComCaucao ? aluguel * 4 : aluguel;
    cobrancas.push({ vencimento: venc, valor, status: venc < hoje ? 'Vencido' : 'A vencer' });
  }
  return cobrancas;
}

// Mesma ideia, mas pros repasses ao proprietário (lê se já existir persistido; senão gera só
// pra leitura aqui) — vence sempre 1 dia depois da cobrança do inquilino daquele mês.
function gerarRepassesB(loc, repasseLiquido) {
  if (loc.repasses) return loc.repasses;
  let base = loc.dataInicio || todayISOb();
  if (loc.diaVencimento) {
    const [y, mo] = base.split('-');
    base = `${y}-${mo}-${String(loc.diaVencimento).padStart(2, '0')}`;
  }
  const nParcelas = loc.prazoMeses && loc.prazoMeses > 0 ? loc.prazoMeses : 12;
  const repasses = [];
  for (let i = 0; i < nParcelas; i++) {
    const venc = addMonthsISOb(base, i) || base;
    const vencRepasse = addDaysISOb(venc, 1);
    repasses.push({ vencimento: vencRepasse, valor: repasseLiquido, status: 'A repassar' });
  }
  return repasses;
}

// Caixa de busca — digita o nome de um inquilino cadastrado e aparece tudo que ele tem em
// aberto (atrasado e a vencer), juntando todas as locações dele na carteira.
function BuscaInquilinoCard({ properties, onOpenLocacoes }) {
  const { Card, Input, ListItem, Badge } = DSb;
  const [q, setQ] = React.useState('');
  const [pessoa, setPessoa] = React.useState(null);
  const people = (window.MB_DATA && window.MB_DATA.people) || [];
  const hoje = todayISOb();

  const ql = q.trim().toLowerCase();
  const matches = !pessoa && ql.length > 0 ? people.filter((p) => (p.nome || '').toLowerCase().includes(ql)).slice(0, 8) : [];

  let itens = [];
  if (pessoa) {
    (properties || []).forEach((p) => {
      (p.locacoes || []).forEach((loc) => {
        if (loc.inquilinoPersonId !== pessoa.id) return;
        const aluguel = loc.valorAluguelAtual || parseBRb(p._form && p._form.valorAluguel);
        const cobrancas = gerarCobrancasB(loc, aluguel);
        cobrancas.forEach((c) => {
          if (c.status === 'Pago') return;
          itens.push({ property: p, loc, vencimento: c.vencimento, valor: c.valor, atrasado: c.vencimento < hoje });
        });
      });
    });
    itens.sort((a, b) => a.vencimento.localeCompare(b.vencimento));
  }
  const atrasados = itens.filter((i) => i.atrasado);
  const aVencer = itens.filter((i) => !i.atrasado);
  const totalAtrasado = atrasados.reduce((a, i) => a + i.valor, 0);
  const totalAVencer = aVencer.reduce((a, i) => a + i.valor, 0);

  return (
    <Card padding="lg" icon="search" tone="accent" title="Buscar inquilino" style={{ gap: 12, marginBottom: 16 }}>
      <div style={{ position: 'relative' }}>
        <Input placeholder="Buscar inquilino cadastrado pelo nome..." value={pessoa ? pessoa.nome : q}
          onChange={(e) => { setQ(e.target.value); setPessoa(null); }} />
        {matches.length > 0 && (
          <div style={{ position: 'absolute', zIndex: 20, top: '100%', left: 0, right: 0, marginTop: 4, background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 10, boxShadow: 'var(--shadow-md)', overflow: 'hidden', maxHeight: 240, overflowY: 'auto' }}>
            {matches.map((p) => (
              <ListItem key={p.id} variant="plain" title={p.nome} description={(p.tipos || [])[0] || ''}
                onClick={() => { setPessoa(p); setQ(''); }} style={{ cursor: 'pointer', padding: '8px 10px' }} />
            ))}
          </div>
        )}
      </div>

      {pessoa && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <div style={{ padding: '8px 10px', borderRadius: 10, background: 'var(--status-danger-bg)' }}>
              <div style={{ fontSize: 10, color: 'var(--status-danger-text)' }}>Atrasado ({atrasados.length})</div>
              <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--status-danger-text)' }}>{fmtMoneyB(totalAtrasado)}</div>
            </div>
            <div style={{ padding: '8px 10px', borderRadius: 10, background: 'var(--status-warning-bg)' }}>
              <div style={{ fontSize: 10, color: 'var(--status-warning-text)' }}>A vencer ({aVencer.length})</div>
              <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--status-warning-text)' }}>{fmtMoneyB(totalAVencer)}</div>
            </div>
          </div>
          {itens.length === 0 ? (
            <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{pessoa.nome} não tem aluguel em aberto cadastrado.</span>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 220, overflowY: 'auto' }}>
              {itens.map((i, idx) => (
                <div key={idx} onClick={() => onOpenLocacoes && onOpenLocacoes(i.property.id)}
                  style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '8px 10px', border: '1px solid var(--border-subtle)', borderRadius: 10, cursor: 'pointer' }}>
                  <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0 }}>
                    <span style={{ fontSize: 13, color: 'var(--text-strong)' }}>{i.property.name}</span>
                    <span style={{ fontSize: 11, color: i.atrasado ? 'var(--status-danger-text)' : 'var(--text-subtle)' }}>vence {fmtDateBRb(i.vencimento)}{i.atrasado ? ' · Vencido' : ''}</span>
                  </div>
                  <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-strong)' }}>{fmtMoneyB(i.valor)}</span>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </Card>
  );
}

// Fluxo de caixa da imobiliária, mês a mês (todas as locações, ativas e encerradas):
// entradas = aluguéis recebidos (sem a parte de caução, que fica retida) + valores pagos por terceiros à imobiliária;
// saídas = repasses feitos aos proprietários + despesas pagas a terceiros (manutenções etc.).
// O saldo é o lucro estimado (basicamente a taxa de administração menos o que a imobiliária bancou).
function fluxoImobiliariaB(props) {
  const por = {};
  const add = (iso, campo, v) => {
    if (!iso || !(v > 0)) return;
    const k = String(iso).slice(0, 7);
    por[k] = por[k] || { entradas: 0, saidas: 0, aRepassar: 0 };
    por[k][campo] += v;
  };
  (props || []).forEach((p) => (p.locacoes || []).forEach((loc) => {
    (loc.cobrancas || []).forEach((c, i) => {
      if (c.status !== 'Pago' || c.compensado) return;
      const v = Number(c.valor) || 0;
      add(c.dataPagamento || c.vencimento, 'entradas', c.caucao ? v / 4 : v);
      // parte do proprietário que ainda não foi repassada: não é lucro, é dinheiro dele em caixa
      const r = (loc.repasses || [])[i];
      if (r && r.status !== 'Repassado' && !r.compensado) add(c.dataPagamento || c.vencimento, 'aRepassar', Number(r.valor) || 0);
    });
    (loc.repasses || []).forEach((r) => {
      if (r.status !== 'Repassado' || r.compensado) return;
      add(r.dataRepasse || r.vencimento, 'saidas', Number(r.valor) || 0);
    });
    (loc.movimentacoes || []).forEach((mv) => {
      if (mv.status !== 'Pago') return;
      const v = Number(mv.valor) || 0;
      if (mv.destino === 'Terceiro') add(mv.dataPagamento || mv.dataVencimento, 'saidas', v);
      else if (mv.destino === 'Imobiliária' && mv.origem === 'Terceiro') add(mv.dataPagamento || mv.dataVencimento, 'entradas', v);
    });
  }));
  return por;
}

function LucroMesCard({ fluxo, mesAtual, m }) {
  const f = fluxo[mesAtual] || { entradas: 0, saidas: 0, aRepassar: 0 };
  const saldo = f.entradas - f.saidas - (f.aRepassar || 0);
  const nomeMes = new Date(mesAtual + '-15T12:00:00').toLocaleDateString('pt-BR', { month: 'long', year: 'numeric' });
  return (
    <div style={{ minWidth: m ? 0 : 300, width: m ? '100%' : undefined, padding: '14px 18px', borderRadius: 20, background: 'rgba(255,255,255,.55)', border: '1px solid rgba(255,255,255,.75)', boxShadow: '0 10px 30px rgba(15,23,42,.08)', backdropFilter: 'blur(16px) saturate(160%)', WebkitBackdropFilter: 'blur(16px) saturate(160%)', display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={{ fontSize: 11, fontWeight: 600, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Lucro estimado · {nomeMes}</span>
      <span style={{ fontSize: 26, fontWeight: 700, letterSpacing: '-0.02em', color: saldo < 0 ? 'var(--status-danger-text)' : 'var(--status-success-text)' }}>{fmtMoneyB(saldo)}</span>
      <div style={{ display: 'flex', gap: 14, fontSize: 12, color: 'var(--text-muted)' }}>
        <span>↓ Entrou <b style={{ color: 'var(--text-strong)' }}>{fmtMoneyB(f.entradas)}</b></span>
        <span>↑ Saiu <b style={{ color: 'var(--text-strong)' }}>{fmtMoneyB(f.saidas)}</b></span>
      </div>
      {f.aRepassar > 0 && <span style={{ fontSize: 11.5, color: 'var(--status-warning-text)' }}>Já descontado: {fmtMoneyB(f.aRepassar)} ainda a repassar aos proprietários</span>}
    </div>
  );
}

function LucroHistoricoCard({ fluxo, hoje, m }) {
  const { Card } = DSb;
  const meses = [];
  for (let i = 11; i >= 0; i--) {
    const iso = addMonthsISOb(hoje.slice(0, 7) + '-01', -i);
    const k = iso.slice(0, 7);
    const f = fluxo[k] || { entradas: 0, saidas: 0, aRepassar: 0 };
    const dt = new Date(k + '-15T12:00:00');
    const rot = dt.toLocaleDateString('pt-BR', { month: 'short' }).replace('.', '');
    meses.push({ k, rot: rot.charAt(0).toUpperCase() + rot.slice(1) + '/' + String(dt.getFullYear()).slice(2), ...f, saldo: f.entradas - f.saidas - (f.aRepassar || 0) });
  }
  const maxAbs = Math.max(1, ...meses.map((x) => Math.abs(x.saldo)));
  const temNeg = meses.some((x) => x.saldo < 0);
  const H = m ? 150 : 190;
  const hPos = temNeg ? H * 0.68 : H, hNeg = temNeg ? H * 0.32 : 0;
  const total = meses.reduce((a, x) => a + x.saldo, 0);
  const curto = (v) => { const a = Math.abs(v); const t = a >= 1000 ? (a / 1000).toLocaleString('pt-BR', { maximumFractionDigits: 1 }) + ' mil' : a.toLocaleString('pt-BR', { maximumFractionDigits: a < 10 ? 2 : 0 }); return (v < 0 ? '-' : '') + 'R$' + t; };
  return (
    <Card padding="lg" title="Lucro da imobiliária — últimos 12 meses" icon="trending-up" tone="success"
      action={<span style={{ fontSize: 12, color: 'var(--text-muted)' }}>Saldo no período: <b style={{ color: total < 0 ? 'var(--status-danger-text)' : 'var(--status-success-text)' }}>{fmtMoneyB(total)}</b></span>}
      style={{ gap: 12, marginBottom: 16 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: m ? 3 : 8, alignItems: 'end' }}>
        {meses.map((x) => {
          const h = Math.max(x.saldo === 0 ? 0 : 3, Math.abs(x.saldo) / maxAbs * (x.saldo >= 0 ? hPos : hNeg));
          return (
            <div key={x.k} title={`${x.rot}\nEntrou: ${fmtMoneyB(x.entradas)}\nSaiu: ${fmtMoneyB(x.saidas)}${x.aRepassar > 0 ? '\nA repassar: ' + fmtMoneyB(x.aRepassar) : ''}\nLucro: ${fmtMoneyB(x.saldo)}`} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', cursor: 'default' }}>
              <div style={{ height: hPos, width: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', alignItems: 'center' }}>
                {x.saldo > 0 && <span style={{ fontSize: m ? 8 : 10, fontWeight: 600, color: 'var(--status-success-text)', marginBottom: 3, whiteSpace: 'nowrap' }}>{curto(x.saldo)}</span>}
                {x.saldo > 0 && <div style={{ width: '70%', height: h, borderRadius: '6px 6px 2px 2px', background: 'linear-gradient(180deg,#22c55e,#16a34a)' }} />}
              </div>
              <div style={{ height: 1, width: '100%', background: 'var(--border-subtle, #e5e7eb)' }} />
              {temNeg && <div style={{ height: hNeg, width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                {x.saldo < 0 && <div style={{ width: '70%', height: h, borderRadius: '2px 2px 6px 6px', background: 'linear-gradient(180deg,#ef4444,#dc2626)' }} />}
                {x.saldo < 0 && <span style={{ fontSize: m ? 8 : 10, fontWeight: 600, color: 'var(--status-danger-text)', marginTop: 3, whiteSpace: 'nowrap' }}>{curto(x.saldo)}</span>}
              </div>}
              <span style={{ fontSize: m ? 9 : 11, color: 'var(--text-subtle)', marginTop: 6 }}>{x.rot}</span>
            </div>
          );
        })}
      </div>
      <span style={{ fontSize: 11, color: 'var(--text-subtle)' }}>Lucro do mês = aluguéis recebidos (pelo dia do pagamento) − repasses aos proprietários (feitos ou ainda a fazer) − despesas pagas a terceiros. Verde: lucro · vermelho: prejuízo. Passe o mouse numa barra para ver entradas e saídas.</span>
    </Card>
  );
}

function Billing({ mode, go, properties, setProperties, onOpenLocacoes }) {
  const { Card, IconButton, Button } = DSb;
  const m = mode === 'mobile';
  const props = properties || [];
  const hoje = todayISOb();
  const mesAtual = hoje.slice(0, 7);
  const mesAnteriorISO = addMonthsISOb(hoje, -1);
  const mesAnterior = mesAnteriorISO.slice(0, 7);
  const fluxo = React.useMemo(() => fluxoImobiliariaB(props), [props]);
  const [verFinanceiroDe, setVerFinanceiroDe] = React.useState(null);
  const [pixBilling, setPixBilling] = React.useState(null); // { property, loc, cobranca }
  const [pixRepasseB, setPixRepasseB] = React.useState(null); // lançamento de repasse com o QR do proprietário aberto
  const [pixDespesa, setPixDespesa] = React.useState(null); // despesa com o QR de pagamento aberto
  const [verTodosAtrasados, setVerTodosAtrasados] = React.useState(false);
  const [abaDespesas, setAbaDespesas] = React.useState('apagar');

  let recebidoMes = 0, aVencerMes = 0, vencidoMes = 0;
  let recebidoMesAnt = 0, aVencerMesAnt = 0, vencidoMesAnt = 0;
  const despesas = [];
  const lancamentos = [];
  const pagamentosInquilinos = [];

  props.forEach((p) => {
    (p.locacoes || []).forEach((loc) => {
      if (!loc.ativa) return;
      const aluguel = loc.valorAluguelAtual || parseBRb(p._form && p._form.valorAluguel);
      const pct = parseBRb(p._form && p._form.fields && p._form.fields.txAdm);
      const valorAdmFixo = parseBRb(p._form && p._form.fields && p._form.fields.valorAdm);
      const taxaAdmMensal = valorAdmFixo > 0 ? valorAdmFixo : aluguel * (pct / 100);
      const repasseLiquido = aluguel - taxaAdmMensal;
      const cobrancas = gerarCobrancasB(loc, aluguel);
      cobrancas.forEach((c) => {
        if (c.vencimento.slice(0, 7) === mesAtual) {
          if (c.status === 'Pago') recebidoMes += c.valor;
          else if (c.status === 'Vencido') vencidoMes += c.valor;
          else aVencerMes += c.valor;
        }
        if (c.vencimento.slice(0, 7) === mesAnterior) {
          if (c.status === 'Pago') recebidoMesAnt += c.valor;
          else if (c.status === 'Vencido') vencidoMesAnt += c.valor;
          else aVencerMesAnt += c.valor;
        }
      });
      // Inclui todos os aluguéis atrasados (ainda não pagos) dessa locação, mais o próximo em
      // aberto — não os meses seguintes, senão uma locação com muito contrato pela frente
      // sozinha ocuparia as vagas, deixando de fora as demais locações. Sem isso, locações com
      // vários meses em atraso nunca chegavam a mostrar o próximo aluguel (parava no mais antigo).
      for (let idx = 0; idx < cobrancas.length; idx++) {
        const c = cobrancas[idx];
        if (c.status === 'Pago') continue;
        const atrasado = c.vencimento < hoje;
        pagamentosInquilinos.push({
          key: `cob-${p.id}-${loc.id}-${idx}`,
          tipo: 'Aluguel',
          descricao: `Aluguel — ${loc.inquilino || 'locação'}`,
          valor: c.valor,
          data: c.vencimento,
          atrasado,
          podePagar: true,
          propertyName: p.name,
          property: p,
          loc,
          acaoPagar: () => marcarCobrancaPaga(p, loc, cobrancas, idx),
          pixParcela: c,
        });
        if (!atrasado) break;
      }
      (loc.movimentacoes || []).forEach((mv) => {
        if ((mv.destino === 'Terceiro' || mv.destino === 'Imobiliária') && mv.dataVencimento >= hoje) {
          despesas.push({ propertyId: p.id, propertyName: p.name, ...mv, _property: p, _loc: loc });
        }
        if (mv.status !== 'Pago') {
          // Quando sai do proprietário, o pagamento só pode ser liberado depois que o inquilino
          // já pagou o aluguel do mês correspondente (é esse aluguel que banca o repasse).
          let podePagar = true;
          if (mv.origem === 'Proprietário' && mv.dataVencimentoOrigem) {
            const cRel = cobrancas.find((c) => c.vencimento.slice(0, 7) === mv.dataVencimentoOrigem.slice(0, 7));
            if (cRel) podePagar = cRel.status === 'Pago';
          }
          lancamentos.push({
            key: `mov-${mv.id || ''}-${p.id}-${loc.id}`,
            tipo: 'Movimentação',
            descricao: mv.descricao,
            valor: mv.valor,
            data: mv.dataVencimento,
            atrasado: mv.dataVencimento < hoje,
            podePagar,
            propertyName: p.name,
            property: p,
            loc,
            acaoPagar: () => marcarMovimentacaoPaga(p, loc, mv.id),
          });
        }
      });
      // Inclui todos os repasses atrasados (ainda não repassados) dessa locação, mais o próximo
      // em aberto — não os meses seguintes, senão uma locação com muito contrato pela frente
      // sozinha ocuparia todas as vagas, deixando de fora as demais locações.
      const repasses = gerarRepassesB(loc, repasseLiquido);
      for (let idx = 0; idx < repasses.length; idx++) {
        const r = repasses[idx];
        if (r.status === 'Repassado') continue;
        const atrasado = r.vencimento < hoje;
        // O repasse só libera pagamento depois que o inquilino pagou o aluguel do mesmo mês.
        const cRel = cobrancas[idx];
        const podePagar = cRel ? cRel.status === 'Pago' : true;
        lancamentos.push({
          key: `rep-${p.id}-${loc.id}-${idx}`,
          tipo: 'Repasse ao proprietário',
          repasse: r,
          descricao: `Repasse — ${p.owner || 'proprietário'}`,
          valor: r.valor,
          data: r.vencimento,
          atrasado,
          podePagar,
          propertyName: p.name,
          property: p,
          loc,
          acaoPagar: (forma) => marcarRepassePago(p, loc, repasses, idx, forma),
        });
        if (!atrasado) break;
      }
    });
  });
  despesas.sort((a, b) => a.dataVencimento.localeCompare(b.dataVencimento));
  // Já pagas saem de "Próximas despesas" e vão para a aba "Pagas" (mais recentes primeiro).
  const despesasPagas = [];
  props.forEach((p) => (p.locacoes || []).forEach((loc) => (loc.movimentacoes || []).forEach((mv) => {
    if (mv.status === 'Pago' && (mv.destino === 'Terceiro' || mv.destino === 'Imobiliária')) despesasPagas.push({ propertyId: p.id, propertyName: p.name, ...mv, _property: p, _loc: loc });
  })));
  despesasPagas.sort((a, b) => String(b.dataPagamento || b.dataVencimento).localeCompare(String(a.dataPagamento || a.dataVencimento)));
  const despesasAPagar = despesas.filter((d) => d.status !== 'Pago');
  lancamentos.sort((a, b) => a.data.localeCompare(b.data));
  pagamentosInquilinos.sort((a, b) => a.data.localeCompare(b.data));
  // Três listas separadas: aluguéis dos inquilinos, lançamentos (movimentações/repasses) e
  // atrasados (dos dois juntos) — cada card mostra só a sua.
  const proximosPagamentosInquilinos = pagamentosInquilinos.filter((l) => !l.atrasado).slice(0, 20);
  const atrasadosTodos = [...lancamentos.filter((l) => l.atrasado), ...pagamentosInquilinos.filter((l) => l.atrasado)]
    .sort((a, b) => a.data.localeCompare(b.data));
  const atrasadosExibidos = verTodosAtrasados ? atrasadosTodos : atrasadosTodos.slice(0, 20);

  // Marca o aluguel como pago em dinheiro — garante que as cobranças fiquem persistidas na
  // locação (antes podiam só existir "ao vivo", geradas aqui pra leitura).
  const marcarCobrancaPaga = (property, loc, cobrancasBase, idx) => {
    setProperties((cur) => cur.map((p) => p.id !== property.id ? p : {
      ...p,
      locacoes: (p.locacoes || []).map((l) => {
        if (l.id !== loc.id) return l;
        const base = l.cobrancas || cobrancasBase;
        const k = window.mbCarimbo ? window.mbCarimbo('Dinheiro') : { em: new Date().toISOString(), forma: 'Dinheiro', por: null };
        return { ...l, cobrancas: base.map((c, i) => i !== idx || c.status === 'Pago' ? c : { ...c, status: 'Pago', dataPagamento: k.em, formaPagamento: k.forma, recebidoPor: k.por }) };
      }),
    }));
  };

  // Marca o repasse como repassado em dinheiro — garante que cobranças/repasses fiquem
  // persistidos na locação (antes podiam só existir "ao vivo", gerados aqui pra leitura).
  const marcarRepassePago = (property, loc, repassesBase, idx, forma) => {
    setProperties((cur) => cur.map((p) => p.id !== property.id ? p : {
      ...p,
      locacoes: (p.locacoes || []).map((l) => {
        if (l.id !== loc.id) return l;
        const base = l.repasses || repassesBase;
        const k = window.mbCarimbo ? window.mbCarimbo(forma || 'Dinheiro') : { em: new Date().toISOString(), forma: forma || 'Dinheiro', por: null };
        return { ...l, repasses: base.map((r, i) => i !== idx || r.status === 'Repassado' ? r : { ...r, status: 'Repassado', dataRepasse: k.em, formaRepasse: k.forma, repassadoPor: k.por }) };
      }),
    }));
  };
  const marcarMovimentacaoPaga = (property, loc, movId, forma) => {
    setProperties((cur) => cur.map((p) => p.id !== property.id ? p : {
      ...p,
      locacoes: (p.locacoes || []).map((l) => l.id !== loc.id ? l : {
        ...l, movimentacoes: (l.movimentacoes || []).map((mv) => {
          if (mv.id !== movId || mv.status === 'Pago') return mv;
          const k = window.mbCarimbo ? window.mbCarimbo(forma || 'Dinheiro') : { em: new Date().toISOString(), forma: forma || 'Dinheiro', por: null };
          return { ...mv, status: 'Pago', dataPagamento: k.em, formaPagamento: k.forma, pagoPor: k.por };
        }),
      }),
    }));
  };

  const LancamentoRow = ({ l }) => (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 10, background: 'var(--surface-sunken)', cursor: 'pointer' }}
      onClick={() => setVerFinanceiroDe({ property: l.property, loc: l.loc })}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
        <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--text-strong)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{l.descricao}</span>
        <span style={{ fontSize: 11, color: l.atrasado ? 'var(--status-danger-text)' : 'var(--text-subtle)' }}>{l.tipo} · {l.propertyName} · vence {fmtDateBRb(l.data)}</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4 }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-strong)', whiteSpace: 'nowrap' }}>{fmtMoneyB(l.valor)}</span>
        <div style={{ display: 'flex', gap: 4 }} onClick={(e) => e.stopPropagation()}>
          <IconButton icon="qr-code" label={l.pixParcela ? (l.pixParcela.pix && l.pixParcela.pix.status === 'ATIVA' ? 'Pix já enviado — ver QR' : 'Emitir cobrança por Pix') : l.repasse ? (l.podePagar ? 'Repassar via Pix (QR do proprietário)' : 'Aguardando o inquilino pagar o aluguel do mês') : 'Pix disponível só para aluguel e repasse'} size="sm" variant="soft"
            style={{ borderRadius: '50%', background: l.pixParcela && l.pixParcela.pix && l.pixParcela.pix.status === 'ATIVA' ? 'var(--status-info-bg)' : undefined, color: l.pixParcela && l.pixParcela.pix && l.pixParcela.pix.status === 'ATIVA' ? 'var(--status-info-text)' : undefined }}
            disabled={!l.pixParcela && !(l.repasse && l.podePagar)} onClick={() => { if (l.pixParcela) setPixBilling({ property: l.property, loc: l.loc, cobranca: l.pixParcela }); else if (l.repasse && l.podePagar) setPixRepasseB(l); }} />
          <IconButton icon="banknote" label={l.podePagar ? 'Pagar em dinheiro na imobiliária' : 'Aguardando o inquilino pagar o aluguel do mês'} size="sm" variant="soft"
            style={{ borderRadius: '50%' }} disabled={!l.podePagar} onClick={() => l.podePagar && window.mbConfirmarDinheiro({ titulo: 'Confirmar pagamento em dinheiro', detalhe: (l.descricao || '') + (l.propertyName ? ' · ' + l.propertyName : ''), valor: l.valor }).then((ok) => ok && l.acaoPagar())} />
        </div>
      </div>
    </div>
  );

  return (
    <div style={{ padding: m ? '16px' : 'var(--page-pad)' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16, marginBottom: 20 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <IconBadge icon="banknote" tone="success" size={m ? 36 : 44} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            <h1 style={{ margin: 0, fontSize: m ? 22 : 28, fontWeight: 600, letterSpacing: '-0.01em', color: 'var(--text-strong)' }}>Finanças</h1>
            <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>Visão consolidada de aluguéis e despesas de todas as locações ativas.</span>
          </div>
        </div>
        <LucroMesCard fluxo={fluxo} mesAtual={mesAtual} m={m} />
      </div>

      <BuscaInquilinoCard properties={props} onOpenLocacoes={onOpenLocacoes} />

      <LucroHistoricoCard fluxo={fluxo} hoje={hoje} m={m} />

      <div style={{ display: 'grid', gridTemplateColumns: m ? '1fr' : 'repeat(3, 1fr)', gap: 16 }}>
        <Card variant="dark" padding="lg" title="Aluguéis — mês atual" icon="calendar" style={{ gap: 14 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 12, color: 'rgba(255,255,255,.75)' }}>Recebido</span>
              <span style={{ fontSize: 17, fontWeight: 600, color: '#fff' }}>{fmtMoneyB(recebidoMes)}</span>
            </div>
            <div style={{ height: 1, background: 'rgba(255,255,255,.14)' }} />
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 12, color: 'rgba(255,255,255,.75)' }}>A receber</span>
              <span style={{ fontSize: 17, fontWeight: 600, color: '#fff' }}>{fmtMoneyB(aVencerMes)}</span>
            </div>
            <div style={{ height: 1, background: 'rgba(255,255,255,.14)' }} />
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 12, color: 'rgba(255,255,255,.75)' }}>Vencido</span>
              <span style={{ fontSize: 17, fontWeight: 600, color: vencidoMes > 0 ? 'var(--status-danger-text)' : '#fff' }}>{fmtMoneyB(vencidoMes)}</span>
            </div>
          </div>
        </Card>

        <Card variant="accent" padding="lg" title="Aluguéis — mês anterior" icon="calendar" style={{ gap: 14 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 12, color: 'rgba(255,255,255,.75)' }}>Recebido</span>
              <span style={{ fontSize: 17, fontWeight: 600, color: '#fff' }}>{fmtMoneyB(recebidoMesAnt)}</span>
            </div>
            <div style={{ height: 1, background: 'rgba(255,255,255,.22)' }} />
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 12, color: 'rgba(255,255,255,.75)' }}>A receber</span>
              <span style={{ fontSize: 17, fontWeight: 600, color: '#fff' }}>{fmtMoneyB(aVencerMesAnt)}</span>
            </div>
            <div style={{ height: 1, background: 'rgba(255,255,255,.22)' }} />
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 12, color: 'rgba(255,255,255,.75)' }}>Vencido</span>
              <span style={{ fontSize: 17, fontWeight: 600, color: '#fff' }}>{fmtMoneyB(vencidoMesAnt)}</span>
            </div>
          </div>
        </Card>

        <Card padding="lg" title="Despesas" icon="receipt" tone="warning"
          action={<div style={{ display: 'flex', gap: 4, padding: 3, borderRadius: 999, background: 'var(--surface-sunken)' }}>
            {[['apagar', `A pagar (${despesasAPagar.length})`], ['pagas', `Pagas (${despesasPagas.length})`]].map(([k, rot]) => (
              <button key={k} type="button" onClick={() => setAbaDespesas(k)} style={{ border: 0, cursor: 'pointer', padding: '4px 10px', borderRadius: 999, fontSize: 11.5, fontWeight: 600, fontFamily: 'inherit', background: abaDespesas === k ? 'var(--surface-raised, #fff)' : 'transparent', color: abaDespesas === k ? (k === 'pagas' ? 'var(--status-success-text)' : 'var(--status-warning-text)') : 'var(--text-muted)', boxShadow: abaDespesas === k ? '0 1px 3px rgba(15,23,42,.12)' : 'none' }}>{rot}</button>
            ))}
          </div>} style={{ gap: 10 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 220, overflowY: 'auto' }}>
            {(abaDespesas === 'pagas' ? despesasPagas : despesasAPagar).length === 0 ? (
              <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{abaDespesas === 'pagas' ? 'Nenhuma despesa paga ainda.' : 'Nenhuma despesa a pagar nas locações ativas.'}</span>
            ) : (abaDespesas === 'pagas' ? despesasPagas : despesasAPagar).map((d, i) => (
              <div key={d.id || i} onClick={() => onOpenLocacoes && onOpenLocacoes(d.propertyId)}
                style={{ display: 'flex', flexDirection: 'column', gap: 2, padding: '8px 10px', borderRadius: 10, background: 'var(--surface-sunken)', cursor: onOpenLocacoes ? 'pointer' : 'default' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--text-strong)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{d.descricao}</span>
                  <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-strong)', whiteSpace: 'nowrap' }}>{fmtMoneyB(d.valor)}</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontSize: 11, color: 'var(--text-subtle)' }}>{d.propertyName} · {d.status === 'Pago' ? 'venceu' : 'vence'} {fmtDateBRb(d.dataVencimento)}{d.destino === 'Terceiro' && d.destinoNome ? ` · para ${d.destinoNome}` : d.destino === 'Imobiliária' ? ' · para a imobiliária' : ''}</span>
                  {d.status !== 'Pago' && d.destino === 'Terceiro' && (
                    <span onClick={(e) => e.stopPropagation()}>
                      <IconButton icon="qr-code" label={`Pagar por Pix${d.destinoNome ? ' — ' + d.destinoNome : ''}`} size="sm" variant="soft" style={{ borderRadius: '50%' }} onClick={() => setPixDespesa(d)} />
                    </span>
                  )}
                  {d.status === 'Pago' && <span style={{ fontSize: 11, color: 'var(--status-success-text)', textAlign: 'right', whiteSpace: 'nowrap' }}>✓ Pago{d.dataPagamento ? ' em ' + window.mbFmtDataHora(d.dataPagamento) : ''}{d.formaPagamento ? ' · ' + d.formaPagamento : ''}</span>}
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      <div style={{ marginTop: 16, display: 'grid', gridTemplateColumns: m ? '1fr' : '1fr 1fr', gap: 16 }}>
        <Card padding="lg" title="Próximos pagamentos de inquilinos" icon="users" tone="accent" action={<span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{proximosPagamentosInquilinos.length}</span>}
          style={{ gap: 10 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 520, overflowY: 'auto' }}>
            {proximosPagamentosInquilinos.length === 0 ? (
              <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>Nenhum aluguel em aberto nas locações ativas.</span>
            ) : proximosPagamentosInquilinos.map((l) => <LancamentoRow key={l.key} l={l} />)}
          </div>
        </Card>

        <Card padding="lg" title="Atrasados" icon="circle-alert" tone="danger" action={<span style={{ fontSize: 12, color: 'var(--status-danger-text)' }}>{atrasadosTodos.length}</span>}
          style={{ gap: 10 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 520, overflowY: 'auto' }}>
            {atrasadosExibidos.length === 0 ? (
              <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>Nenhum lançamento atrasado nas locações ativas.</span>
            ) : atrasadosExibidos.map((l) => <LancamentoRow key={l.key} l={l} />)}
            {!verTodosAtrasados && atrasadosTodos.length > 20 && (
              <Button variant="secondary" size="sm" onClick={() => setVerTodosAtrasados(true)}>Ver todos atrasados</Button>
            )}
          </div>
        </Card>
      </div>

      {verFinanceiroDe && (
        <window.FinanceiroDialog
          property={verFinanceiroDe.property}
          loc={verFinanceiroDe.loc}
          setProperties={setProperties}
          onClose={() => setVerFinanceiroDe(null)}
        />
      )}
      {pixDespesa && window.PixPagarDialog && (
        <window.PixPagarDialog titulo="Pagar despesa por Pix" descricao={`${pixDespesa.descricao} · ${pixDespesa.propertyName} · venc. ${fmtDateBRb(pixDespesa.dataVencimento)}`}
          valor={pixDespesa.valor} nomeBeneficiario={pixDespesa.destinoNome} personId={pixDespesa.destinoPersonId}
          txidRef={'DESP' + String(pixDespesa.id || '').replace(/\D/g, '').slice(-12)} textoPix={String(pixDespesa.descricao || 'Despesa').slice(0, 40)}
          pago={pixDespesa.status === 'Pago'} pagoEm={pixDespesa.dataPagamento}
          onPago={(forma) => marcarMovimentacaoPaga(pixDespesa._property, pixDespesa._loc, pixDespesa.id, forma)}
          onClose={() => setPixDespesa(null)} />
      )}
      {pixRepasseB && window.PixRepasseDialog && (
        <window.PixRepasseDialog property={pixRepasseB.property} loc={pixRepasseB.loc} repasse={pixRepasseB.repasse}
          onMarcarRepassado={(forma) => pixRepasseB.acaoPagar(forma)} onClose={() => setPixRepasseB(null)} />
      )}
      {pixBilling && window.PixCobrancaDialog && (
        <window.PixCobrancaDialog property={pixBilling.property} loc={pixBilling.loc} cobranca={pixBilling.cobranca}
          setProperties={setProperties} onClose={() => setPixBilling(null)} />
      )}
    </div>
  );
}

window.Billing = Billing;
