const DSd = window.MyBrokerPantanalDesignSystem_2460cb;
const DONUT_DOT = { accent: 'var(--action-accent)', dark: 'var(--mb-black)', muted: 'var(--mb-gray-300)', soft: 'var(--mb-blue-200)', success: 'var(--status-success)', warning: 'var(--status-warning)', danger: 'var(--status-danger)' };

function DonutChart({ segments = [], size = 150, thickness = 26, centerLabel, centerValue, valueFormat }) {
  const fmtVal = valueFormat || ((v) => v);
  const total = segments.reduce((a, s) => a + s.value, 0) || 1;
  let acc = 0;
  const stops = segments.map((s) => {
    const pct = (s.value / total) * 100;
    const start = acc; acc += pct;
    return `${DONUT_DOT[s.tone || 'accent']} ${start}% ${acc}%`;
  }).join(', ');
  return (
    <div style={{ display: 'flex', gap: 20, alignItems: 'center', flexWrap: 'wrap' }}>
      <div style={{ position: 'relative', width: size, height: size, borderRadius: '50%', background: `conic-gradient(${stops})`, flexShrink: 0 }}>
        <div style={{ position: 'absolute', inset: thickness, borderRadius: '50%', background: 'var(--surface-card)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center' }}>
          <span style={{ fontSize: 20, fontWeight: 500, letterSpacing: '-0.02em', color: 'var(--text-strong)', fontVariantNumeric: 'tabular-nums' }}>{centerValue}</span>
          <span style={{ fontSize: 10, color: 'var(--text-subtle)' }}>{centerLabel}</span>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, minWidth: 0 }}>
        {segments.map((s, i) => (
          <span key={i} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--text-muted)', whiteSpace: 'nowrap' }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: DONUT_DOT[s.tone || 'accent'], flexShrink: 0 }} />
            {s.label} <b style={{ color: 'var(--text-strong)' }}>{fmtVal(s.value)}</b>
            <span style={{ fontSize: 10, color: 'var(--text-subtle)' }}>({Math.round((s.value / total) * 100)}%)</span>
          </span>
        ))}
      </div>
    </div>
  );
}

function parseBRd(v) {
  if (!v) return 0;
  const n = parseFloat(String(v).replace(/\./g, '').replace(',', '.').replace(/[^\d.-]/g, ''));
  return isNaN(n) ? 0 : n;
}
function fmtMoneyD(n) {
  return `R$ ${(n || 0).toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}

function GroupTile({ g }) {
  const dark = g.tone === 'dark', acc = g.tone === 'accent';
  return (
    <div style={{ flex: 1, minWidth: 0, padding: '10px 12px', borderRadius: 12, display: 'flex', flexDirection: 'column', gap: 6,
      background: dark ? 'var(--pattern-hatch-light), var(--mb-black)' : acc ? 'var(--action-accent)' : 'var(--surface-sunken)', color: dark || acc ? '#fff' : 'var(--text-strong)' }}>
      <span style={{ fontSize: 11, opacity: dark || acc ? 0.85 : 0.75, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{g.label}</span>
      <span style={{ fontSize: 20, fontWeight: 500, letterSpacing: '-0.02em', lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>{g.count}</span>
      <span style={{ alignSelf: 'flex-start', maxWidth: '100%', overflow: 'hidden', display: 'inline-flex', alignItems: 'center', gap: 5, height: 18, padding: '0 7px', borderRadius: 999, fontSize: 10, whiteSpace: 'nowrap',
        background: dark || acc ? 'rgba(255,255,255,.16)' : 'var(--surface-card)', color: dark || acc ? '#fff' : 'var(--text-muted)' }}>
        <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--status-success)' }} />{g.note}
      </span>
    </div>
  );
}

const PENDENTE_STATUS = ['Em negociação', 'A confirmar', 'Manutenção', 'Pendência'];

function Dashboard({ mode, go, onQuick, properties, onOpenLocacoes, maintenanceRecords }) {
  const { Card, StatCard, QuickAction, Select, IconButton, Button, ListItem, Avatar, Badge, BarChart, StackedBar, ProgressBar, Delta, Icon } = DSd;
  const D = window.MB_DATA;
  const m = mode === 'mobile', t = mode === 'tablet';
  const gap = m ? 12 : 16;
  const tone = { danger: 'var(--status-danger)', warning: 'var(--status-warning)', neutral: 'var(--text-muted)' };

  // Calculado ao vivo a partir dos imóveis cadastrados (reage a edições feitas em Imóveis).
  const props = properties || D.properties;
  const locadosN = props.filter((p) => p.status === 'Locado').length;
  const disponiveisN = props.filter((p) => p.status === 'Disponível').length;
  const pendentesN = props.filter((p) => PENDENTE_STATUS.includes(p.status)).length;
  const vistoriasAgendadasN = props.reduce((total, p) => total + (p.vistorias || []).filter((v) => v.status === 'Agendada').length, 0);
  // Contratos ativos com vencimento dentro dos próximos 30 dias (já vigente, ainda não vencido).
  const diasAteD = (iso) => {
    if (!iso) return Infinity;
    const [y, mo, d] = iso.split('-').map(Number);
    const alvo = new Date(y, mo - 1, d);
    const hoje = new Date(); hoje.setHours(0, 0, 0, 0);
    return Math.round((alvo - hoje) / 86400000);
  };
  const contratosVencer30N = props.reduce((total, p) => total + (p.locacoes || [])
    .filter((l) => l.ativa && l.dataVencimento && diasAteD(l.dataVencimento) >= 0 && diasAteD(l.dataVencimento) <= 30).length, 0);
  const groups = [
    { label: 'Vistorias agendadas', count: vistoriasAgendadasN, note: 'Ver em Vistorias', tone: 'dark' },
    { label: 'Pendências', count: pendentesN, note: 'Ver em Imóveis', tone: 'accent' },
    { label: 'Contratos a vencer', count: contratosVencer30N, note: 'Próximos 30 dias', tone: 'light' },
  ];
  const kpis = [
    { label: 'Imóveis na carteira', value: String(props.length), delta: '', trend: 'up', icon: 'house' },
    { label: 'Locados', value: String(locadosN), delta: '', trend: 'up', icon: 'key-round' },
    { label: 'Disponíveis', value: String(disponiveisN), delta: '', trend: 'up', icon: 'door-open' },
    { label: 'Pendentes', value: String(pendentesN), delta: '', trend: pendentesN > 0 ? 'down' : 'up', icon: 'circle-alert' },
  ];
  const manutencaoAbertaN = props.filter((p) => p.status === 'Manutenção').length;

  // ===== Números reais (calculados ao vivo a partir das locações) =====
  const hojeISO = new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 10);
  const mesKey = hojeISO.slice(0, 7);
  const MES_ABR = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
  const ultimos6 = [];
  for (let i = 5; i >= 0; i--) { const d = new Date(Number(mesKey.slice(0, 4)), Number(mesKey.slice(5, 7)) - 1 - i, 1); ultimos6.push({ k: `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`, label: MES_ABR[d.getMonth()], ano: d.getFullYear() }); }
  const fmtMil = (v) => v >= 1000 ? 'R$ ' + (v / 1000).toLocaleString('pt-BR', { maximumFractionDigits: 1 }) + ' mil' : v.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
  const recPorMes = {}, taxaPorMes = {}, ativosPorMes = {};
  let ativosAgora = 0, somaAluguelAtivos = 0;
  let pagasMes = 0, aVencerMes = 0, atrasadasMes = 0, recebidoMesV = 0, previstoMesV = 0, repasseMesV = 0;
  const donosRepasse = new Set();
  props.forEach((p) => (p.locacoes || []).forEach((l) => {
    const aluguelL = l.valorAluguelAtual || parseBRd(p._form && p._form.valorAluguel) || 0;
    if (l.ativa) { ativosAgora += 1; somaAluguelAtivos += aluguelL; }
    ultimos6.forEach((mm) => {
      const ini = (l.dataInicio || '').slice(0, 7), fim = (l.dataFim || '').slice(0, 7);
      if (ini && ini <= mm.k && (!fim || fim >= mm.k)) ativosPorMes[mm.k] = (ativosPorMes[mm.k] || 0) + 1;
    });
    const cobs = l.cobrancas || [], reps = l.repasses || [];
    cobs.forEach((c, i) => {
      const v = Number(c.valor) || 0, venc = (c.vencimento || '').slice(0, 7);
      if (c.status === 'Pago' && !c.compensado) {
        const k = String(c.dataPagamento || c.vencimento || '').slice(0, 7);
        const base = c.caucao ? v / 4 : v;
        recPorMes[k] = (recPorMes[k] || 0) + base;
        const r = reps[i];
        if (r) taxaPorMes[k] = (taxaPorMes[k] || 0) + Math.max(0, base - (Number(r.valor) || 0));
      }
      if (venc === mesKey) {
        previstoMesV += v;
        if (c.status === 'Pago') { pagasMes += 1; recebidoMesV += v; }
        else if ((c.vencimento || '') < hojeISO) atrasadasMes += 1;
        else aVencerMes += 1;
      }
    });
    reps.forEach((r) => {
      if ((r.vencimento || '').slice(0, 7) === mesKey && r.status !== 'Repassado') { repasseMesV += Number(r.valor) || 0; donosRepasse.add(p.owner || p.id); }
    });
  }));
  const receita6 = ultimos6.reduce((a, mm) => a + (recPorMes[mm.k] || 0), 0);
  const taxa6 = ultimos6.reduce((a, mm) => a + (taxaPorMes[mm.k] || 0), 0);
  const revenueKpisReal = [
    { label: 'Receita (aluguéis recebidos)', value: fmtMil(receita6), delta: '' },
    { label: 'Contratos ativos', value: String(ativosAgora) },
    { label: 'Ticket médio', value: fmtMil(ativosAgora ? somaAluguelAtivos / ativosAgora : 0) },
    { label: 'Taxa adm. (receita da imobiliária)', value: fmtMil(taxa6) },
  ];
  const revenueReal = ultimos6.map((mm) => ({ label: mm.label, value: ativosPorMes[mm.k] || 0, line: Math.round((recPorMes[mm.k] || 0) / 100) / 10 }));
  const periodoRec = `${ultimos6[0].label}–${ultimos6[5].label} ${ultimos6[5].ano}`;
  const billingReal = [
    { label: 'Pagas', value: pagasMes, tone: 'accent' },
    { label: 'A vencer', value: aVencerMes, tone: 'dark' },
    { label: 'Atrasadas', value: atrasadasMes, tone: 'muted' },
  ];
  // Próximos repasses a fazer (todas as locações), do mais próximo para o mais distante.
  const proxRepasses = [];
  props.forEach((p) => (p.locacoes || []).forEach((l) => (l.repasses || []).forEach((r, i) => {
    if (r.status === 'Repassado' || r.compensado) return;
    const c = (l.cobrancas || [])[i];
    proxRepasses.push({ key: p.id + l.id + i, propertyId: p.id, imovel: p.name, dono: p.owner || 'Proprietário', mes: r.mes, venc: r.vencimento, valor: Number(r.valor) || 0, liberado: !c || c.status === 'Pago' });
  })));
  proxRepasses.sort((a, b) => String(a.venc).localeCompare(String(b.venc)));
  // Locações novas: contratos iniciados por mês nos últimos 12 meses (data de início de cada locação cadastrada)
  const MES_MIN = ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'];
  const novasLoc = [];
  for (let i = 11; i >= 0; i--) { const d = new Date(Number(mesKey.slice(0, 4)), Number(mesKey.slice(5, 7)) - 1 - i, 1); novasLoc.push({ k: `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`, label: MES_MIN[d.getMonth()], value: 0 }); }
  props.forEach((p) => (p.locacoes || []).forEach((l) => { const b = novasLoc.find((x) => x.k === String(l.dataInicio || '').slice(0, 7)); if (b) b.value += 1; }));
  const metaPct = previstoMesV > 0 ? Math.round(recebidoMesV / previstoMesV * 100) : 0;


  // Vencimentos mensais por dia (5/15/25) — quantidade de contratos ativos e VGV (soma dos
  // aluguéis) que vence em cada dia, calculado ao vivo a partir das locações ativas.
  const DIAS_VENCIMENTO = [5, 15, 25];
  const vencData = DIAS_VENCIMENTO.map((dia) => {
    let count = 0, vgv = 0;
    props.forEach((p) => {
      (p.locacoes || []).forEach((l) => {
        if (l.ativa && l.diaVencimento === dia) {
          count += 1;
          vgv += l.valorAluguelAtual || parseBRd(p._form && p._form.valorAluguel);
        }
      });
    });
    return { dia, count, vgv };
  });
  const maxVgv = Math.max(...vencData.map((v) => v.vgv), 1);

  // Contratos de locação mais próximos do fim (baseado no prazo/data de vencimento da locação ativa).
  const contratosAVencer = props.flatMap((p) => (p.locacoes || [])
    .filter((l) => l.ativa && l.dataVencimento)
    .map((l) => ({ propertyId: p.id, title: p.name, sub: `Inquilino: ${l.inquilino || '—'}`, dias: diasAteD(l.dataVencimento) })))
    .filter((r) => r.dias >= 0)
    .sort((a, b) => a.dias - b.dias);

  // Contratos ativos cujo vencimento já passou (ninguém renovou/encerrou ainda) — só a quantidade
  // entra em "Precisa de atenção", levando pra página de Contratos (lá sim lista um por um).
  const contratosVencidosN = props.reduce((total, p) => total + (p.locacoes || [])
    .filter((l) => l.ativa && l.dataVencimento && diasAteD(l.dataVencimento) < 0).length, 0);

  const attentionItems = [
    { n: pendentesN, title: 'Imóveis pendentes', sub: 'Em negociação, a confirmar, em manutenção ou pendência', tone: 'warning', onClick: () => go('properties') },
    { n: contratosVencidosN, title: 'Contratos vencidos', sub: 'Locações ativas com vencimento já passado', tone: 'danger', onClick: () => go('contracts') },
    { n: vistoriasAgendadasN, title: 'Vistorias agendadas', sub: 'Vistorias marcadas em imóveis da carteira', tone: 'neutral', onClick: () => go('inspections') },
    { n: manutencaoAbertaN, title: 'Manutenção em aberto', sub: 'Imóveis com manutenção em andamento', tone: 'warning', onClick: () => go('maintenance') },
  ];

  const quick = m ? (
    <div style={{ display: 'flex', gap: 10, overflowX: 'auto', margin: '0 -16px', padding: '2px 16px 6px', scrollbarWidth: 'none' }}>
      {D.quickActions.map((a) => <QuickAction key={a.id} icon={a.icon} label={a.label} variant={a.primary ? 'primary' : 'default'} onClick={() => onQuick(a.id)} style={{ flex: '0 0 108px' }} />)}
    </div>
  ) : (
    <div style={{ display: 'grid', gridTemplateColumns: `repeat(${t ? 3 : 6}, minmax(0,1fr))`, gap: 12 }}>
      {D.quickActions.map((a) => <QuickAction key={a.id} icon={a.icon} label={a.label} variant={a.primary ? 'primary' : 'default'} onClick={() => onQuick(a.id)} />)}
    </div>
  );

  const portfolio = (
    <Card title="Desempenho da carteira" icon="house" tone="accent" action={<IconButton label="Ver imóveis" size="sm" onClick={() => go('properties')} />}>
      <div style={{ display: 'grid', gridTemplateColumns: m ? '1fr 1fr' : 'repeat(4, minmax(0,1fr))', gap: 10 }}>
        {kpis.map((k) => <StatCard key={k.label} {...k} caption="vs. mês anterior" />)}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: m ? '1fr' : 'minmax(0,1fr) minmax(0,1fr)', gap: 10 }}>
        <Card variant="accent" padding="sm" radius="md" title="Vencimentos por dia" icon="calendar-clock" style={{ gap: 10, boxShadow: 'none' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {vencData.map((v) => (
              <div key={v.dia} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ display: 'flex', flexDirection: 'column', width: 68, flexShrink: 0 }}>
                  <span style={{ fontSize: 10, color: '#fff', opacity: 0.75 }}>Dia {v.dia}</span>
                  <span style={{ fontSize: 13, fontWeight: 600, color: '#fff' }}>{v.count} {v.count === 1 ? 'contrato' : 'contratos'}</span>
                </div>
                <div style={{ flex: 1, height: 10, borderRadius: 5, background: 'rgba(255,255,255,.2)', overflow: 'hidden' }}>
                  <div style={{ width: `${(v.vgv / maxVgv) * 100}%`, minWidth: v.vgv > 0 ? 6 : 0, height: '100%', borderRadius: 5, background: '#fff' }} />
                </div>
                <span style={{ fontSize: 12, fontWeight: 600, color: '#fff', whiteSpace: 'nowrap', width: 92, textAlign: 'right' }}>{fmtMoneyD(v.vgv)}</span>
              </div>
            ))}
          </div>
        </Card>
        <Card variant="sunken" padding="sm" radius="md" title="Contratos a vencer" icon="file-text" tone="warning" action={<IconButton label="Ver contratos" size="sm" onClick={() => go('contracts')} />} style={{ gap: 10 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {contratosAVencer.length === 0 ? (
              <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>Nenhum contrato de locação ativo com vencimento cadastrado.</span>
            ) : contratosAVencer.slice(0, 3).map((r, i) => (
              <ListItem key={r.propertyId + i} variant="card" onClick={() => onOpenLocacoes && onOpenLocacoes(r.propertyId)} style={{ padding: '8px 10px', cursor: 'pointer' }}
                leading={<span style={{ fontSize: 11, color: 'var(--text-subtle)', width: 16 }}>{String(i + 1).padStart(2, '0')}</span>}
                title={r.title} description={r.sub}
                trailing={<span style={{ fontSize: 11, fontWeight: 600, color: r.dias <= 7 ? 'var(--status-warning-text)' : 'var(--text-muted)', whiteSpace: 'nowrap' }}>{r.dias} {r.dias === 1 ? 'dia' : 'dias'}</span>} />
            ))}
          </div>
        </Card>
      </div>
    </Card>
  );

  const manutencoesPendentes = [...(maintenanceRecords || [])]
    .filter((r) => r.status !== 'Realizada')
    .sort((a, b) => a.data.localeCompare(b.data))
    .slice(0, 4);

  const activity = (
    <Card title="Atividade" icon="wrench" tone="accent" action={<><Button variant="ghost" size="sm" onClick={() => go('maintenance')}>Ver tudo</Button><IconButton label="Abrir atividade" size="sm" onClick={() => go('maintenance')} /></>}>
      <div style={{ display: 'flex', gap: 8 }}>{groups.map((g) => <GroupTile key={g.label} g={g} />)}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {manutencoesPendentes.length === 0 ? (
          <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>Nenhuma manutenção pendente no momento.</span>
        ) : manutencoesPendentes.map((r) => (
          <ListItem key={r.id} onClick={() => go('maintenance')} style={{ cursor: 'pointer' }}
            leading={<Avatar name={r.prestadorNome || '?'} size={30} />}
            title={<><b style={{ fontWeight: 600 }}>{r.prestadorNome}</b> vai fazer <b style={{ fontWeight: 600 }}>{r.descricao}</b> em <b style={{ fontWeight: 600 }}>{r.propertyName}</b></>}
            meta={typeof fmtDataHoraBRmn === 'function' ? fmtDataHoraBRmn(r.data) : r.data} />
        ))}
      </div>
    </Card>
  );

  const revenue = (
    <Card title="Receita de aluguéis" icon="banknote" tone="success" subtitle="Contratos ativos (barras) × aluguéis recebidos em R$ mil (linha) — últimos 6 meses" action={<span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{periodoRec}</span>}>
      <div style={{ display: 'grid', gridTemplateColumns: m ? '1fr 1fr' : '1.5fr 1fr 1fr 1fr', gap: 10 }}>
        {revenueKpisReal.map((k, i) => (
          <div key={k.label} style={{ display: 'flex', flexDirection: 'column', gap: 4, padding: '10px 12px', borderRadius: 12, background: 'var(--surface-sunken)' }}>
            <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>{k.label}</span>
            <span style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}><span style={{ fontSize: i === 0 ? 22 : 18, fontWeight: 500, letterSpacing: '-0.02em', color: 'var(--text-strong)', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>{k.value}</span>{k.delta && <Delta value={k.delta} />}</span>
          </div>
        ))}
      </div>
      <BarChart height={m ? 170 : 200} data={revenueReal} lineFormat={(v) => `R$ ${String(v).replace('.', ',')} mil`} />
    </Card>
  );

  const monthLabel = new Date().toLocaleDateString('pt-BR', { month: 'long', year: 'numeric' });
  const billingTotal = billingReal.reduce((a, s) => a + s.value, 0);
  const billing = (
    <Card title="Status de cobranças" icon="receipt" tone="accent" subtitle={`${monthLabel.charAt(0).toUpperCase() + monthLabel.slice(1)} · ${billingTotal} cobranças`} action={<IconButton label="Ver cobranças" size="sm" onClick={() => go('billing')} />}>
      <DonutChart segments={billingReal} centerValue={billingTotal} centerLabel="cobranças" />
    </Card>
  );

  const newLeases = (
    <Card title="Locações novas" icon="key-round" tone="accent" subtitle="Locações iniciadas por mês, conforme as locações cadastradas" action={<span style={{ fontSize: 12, color: 'var(--text-muted)' }}>Últimos 12 meses</span>}>
      <BarChart height={m ? 170 : 200} data={novasLoc.map(({ label, value }) => ({ label, value }))} showLine={false} />
    </Card>
  );

  const attention = (
    <Card title="Precisa de atenção" icon="triangle-alert" tone="warning" padding="md">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {attentionItems.map((a) => <ListItem key={a.title} onClick={a.onClick || (() => go('properties'))} leading={<span style={{ width: 20, textAlign: 'center', fontSize: 14, fontWeight: 600, color: tone[a.tone] }}>{a.n}</span>} title={a.title} description={a.sub} />)}
      </div>
    </Card>
  );

  const fmtDataCurta = (iso) => { if (!iso) return '—'; const [y, mo, d] = iso.split('-'); return `${d}/${mo}/${y}`; };
  const goal = (
    <Card variant="accent" pattern title="Próximos repasses" icon="wallet" subtitle="Aos proprietários, por data de vencimento" action={<IconButton label="Ver repasses" variant="light" size="sm" onClick={() => go('payouts')} />} style={{ minHeight: m ? undefined : '100%' }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {proxRepasses.length === 0 ? (
          <span style={{ fontSize: 13, color: 'rgba(255,255,255,.85)' }}>Nenhum repasse pendente.</span>
        ) : proxRepasses.slice(0, 8).map((r) => {
          const atras = r.venc < hojeISO;
          return (
            <div key={r.key} onClick={() => onOpenLocacoes && onOpenLocacoes(r.propertyId)}
              style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10, padding: '9px 12px', borderRadius: 12, background: 'rgba(255,255,255,.12)', border: '1px solid rgba(255,255,255,.18)', cursor: onOpenLocacoes ? 'pointer' : 'default' }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
                <span style={{ fontSize: 13, fontWeight: 600, color: '#fff', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.dono}</span>
                <span style={{ fontSize: 11, color: 'rgba(255,255,255,.75)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.imovel} · {r.mes}</span>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 2, flex: 'none' }}>
                <span style={{ fontSize: 13, fontWeight: 600, color: '#fff' }}>{r.valor.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}</span>
                <span style={{ fontSize: 10.5, fontWeight: 600, color: atras ? '#fecaca' : r.liberado ? '#bbf7d0' : 'rgba(255,255,255,.7)' }}>{atras ? 'Atrasado · ' : ''}{fmtDataCurta(r.venc)}{!r.liberado ? ' · aguarda inquilino' : ''}</span>
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ flex: 1 }} />
      <Button variant="inverse" size="sm" iconRight="arrow-right" onClick={() => go('payouts')} style={{ alignSelf: 'flex-start' }}>Ver todos os repasses</Button>
    </Card>
  );

  return (
    <div style={{ padding: m ? '4px 16px 24px' : '4px var(--page-pad) var(--page-pad)', display: 'flex', flexDirection: 'column', gap }}>
      <PageHeader display mode={mode} icon="layout-dashboard" tone="accent" title={`Bem-vindo de volta, ${D.user.first}!`} subtitle="Veja o que está acontecendo na sua carteira hoje." actions={!m && <Button variant="secondary" size="sm" icon="layout-grid">Personalizar painel</Button>} />
      {quick}
      {mode === 'desktop' ? (
        <>
          <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,7fr) minmax(0,5fr)', gap }}>{portfolio}{activity}</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,6fr) minmax(0,3fr) minmax(0,3fr)', gap }}>
            {revenue}
            <div style={{ display: 'flex', flexDirection: 'column', gap }}>{billing}{attention}</div>
            {goal}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr)', gap }}>{newLeases}</div>
        </>
      ) : t ? (
        <>
          {portfolio}
          <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1fr)', gap }}>{activity}<div style={{ display: 'flex', flexDirection: 'column', gap }}>{billing}{attention}</div></div>
          <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,2fr) minmax(0,1fr)', gap }}>{revenue}{goal}</div>
          {newLeases}
        </>
      ) : (
        <>{goal}{portfolio}{attention}{billing}{newLeases}{revenue}{activity}</>
      )}
    </div>
  );
}

window.Dashboard = Dashboard;
window.DonutChart = DonutChart;
