// Brisas do Lago — Backoffice
// Dashboard, Lotes, CRM, Carteira, Cobrança, Financeiro, Documentos, Relatórios

const { useState, useMemo } = React;

function BackofficeApp() {
  const [section, setSection] = useState('dashboard');

  const sections = [
    {id:'dashboard', lbl:'Dashboard', icon:'dashboard'},
    {id:'lotes', lbl:'Lotes', icon:'layers'},
    {id:'crm', lbl:'Funil & CRM', icon:'funnel'},
    {id:'carteira', lbl:'Carteira', icon:'briefcase'},
    {id:'cobranca', lbl:'Cobrança', icon:'invoice'},
    {id:'financeiro', lbl:'Financeiro', icon:'coin'},
    {id:'docs', lbl:'Documentos', icon:'file'},
    {id:'relatorios', lbl:'Relatórios', icon:'sparkle'},
  ];

  return (
    <div style={{display:'grid', gridTemplateColumns:'220px 1fr', minHeight:'calc(100vh - 70px)'}}>
      {/* Sidebar */}
      <aside style={{
        borderRight:'1px solid var(--line)', padding:'24px 14px',
        background:'var(--bg-card)',
        position:'sticky', top:70, height:'calc(100vh - 70px)', overflow:'auto'
      }}>
        <div className="eyebrow" style={{padding:'0 12px', marginBottom:12}}>◇ Backoffice</div>
        <nav style={{display:'flex', flexDirection:'column', gap:2}}>
          {sections.map(s => (
            <button key={s.id} onClick={()=>setSection(s.id)} style={{
              padding:'10px 14px', borderRadius:10,
              display:'flex', alignItems:'center', gap:10,
              fontSize:13.5, fontWeight: section === s.id ? 700 : 500,
              background: section === s.id ? 'var(--green-soft)' : 'transparent',
              color: section === s.id ? 'var(--green-deep)' : 'var(--ink-soft)',
              cursor:'pointer', textAlign:'left'
            }}>
              <Icon name={s.icon} size={15}/> {s.lbl}
            </button>
          ))}
        </nav>

        <div style={{height:1, background:'var(--line-soft)', margin:'24px 8px'}}/>
        <div style={{padding:'0 12px'}}>
          <div className="eyebrow" style={{marginBottom:10}}>◇ Equipe online</div>
          <div style={{display:'flex', flexDirection:'column', gap:8}}>
            {[
              ['Júlia Mendes', 'JM', '#C97B4A'],
              ['Rafael Pinto', 'RP', '#2D4F3C'],
              ['Diego Aragão', 'DA', '#5B8FA8'],
            ].map(([n, init, c]) => (
              <div key={n} style={{display:'flex', alignItems:'center', gap:8, fontSize:12}}>
                <div style={{width:28, height:28, borderRadius:'50%', background:c, color:'white', display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:700, position:'relative'}}>
                  {init}
                  <div style={{position:'absolute', bottom:-1, right:-1, width:8, height:8, borderRadius:50, background:'var(--success)', border:'2px solid var(--bg-card)'}}/>
                </div>
                {n}
              </div>
            ))}
          </div>
        </div>
      </aside>

      <main style={{padding:'30px 36px 60px', maxWidth:'100%', overflow:'hidden'}}>
        {section === 'dashboard' && <BoDashboard/>}
        {section === 'lotes' && <BoLotes/>}
        {section === 'crm' && <BoCrm/>}
        {section === 'carteira' && <BoCarteira/>}
        {section === 'cobranca' && <BoCobranca/>}
        {section === 'financeiro' && <BoFinanceiro/>}
        {section === 'docs' && <BoDocs/>}
        {section === 'relatorios' && <BoRelatorios/>}
      </main>
    </div>
  );
}

// ─── Dashboard ──────────────────────────────────────────────
function BoDashboard() {
  const k = window.BL.kpis();
  const [variation, setVariation] = useState('A');

  return (
    <div>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom:24}}>
        <div>
          <div className="eyebrow" style={{marginBottom:6}}>◇ Visão geral</div>
          <h1 className="display" style={{fontSize:36, fontWeight:500, color:'var(--green-deep)'}}>Dashboard</h1>
          <div style={{fontSize:13, color:'var(--ink-soft)', marginTop:4}}>21 Mai 2026 · atualizado há 2 minutos</div>
        </div>
        <div style={{display:'flex', gap:6}}>
          <div style={{display:'flex', gap:4, background:'var(--bg-card)', padding:4, borderRadius:100, border:'1px solid var(--line)', marginRight:8}}>
            <button onClick={()=>setVariation('A')} className="btn btn-sm" style={{padding:'5px 14px', fontSize:11, background: variation==='A' ? 'var(--green)' : 'transparent', color: variation==='A' ? 'var(--bg-card)' : 'var(--ink-soft)'}}>Editorial</button>
            <button onClick={()=>setVariation('B')} className="btn btn-sm" style={{padding:'5px 14px', fontSize:11, background: variation==='B' ? 'var(--green)' : 'transparent', color: variation==='B' ? 'var(--bg-card)' : 'var(--ink-soft)'}}>Denso</button>
          </div>
          <button className="btn btn-sm btn-secondary"><Icon name="calendar" size={13}/> Maio · 2026</button>
          <button className="btn btn-sm btn-secondary"><Icon name="download" size={13}/> Exportar</button>
        </div>
      </div>

      {variation === 'A' ? <DashboardA k={k}/> : <DashboardB k={k}/>}
    </div>
  );
}

function DashboardA({k}) {
  return (
    <>
      {/* Big hero KPI */}
      <div style={{display:'grid', gridTemplateColumns:'minmax(0, 1.6fr) minmax(0, 1fr) minmax(0, 1fr)', gap:14, marginBottom:14}}>
        <div className="card" style={{padding:'28px 32px', background:'var(--green-deep)', borderColor:'transparent', color:'var(--bg-card)', position:'relative', overflow:'hidden'}}>
          <div style={{position:'absolute', right:-30, bottom:-40, opacity:0.15}}>
            <MapaLoteamento estilo="esquematico" compacto/>
          </div>
          <div className="eyebrow" style={{color:'#D9C7A8', marginBottom:14, position:'relative'}}>◐ VGV total · 95 lotes</div>
          <div className="display" style={{fontSize:'clamp(40px, 5vw, 64px)', fontWeight:500, lineHeight:1, color:'var(--bg-card)', position:'relative', whiteSpace:'nowrap'}}>
            {fmtBRL(k.vgvTotal)}
          </div>
          <div style={{display:'flex', gap:24, marginTop:24, position:'relative'}}>
            <Stat lbl="Vendido" v={fmtBRL(k.vgvVendido)} sub={`${(k.pctVendido*100).toFixed(0)}%`} dark/>
            <Stat lbl="Reservado" v={fmtBRL(k.vgvReservado)} sub={`${(k.pctReservado*100).toFixed(0)}%`} dark/>
            <Stat lbl="A disponibilizar" v={fmtBRL(k.vgvTotal - k.vgvVendido - k.vgvReservado)} sub={`${k.disponiveis} lotes`} dark/>
          </div>
        </div>
        <KpiCard label="Lotes vendidos" value={k.vendidos} sub={`de ${k.total} totais`} icon="check" trend={{dir:'up', value:'+4 este mês'}}/>
        <KpiCard label="Em negociação" value={k.negociacao} sub={`${k.reservados} reservas ativas`} icon="funnel" color="var(--terra)"/>
      </div>

      {/* Second row */}
      <div style={{display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:14, marginBottom:24}}>
        <KpiCard label="Carteira ativa" value={fmtBRL(k.carteiraTotal).replace('R$', 'R$').slice(0, -3) + 'M'} sub={`${window.BL.CLIENTES.length} clientes`} icon="briefcase"/>
        <KpiCard label="Inadimplência" value={(k.inadimplenciaPct*100).toFixed(1) + '%'} sub={`${k.inadimplentes} clientes em atraso`} icon="warn" color="var(--terra)" trend={{dir:'down', value:'-1.2% vs abr'}}/>
        <KpiCard label="Boletos do mês" value={window.BL.CLIENTES.length} sub={fmtBRL(window.BL.CLIENTES.reduce((s,c)=>s+c.valorContrato*0.8/48, 0))} icon="invoice"/>
        <KpiCard label="Leads ativos" value={window.BL.LEADS.length} sub="3 ↑ vs semana passada" icon="users" color="var(--lago)"/>
      </div>

      {/* Map + Funil */}
      <div style={{display:'grid', gridTemplateColumns:'minmax(0, 1.6fr) minmax(0, 1fr)', gap:18, marginBottom:18}}>
        <div className="card" style={{padding:18}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14}}>
            <div className="eyebrow">◇ Mapa de disponibilidade</div>
            <div style={{display:'flex', gap:14, fontSize:11, color:'var(--ink-soft)'}}>
              <span><span style={{width:8, height:8, background:'#2D4F3C', display:'inline-block', borderRadius:2, marginRight:5}}/>Disp.</span>
              <span><span style={{width:8, height:8, background:'#C97B4A', display:'inline-block', borderRadius:2, marginRight:5}}/>Reserv.</span>
              <span><span style={{width:8, height:8, background:'#5B8FA8', display:'inline-block', borderRadius:2, marginRight:5}}/>Negoc.</span>
              <span><span style={{width:8, height:8, background:'#6E7B72', display:'inline-block', borderRadius:2, marginRight:5}}/>Vendido</span>
            </div>
          </div>
          <MapaLoteamento estilo="tecnico" compacto/>
        </div>
        <div className="card" style={{padding:24}}>
          <div className="eyebrow" style={{marginBottom:18}}>◇ Funil de vendas (5 meses)</div>
          <FunnelChart/>
        </div>
      </div>

      {/* Atividade recente */}
      <div style={{display:'grid', gridTemplateColumns:'minmax(0, 1.4fr) minmax(0, 1fr)', gap:18}}>
        <div className="card" style={{padding:24}}>
          <div style={{display:'flex', justifyContent:'space-between', marginBottom:18}}>
            <div className="eyebrow">◇ Atividade recente</div>
            <button className="btn btn-sm btn-ghost">Tudo <Icon name="chevR" size={11}/></button>
          </div>
          <div style={{display:'flex', flexDirection:'column', gap:14}}>
            <Atividade icon="check" color="var(--success)" titulo="Lote 4 · Quadra A vendido"
              sub="Henrique Vasconcelos · Júlia Mendes · R$ 214.200" tempo="há 12 min"/>
            <Atividade icon="invoice" color="var(--terra)" titulo="Boleto pago — Lote 38"
              sub="Marcos Pereira · parcela 4/48 · R$ 6.317" tempo="há 35 min"/>
            <Atividade icon="users" color="var(--lago)" titulo="Novo lead via Instagram"
              sub="Patrícia Nunes · interesse vista lago" tempo="há 1h"/>
            <Atividade icon="warn" color="var(--terra)" titulo="Cobrança automática enviada"
              sub="3 clientes em atraso · WhatsApp + e-mail" tempo="há 2h"/>
            <Atividade icon="file" color="var(--green)" titulo="Contrato assinado · Lote 78"
              sub="Roberto Mendes · D4Sign · R$ 432.000" tempo="há 3h"/>
            <Atividade icon="pin" color="var(--green)" titulo="Reserva criada · Lote 88"
              sub="Ana Carolina Rocha · 24h timer iniciado" tempo="há 4h"/>
          </div>
        </div>
        <div className="card" style={{padding:24}}>
          <div style={{display:'flex', justifyContent:'space-between', marginBottom:18}}>
            <div className="eyebrow">◇ Top corretores · maio</div>
          </div>
          <div style={{display:'flex', flexDirection:'column', gap:14}}>
            {[
              ['Júlia Mendes', 8, 1850000, '#C97B4A', 100],
              ['Rafael Pinto', 6, 1420000, '#2D4F3C', 77],
              ['Diego Aragão', 4, 980000, '#5B8FA8', 53],
            ].map(([n, vendas, vgv, c, pct]) => (
              <div key={n}>
                <div style={{display:'flex', justifyContent:'space-between', marginBottom:6}}>
                  <div style={{display:'flex', alignItems:'center', gap:10, minWidth:0}}>
                    <div style={{width:30, height:30, borderRadius:'50%', background:c, color:'white', display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:700, flexShrink:0}}>{n.split(' ').map(x=>x[0]).join('')}</div>
                    <div style={{minWidth:0}}>
                      <div style={{fontSize:13, fontWeight:600, whiteSpace:'nowrap'}}>{n}</div>
                      <div style={{fontSize:11, color:'var(--ink-soft)'}}>{vendas} vendas</div>
                    </div>
                  </div>
                  <div className="mono" style={{fontSize:12, fontWeight:600, color:'var(--green-deep)'}}>{fmtBRL(vgv)}</div>
                </div>
                <div style={{height:5, background:'var(--bg-elev)', borderRadius:100, overflow:'hidden'}}>
                  <div style={{width: pct + '%', height:'100%', background:c, borderRadius:100}}/>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </>
  );
}

function DashboardB({k}) {
  // Variação 2: dashboard mais denso, tabela
  return (
    <>
      <div style={{display:'grid', gridTemplateColumns:'repeat(6, 1fr)', gap:10, marginBottom:18}}>
        {[
          ['VGV total', fmtBRL(k.vgvTotal).replace(/\s/g,'')],
          ['Vendido', fmtBRL(k.vgvVendido).replace(/\s/g,'')],
          ['% vendido', (k.pctVendido*100).toFixed(0)+'%'],
          ['Disponível', k.disponiveis + ' lotes'],
          ['Carteira', fmtBRL(k.carteiraTotal).replace(/\s/g,'')],
          ['Inadimpl.', (k.inadimplenciaPct*100).toFixed(1)+'%'],
        ].map(([lbl, v]) => (
          <div key={lbl} style={{padding:'14px 16px', background:'var(--bg-card)', borderRadius:10, border:'1px solid var(--line-soft)'}}>
            <div style={{fontSize:10, color:'var(--ink-soft)', textTransform:'uppercase', letterSpacing:1, marginBottom:4}}>{lbl}</div>
            <div className="mono" style={{fontSize:16, fontWeight:700, color:'var(--green-deep)'}}>{v}</div>
          </div>
        ))}
      </div>

      <div style={{display:'grid', gridTemplateColumns:'minmax(0, 2fr) minmax(0, 1fr)', gap:14, marginBottom:14}}>
        <div className="card" style={{padding:6}}>
          <MapaLoteamento estilo="tecnico" compacto/>
        </div>
        <div className="card" style={{padding:20}}>
          <div className="eyebrow" style={{marginBottom:14}}>◇ Distribuição por status</div>
          <DonutChart data={[
            {lbl:'Disponível', v:k.disponiveis, c:'var(--green)'},
            {lbl:'Reservado', v:k.reservados, c:'var(--terra)'},
            {lbl:'Negociação', v:k.negociacao, c:'var(--lago)'},
            {lbl:'Vendido', v:k.vendidos, c:'#6E7B72'},
          ]} total={k.total}/>
        </div>
      </div>

      <div className="card" style={{padding:0, overflow:'hidden'}}>
        <div style={{padding:'14px 20px', borderBottom:'1px solid var(--line-soft)'}}>
          <div className="eyebrow">◇ Últimas atividades</div>
        </div>
        <table style={{width:'100%', borderCollapse:'collapse', fontSize:12.5}}>
          <thead>
            <tr style={{background:'var(--bg-elev)'}}>
              <Th>Tempo</Th><Th>Tipo</Th><Th>Lote/Cliente</Th><Th>Corretor</Th><Th align="right">Valor</Th><Th align="right">Status</Th>
            </tr>
          </thead>
          <tbody>
            {[
              ['12 min', 'venda', 'Lote 4 · Henrique V.', 'Júlia M.', 214200, 'vendido'],
              ['35 min', 'pagamento', 'Lote 38 · Marcos P.', '—', 6317, 'pago'],
              ['1h', 'lead', 'Patrícia Nunes', 'Rafael P.', 0, 'lead'],
              ['2h', 'cobrança', 'Camila S. · Lote 9', '—', 7434, 'atraso'],
              ['3h', 'contrato', 'Lote 78 · Roberto M.', 'Rafael P.', 432000, 'contrato'],
              ['4h', 'reserva', 'Lote 88 · Ana R.', 'Júlia M.', 295880, 'reservado'],
              ['5h', 'simulação', 'Lote 9 · Carlos L.', 'Rafael P.', 446000, 'simulacao'],
              ['ontem', 'venda', 'Lote 22 · Vanessa L.', 'Diego A.', 215000, 'vendido'],
            ].map((r, i) => (
              <tr key={i} style={{borderTop:'1px solid var(--line-soft)'}}>
                <Td muted>{r[0]}</Td>
                <Td><span style={{padding:'2px 8px', background:'var(--bg-elev)', borderRadius:4, fontSize:11, fontWeight:600}}>{r[1]}</span></Td>
                <Td>{r[2]}</Td>
                <Td>{r[3]}</Td>
                <Td align="right" mono>{r[4] ? fmtBRL(r[4]) : '—'}</Td>
                <Td align="right"><StatusBadge type={r[6]==='vendido'||r[6]==='contrato'||r[6]==='pago' ? 'success' : r[6]==='atraso' ? 'warn' : 'muted'}>{r[6]}</StatusBadge></Td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

function Stat({lbl, v, sub, dark}) {
  return (
    <div>
      <div style={{fontSize:10.5, color: dark ? '#D9C7A8' : 'var(--ink-soft)', letterSpacing:1, textTransform:'uppercase', marginBottom:4}}>{lbl}</div>
      <div style={{fontSize:18, fontWeight:700, fontFamily:'var(--mono)', color: dark ? 'var(--bg-card)' : 'var(--green-deep)'}}>{v}</div>
      <div style={{fontSize:11, color: dark ? '#D9C7A8' : 'var(--ink-soft)', marginTop:2}}>{sub}</div>
    </div>
  );
}

function Atividade({icon, color, titulo, sub, tempo}) {
  return (
    <div style={{display:'flex', alignItems:'center', gap:14}}>
      <div style={{width:36, height:36, borderRadius:'50%', background:color, color:'white', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, opacity:0.9}}>
        <Icon name={icon} size={15}/>
      </div>
      <div style={{flex:1, minWidth:0}}>
        <div style={{fontSize:13.5, fontWeight:600}}>{titulo}</div>
        <div style={{fontSize:11.5, color:'var(--ink-soft)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{sub}</div>
      </div>
      <div style={{fontSize:11, color:'var(--ink-faint)', flexShrink:0, whiteSpace:'nowrap'}}>{tempo}</div>
    </div>
  );
}

function FunnelChart() {
  const data = [
    {lbl:'Leads', v:128, c:'#9CB5A2'},
    {lbl:'Visitas', v:54, c:'#7AA1AF'},
    {lbl:'Simulações', v:32, c:'#5B8FA8'},
    {lbl:'Propostas', v:21, c:'#C97B4A'},
    {lbl:'Reservas', v:15, c:'#A8632F'},
    {lbl:'Contratos', v:11, c:'#2D4F3C'},
  ];
  const max = data[0].v;
  return (
    <div style={{display:'flex', flexDirection:'column', gap:8}}>
      {data.map((d, i) => {
        const pct = d.v / max * 100;
        const conv = i > 0 ? (d.v / data[i-1].v * 100).toFixed(0) : null;
        return (
          <div key={d.lbl}>
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:4}}>
              <span style={{fontSize:12.5, fontWeight:600}}>{d.lbl}</span>
              <span style={{display:'flex', gap:8, alignItems:'baseline'}}>
                <span className="mono" style={{fontSize:14, fontWeight:700, color:'var(--green-deep)'}}>{d.v}</span>
                {conv && <span style={{fontSize:10.5, color:'var(--ink-soft)'}}>{conv}%</span>}
              </span>
            </div>
            <div style={{height:14, background:'var(--bg-elev)', borderRadius:3, overflow:'hidden'}}>
              <div style={{width:pct+'%', height:'100%', background:d.c, borderRadius:3}}/>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function DonutChart({data, total}) {
  const radius = 60, c = 2 * Math.PI * radius;
  let offset = 0;
  return (
    <div style={{display:'flex', gap:18, alignItems:'center'}}>
      <svg width="140" height="140" viewBox="0 0 140 140">
        <circle cx="70" cy="70" r={radius} fill="none" stroke="var(--bg-elev)" strokeWidth="22"/>
        {data.map((d, i) => {
          const pct = d.v / total;
          const dash = c * pct;
          const el = (
            <circle key={i} cx="70" cy="70" r={radius} fill="none" stroke={d.c}
              strokeWidth="22" strokeDasharray={`${dash} ${c}`}
              strokeDashoffset={-offset}
              transform="rotate(-90 70 70)"/>
          );
          offset += dash;
          return el;
        })}
        <text x="70" y="68" textAnchor="middle" fontFamily="var(--display)" fontSize="28" fontWeight="600" fill="var(--green-deep)">{total}</text>
        <text x="70" y="84" textAnchor="middle" fontSize="9" fill="var(--ink-soft)" letterSpacing="1">LOTES</text>
      </svg>
      <div style={{flex:1, display:'flex', flexDirection:'column', gap:6}}>
        {data.map(d => (
          <div key={d.lbl} style={{display:'flex', justifyContent:'space-between', alignItems:'center', fontSize:12}}>
            <span style={{display:'inline-flex', alignItems:'center', gap:6}}>
              <span style={{width:9, height:9, borderRadius:2, background:d.c}}/>
              {d.lbl}
            </span>
            <span className="mono" style={{fontWeight:600}}>{d.v}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Lotes ──────────────────────────────────────────────────
function BoLotes() {
  const [filtroStatus, setFiltroStatus] = useState(null);
  const [filtroQ, setFiltroQ] = useState(null);
  const [view, setView] = useState('mapa');
  const [hover, setHover] = useState(null);
  const [sel, setSel] = useState(null);
  const LOTES = window.BL.LOTES;
  const filtered = LOTES.filter(l =>
    (!filtroStatus || l.status === filtroStatus) &&
    (!filtroQ || l.quadra === filtroQ)
  );

  return (
    <div>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom:18}}>
        <div>
          <div className="eyebrow" style={{marginBottom:6}}>◇ Gestão</div>
          <h1 className="display" style={{fontSize:36, fontWeight:500, color:'var(--green-deep)'}}>Lotes</h1>
          <div style={{fontSize:13, color:'var(--ink-soft)', marginTop:4}}>95 lotes · 12 quadras · 67.345 m² comercializáveis</div>
        </div>
        <div style={{display:'flex', gap:6}}>
          <div style={{display:'flex', gap:0, background:'var(--bg-card)', padding:4, borderRadius:100, border:'1px solid var(--line)'}}>
            <button onClick={()=>setView('mapa')} className="btn btn-sm" style={{padding:'5px 12px', fontSize:11, background: view==='mapa' ? 'var(--green)' : 'transparent', color: view==='mapa' ? 'var(--bg-card)' : 'var(--ink-soft)'}}><Icon name="map" size={12}/></button>
            <button onClick={()=>setView('lista')} className="btn btn-sm" style={{padding:'5px 12px', fontSize:11, background: view==='lista' ? 'var(--green)' : 'transparent', color: view==='lista' ? 'var(--bg-card)' : 'var(--ink-soft)'}}><Icon name="list" size={12}/></button>
            <button onClick={()=>setView('grid')} className="btn btn-sm" style={{padding:'5px 12px', fontSize:11, background: view==='grid' ? 'var(--green)' : 'transparent', color: view==='grid' ? 'var(--bg-card)' : 'var(--ink-soft)'}}><Icon name="grid" size={12}/></button>
          </div>
          <button className="btn btn-sm btn-primary"><Icon name="plus" size={13}/> Novo lote</button>
        </div>
      </div>

      {/* Filter bar */}
      <div style={{display:'flex', gap:8, marginBottom:18, flexWrap:'wrap', alignItems:'center'}}>
        {['disponivel','reservado','negociacao','vendido'].map(s => (
          <button key={s} onClick={()=>setFiltroStatus(filtroStatus===s ? null : s)}
            style={{padding:'5px 11px', borderRadius:100, fontSize:11.5, fontWeight:600,
              background: filtroStatus===s ? 'var(--green)' : 'var(--bg-card)',
              color: filtroStatus===s ? 'var(--bg-card)' : 'var(--ink-soft)',
              border:'1px solid ' + (filtroStatus===s ? 'var(--green)' : 'var(--line)')}}>
            {window.STATUS_LABELS[s]} · {LOTES.filter(l => l.status === s).length}
          </button>
        ))}
        <div style={{width:1, height:20, background:'var(--line)', margin:'0 4px'}}/>
        {['A','B','C','D','E','F','G','H','I','J','K','L'].map(q => (
          <button key={q} onClick={()=>setFiltroQ(filtroQ===q ? null : q)}
            style={{
              width:28, height:28, borderRadius:'50%', fontSize:11, fontWeight:700,
              background: filtroQ===q ? 'var(--terra)' : 'var(--bg-card)',
              color: filtroQ===q ? 'var(--bg-card)' : 'var(--ink-soft)',
              border:'1px solid ' + (filtroQ===q ? 'var(--terra)' : 'var(--line)')
            }}>{q}</button>
        ))}
        <div style={{flex:1}}/>
        <div style={{fontSize:12, color:'var(--ink-soft)'}}>{filtered.length} de {LOTES.length}</div>
      </div>

      {view === 'mapa' && (
        <div style={{display:'grid', gridTemplateColumns:'minmax(0, 2.4fr) minmax(280px, 1fr)', gap:18}}>
          <div className="card" style={{padding:8}}>
            <MapaLoteamento estilo="tecnico" filtroStatus={filtroStatus} hover={hover} onHover={setHover} onSelect={setSel} selecionado={sel}/>
          </div>
          <div className="card" style={{padding:24}}>
            {sel ? (
              <BoLoteDetail loteNum={sel} onClose={()=>setSel(null)}/>
            ) : hover ? (
              <BoLotePreview loteNum={hover}/>
            ) : (
              <div style={{textAlign:'center', padding:'40px 20px', color:'var(--ink-faint)'}}>
                <Icon name="pin" size={48} stroke={1}/>
                <div style={{marginTop:14, fontSize:13.5}}>Passe o mouse ou clique em um lote</div>
              </div>
            )}
          </div>
        </div>
      )}

      {view === 'lista' && (
        <div className="card" style={{padding:0, overflow:'hidden'}}>
          <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
            <thead>
              <tr style={{background:'var(--bg-elev)'}}>
                <Th>Lote</Th><Th>Quadra</Th><Th align="right">Área</Th><Th align="right">Frente</Th>
                <Th align="right">R$/m²</Th><Th align="right">Valor</Th>
                <Th>Vista</Th><Th>Status</Th><Th align="right">Ações</Th>
              </tr>
            </thead>
            <tbody>
              {filtered.slice(0, 30).map(l => (
                <tr key={l.numero} style={{borderTop:'1px solid var(--line-soft)'}}>
                  <Td mono><strong>{l.numero}</strong></Td>
                  <Td>{l.quadra}</Td>
                  <Td align="right" mono>{l.area.toFixed(0)}m²</Td>
                  <Td align="right" mono>{l.frente.toFixed(1)}m</Td>
                  <Td align="right" mono>R$ {l.precoM2}</Td>
                  <Td align="right" mono><strong>{fmtBRL(l.valorTotal)}</strong></Td>
                  <Td>{l.vistaLago ? '🌊 Lago' : 'Interior'}</Td>
                  <Td><StatusPill status={l.status} size="sm"/></Td>
                  <Td align="right">
                    <button className="btn btn-sm btn-ghost" onClick={()=>setSel(l.numero)}><Icon name="eye" size={13}/></button>
                    <button className="btn btn-sm btn-ghost"><Icon name="edit" size={13}/></button>
                  </Td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {view === 'grid' && (
        <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(180px, 1fr))', gap:10}}>
          {filtered.map(l => (
            <div key={l.numero} onClick={()=>setSel(l.numero)} className="card" style={{padding:14, cursor:'pointer', position:'relative'}}>
              <div style={{position:'absolute', top:10, right:10}}><StatusPill status={l.status} size="sm"/></div>
              <div className="eyebrow" style={{fontSize:9, marginBottom:6}}>Quadra {l.quadra}</div>
              <div className="display" style={{fontSize:28, color:'var(--green-deep)', fontWeight:500, lineHeight:1, marginBottom:8}}>Lote {l.numero}</div>
              <div className="mono" style={{fontSize:11, color:'var(--ink-soft)', marginBottom:8}}>
                {l.area.toFixed(0)} m² · {l.frente.toFixed(1)}m
              </div>
              <div className="mono" style={{fontSize:14, fontWeight:700, color:'var(--green-deep)'}}>{fmtBRL(l.valorTotal)}</div>
            </div>
          ))}
        </div>
      )}

      {/* Modal de detalhe */}
      <Modal open={!!sel && view === 'lista'} onClose={()=>setSel(null)} width={520}>
        {sel && <div style={{padding:28}}><BoLoteDetail loteNum={sel} onClose={()=>setSel(null)}/></div>}
      </Modal>
    </div>
  );
}

function BoLotePreview({loteNum}) {
  const l = window.BL.LOTE_BY_NUM[loteNum];
  return (
    <>
      <div className="eyebrow">◇ Lote {l.numero} · Quadra {l.quadra}</div>
      <div className="display" style={{fontSize:32, color:'var(--green-deep)', fontWeight:500, marginTop:6, marginBottom:10}}>
        {fmtBRL(l.valorTotal)}
      </div>
      <StatusPill status={l.status}/>
      <div style={{marginTop:18, fontSize:13, color:'var(--ink-soft)'}}>
        {l.area.toFixed(0)} m² · {l.frente.toFixed(1)}m de frente · R$ {l.precoM2}/m²
      </div>
    </>
  );
}

function BoLoteDetail({loteNum, onClose}) {
  const l = window.BL.LOTE_BY_NUM[loteNum];
  return (
    <div>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:18}}>
        <div>
          <div className="eyebrow">◇ Quadra {l.quadra}</div>
          <div className="display" style={{fontSize:32, color:'var(--green-deep)', fontWeight:500}}>Lote {l.numero}</div>
        </div>
        <button className="btn btn-sm btn-ghost" onClick={onClose}><Icon name="x" size={16}/></button>
      </div>
      <StatusPill status={l.status}/>
      <div style={{height:1, background:'var(--line-soft)', margin:'18px 0'}}/>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginBottom:18}}>
        <Stat lbl="Área" v={`${l.area.toFixed(0)} m²`} sub="dimensão total"/>
        <Stat lbl="Valor" v={fmtBRL(l.valorTotal)} sub={`R$ ${l.precoM2}/m²`}/>
        <Stat lbl="Frente" v={`${l.frente.toFixed(1)}m`} sub={l.vistaLago ? 'frente lago' : 'interior'}/>
        <Stat lbl="Fundo" v={`${l.fundo.toFixed(1)}m`}/>
      </div>
      <div style={{display:'flex', flexDirection:'column', gap:8}}>
        <button className="btn btn-primary"><Icon name="edit" size={13}/> Editar lote</button>
        {l.status === 'disponivel' && <button className="btn btn-secondary"><Icon name="pin" size={13}/> Reservar manualmente</button>}
        {l.status === 'vendido' && <button className="btn btn-secondary"><Icon name="user" size={13}/> Ver comprador</button>}
        <button className="btn btn-ghost"><Icon name="file" size={13}/> Histórico</button>
      </div>
    </div>
  );
}

const Th = ({children, align='left'}) => <th style={{padding:'12px 16px', textAlign:align, fontSize:10.5, fontWeight:700, letterSpacing:1, textTransform:'uppercase', color:'var(--ink-soft)', borderBottom:'1px solid var(--line)'}}>{children}</th>;
const Td = ({children, align='left', mono, muted}) => <td style={{padding:'12px 16px', textAlign:align, fontFamily: mono ? 'var(--mono)' : 'inherit', color: muted ? 'var(--ink-soft)' : 'var(--ink)'}}>{children}</td>;

// ─── CRM / Funil ────────────────────────────────────────────
function BoCrm() {
  const [view, setView] = useState('kanban');
  return (
    <div>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom:24}}>
        <div>
          <div className="eyebrow" style={{marginBottom:6}}>◇ Vendas</div>
          <h1 className="display" style={{fontSize:36, fontWeight:500, color:'var(--green-deep)'}}>Funil & CRM</h1>
        </div>
        <div style={{display:'flex', gap:6}}>
          <div style={{display:'flex', gap:0, background:'var(--bg-card)', padding:4, borderRadius:100, border:'1px solid var(--line)'}}>
            {[['kanban','Kanban','grid'],['lista','Lista','list']].map(([k, lbl, ic]) => (
              <button key={k} onClick={()=>setView(k)} className="btn btn-sm" style={{padding:'5px 12px', fontSize:11, background: view===k ? 'var(--green)' : 'transparent', color: view===k ? 'var(--bg-card)' : 'var(--ink-soft)'}}><Icon name={ic} size={12}/> {lbl}</button>
            ))}
          </div>
          <button className="btn btn-sm btn-primary"><Icon name="plus" size={13}/> Novo lead</button>
        </div>
      </div>

      {view === 'kanban' ? <CrmKanban/> : <CrmLista/>}
    </div>
  );
}

function CrmKanban() {
  const etapas = window.BL.ETAPAS_FUNIL;
  const leads = window.BL.LEADS;
  return (
    <div style={{display:'grid', gridTemplateColumns:'repeat(6, minmax(220px, 1fr))', gap:14, overflowX:'auto', minHeight:'60vh'}}>
      {etapas.map(e => {
        const ls = leads.filter(l => l.etapa === e.id);
        const totalVal = ls.reduce((s,l)=>s+l.valor, 0);
        return (
          <div key={e.id} style={{
            background:'var(--bg-card)', borderRadius:14,
            border:'1px solid var(--line-soft)', display:'flex', flexDirection:'column'
          }}>
            <div style={{padding:'14px 16px', borderBottom:'1px solid var(--line-soft)'}}>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:6}}>
                <div style={{display:'inline-flex', alignItems:'center', gap:6, fontWeight:700, fontSize:13}}>
                  <span style={{width:8, height:8, borderRadius:2, background:e.cor}}/>
                  {e.nome}
                </div>
                <span className="mono" style={{fontSize:11.5, fontWeight:700, color:'var(--ink-soft)'}}>{ls.length}</span>
              </div>
              <div className="mono" style={{fontSize:11, color:'var(--ink-soft)'}}>{totalVal > 0 ? fmtBRL(totalVal) : '—'}</div>
            </div>
            <div style={{padding:10, display:'flex', flexDirection:'column', gap:8, flex:1}}>
              {ls.map(l => (
                <div key={l.id} style={{
                  padding:'12px 14px', background:'var(--bg-elev)', borderRadius:10,
                  border:'1px solid var(--line-soft)', cursor:'grab'
                }}>
                  <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:6}}>
                    <div>
                      <div style={{fontSize:13, fontWeight:600}}>{l.nome}</div>
                      <div style={{fontSize:11, color:'var(--ink-soft)', marginTop:2}}>{l.cidade}</div>
                    </div>
                    {l.lote && <div style={{padding:'2px 6px', background:'var(--green-soft)', borderRadius:4, fontSize:10, fontWeight:700, color:'var(--green-deep)'}}>L{l.lote}</div>}
                  </div>
                  {l.valor > 0 && <div className="mono" style={{fontSize:12, fontWeight:700, color:'var(--green-deep)', marginBottom:6}}>{fmtBRL(l.valor)}</div>}
                  <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', fontSize:10.5, color:'var(--ink-soft)'}}>
                    <span>{l.corretor}</span>
                    <span>{l.ultimoContato}</span>
                  </div>
                </div>
              ))}
              <button style={{padding:'10px 14px', border:'1px dashed var(--line)', borderRadius:10, fontSize:11.5, color:'var(--ink-faint)', cursor:'pointer', background:'transparent'}}>
                <Icon name="plus" size={11}/> Adicionar
              </button>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function CrmLista() {
  return (
    <div className="card" style={{padding:0, overflow:'hidden'}}>
      <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
        <thead>
          <tr style={{background:'var(--bg-elev)'}}>
            <Th>Lead</Th><Th>Cidade</Th><Th>Interesse</Th><Th>Origem</Th><Th>Etapa</Th><Th>Lote</Th><Th align="right">Valor</Th><Th>Corretor</Th><Th>Último</Th>
          </tr>
        </thead>
        <tbody>
          {window.BL.LEADS.map(l => (
            <tr key={l.id} style={{borderTop:'1px solid var(--line-soft)'}}>
              <Td><strong>{l.nome}</strong></Td>
              <Td muted>{l.cidade}</Td>
              <Td>{l.interesse}</Td>
              <Td muted>{l.origem}</Td>
              <Td>{window.BL.ETAPAS_FUNIL.find(e => e.id === l.etapa)?.nome}</Td>
              <Td mono>{l.lote || '—'}</Td>
              <Td align="right" mono>{l.valor > 0 ? fmtBRL(l.valor) : '—'}</Td>
              <Td muted>{l.corretor}</Td>
              <Td muted>{l.ultimoContato}</Td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ─── Carteira ───────────────────────────────────────────────
function BoCarteira() {
  return (
    <div>
      <SectionHeader eyebrow="◇ Pós-venda" title="Carteira de clientes" sub={`${window.BL.CLIENTES.length} contratos ativos · ${fmtBRL(window.BL.CLIENTES.reduce((s,c)=>s+c.valorContrato,0))} em carteira`}/>

      <div className="card" style={{padding:0, overflow:'hidden'}}>
        <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
          <thead>
            <tr style={{background:'var(--bg-elev)'}}>
              <Th>Cliente</Th><Th>Lote</Th><Th align="right">Contrato</Th><Th>Andamento</Th><Th>Status</Th><Th>Próx. boleto</Th><Th align="right">Ações</Th>
            </tr>
          </thead>
          <tbody>
            {window.BL.CLIENTES.map(c => {
              const pct = c.parcelasPagas / c.parcelasTotal * 100;
              return (
                <tr key={c.id} style={{borderTop:'1px solid var(--line-soft)'}}>
                  <Td>
                    <div style={{display:'flex', alignItems:'center', gap:10}}>
                      <div style={{width:32, height:32, borderRadius:'50%', background:'var(--terra)', color:'white', display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:700}}>{c.nome.split(' ').map(x=>x[0]).slice(0,2).join('')}</div>
                      <div><strong>{c.nome}</strong></div>
                    </div>
                  </Td>
                  <Td mono>L{c.lote} · Q.{window.BL.LOTE_BY_NUM[c.lote]?.quadra}</Td>
                  <Td align="right" mono><strong>{fmtBRL(c.valorContrato)}</strong></Td>
                  <Td>
                    <div style={{display:'flex', alignItems:'center', gap:8}}>
                      <div style={{width:80, height:5, background:'var(--bg-elev)', borderRadius:100, overflow:'hidden'}}>
                        <div style={{width:pct+'%', height:'100%', background: c.status==='adimplente' ? 'var(--green)' : 'var(--terra)'}}/>
                      </div>
                      <span style={{fontSize:11, color:'var(--ink-soft)'}} className="mono">{c.parcelasPagas}/{c.parcelasTotal}</span>
                    </div>
                  </Td>
                  <Td><StatusPill status={c.status} size="sm"/></Td>
                  <Td>{c.proxBoleto} {c.atraso > 0 && <span style={{color:'var(--danger)', fontSize:11}}>· {c.atraso}d atraso</span>}</Td>
                  <Td align="right">
                    <button className="btn btn-sm btn-ghost"><Icon name="eye" size={13}/></button>
                    <button className="btn btn-sm btn-ghost"><Icon name="mail" size={13}/></button>
                  </Td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── Cobrança ───────────────────────────────────────────────
function BoCobranca() {
  const atrasados = window.BL.CLIENTES.filter(c => c.atraso > 0).sort((a,b)=>b.atraso-a.atraso);
  return (
    <div>
      <SectionHeader eyebrow="◇ Régua de cobrança" title="Cobrança & inadimplência" sub="Boletos vencidos, régua automática e ações manuais"/>

      <div style={{display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:14, marginBottom:24}}>
        <KpiCard label="Em atraso" value={atrasados.length + ' clientes'} sub={`${fmtBRL(atrasados.reduce((s,c)=>s+c.valorContrato*0.8/48, 0))} a receber`} icon="warn" color="var(--terra)"/>
        <KpiCard label="Maior atraso" value={Math.max(...atrasados.map(c=>c.atraso)) + ' dias'} sub="Sílvia Maia · Lote 56" icon="clock" color="var(--danger)"/>
        <KpiCard label="Régua ativa" value="48 envios" sub="Esta semana · WhatsApp + e-mail" icon="mail"/>
        <KpiCard label="Recuperação" value="73%" sub="dos últimos 30 dias" icon="check" color="var(--success)" trend={{dir:'up', value:'+8pp'}}/>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'minmax(0, 2fr) minmax(280px, 1fr)', gap:18}}>
        <div className="card" style={{padding:0, overflow:'hidden'}}>
          <div style={{padding:'14px 20px', borderBottom:'1px solid var(--line-soft)', display:'flex', justifyContent:'space-between'}}>
            <div className="eyebrow">◇ Clientes em atraso</div>
            <button className="btn btn-sm btn-primary"><Icon name="mail" size={12}/> Enviar régua p/ todos</button>
          </div>
          <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
            <thead>
              <tr style={{background:'var(--bg-elev)'}}>
                <Th>Cliente</Th><Th>Lote</Th><Th>Atraso</Th><Th align="right">Valor</Th><Th>Última ação</Th><Th align="right">Ações</Th>
              </tr>
            </thead>
            <tbody>
              {atrasados.map(c => (
                <tr key={c.id} style={{borderTop:'1px solid var(--line-soft)'}}>
                  <Td><strong>{c.nome}</strong></Td>
                  <Td mono>L{c.lote}</Td>
                  <Td>
                    <span style={{padding:'3px 9px', borderRadius:100, fontSize:11, fontWeight:700,
                      background: c.atraso > 30 ? '#F4CFC9' : 'var(--terra-soft)',
                      color: c.atraso > 30 ? '#8B2A1F' : 'var(--terra-deep)'}}>{c.atraso} dias</span>
                  </Td>
                  <Td align="right" mono>{fmtBRL(c.valorContrato * 0.8 / 48)}</Td>
                  <Td muted style={{fontSize:11.5}}>WhatsApp · há 2d</Td>
                  <Td align="right">
                    <button className="btn btn-sm btn-secondary"><Icon name="phone" size={12}/></button>
                    <button className="btn btn-sm btn-secondary"><Icon name="mail" size={12}/></button>
                    <button className="btn btn-sm btn-secondary">2ª via</button>
                  </Td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="card" style={{padding:24}}>
          <div className="eyebrow" style={{marginBottom:14}}>◇ Régua automática</div>
          {[
            ['D-3', 'Lembrete amigável', 'WhatsApp', 'var(--green)'],
            ['D-1', 'Lembrete urgente', 'E-mail + WhatsApp', 'var(--lago)'],
            ['D+1', 'Primeira cobrança', 'E-mail', 'var(--terra)'],
            ['D+7', 'Cobrança formal', 'E-mail + WhatsApp', 'var(--terra-deep)'],
            ['D+15', 'Notificação extrajudicial', 'Carta + e-mail', 'var(--danger)'],
            ['D+30', 'Protesto + escritório', 'Manual', '#8B2A1F'],
          ].map(([d, t, ch, c]) => (
            <div key={d} style={{display:'flex', alignItems:'center', gap:12, padding:'10px 0', borderBottom:'1px solid var(--line-soft)'}}>
              <div className="mono" style={{width:38, fontSize:12, fontWeight:700, color:c}}>{d}</div>
              <div style={{flex:1}}>
                <div style={{fontSize:13, fontWeight:600}}>{t}</div>
                <div style={{fontSize:11, color:'var(--ink-soft)'}}>{ch}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─── Financeiro ─────────────────────────────────────────────
function BoFinanceiro() {
  return (
    <div>
      <SectionHeader eyebrow="◇ Caixa" title="Financeiro" sub="Fluxo de caixa, recebíveis e comissões"/>

      <div style={{display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:14, marginBottom:24}}>
        <KpiCard label="Recebido · maio" value={fmtBRL(485600)} sub="48 boletos pagos" icon="coin" color="var(--success)" trend={{dir:'up', value:'+12% vs abr'}}/>
        <KpiCard label="A receber" value={fmtBRL(295880)} sub="14 boletos · até 31/mai" icon="invoice"/>
        <KpiCard label="Comissões · maio" value={fmtBRL(62400)} sub="3 corretores · 4% sobre vendas" icon="users"/>
        <KpiCard label="Saldo operacional" value={fmtBRL(1240000)} sub="conta empreendimento" icon="briefcase" color="var(--lago)"/>
      </div>

      <div className="card" style={{padding:24, marginBottom:18}}>
        <div className="eyebrow" style={{marginBottom:18}}>◇ Fluxo de caixa · 12 meses</div>
        <CashflowChart/>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:18}}>
        <div className="card" style={{padding:0, overflow:'hidden'}}>
          <div style={{padding:'14px 20px', borderBottom:'1px solid var(--line-soft)'}}>
            <div className="eyebrow">◇ Comissões a pagar</div>
          </div>
          <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
            <thead><tr style={{background:'var(--bg-elev)'}}><Th>Corretor</Th><Th>Vendas</Th><Th align="right">VGV</Th><Th align="right">Comissão</Th></tr></thead>
            <tbody>
              {[
                ['Júlia Mendes', 8, 1850000, 74000],
                ['Rafael Pinto', 6, 1420000, 56800],
                ['Diego Aragão', 4, 980000, 39200],
              ].map((r,i) => (
                <tr key={i} style={{borderTop:'1px solid var(--line-soft)'}}>
                  <Td><strong>{r[0]}</strong></Td>
                  <Td mono>{r[1]}</Td>
                  <Td align="right" mono>{fmtBRL(r[2])}</Td>
                  <Td align="right" mono><strong style={{color:'var(--terra-deep)'}}>{fmtBRL(r[3])}</strong></Td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="card" style={{padding:0, overflow:'hidden'}}>
          <div style={{padding:'14px 20px', borderBottom:'1px solid var(--line-soft)'}}>
            <div className="eyebrow">◇ Despesas operacionais · mai</div>
          </div>
          <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
            <thead><tr style={{background:'var(--bg-elev)'}}><Th>Categoria</Th><Th align="right">Mês</Th><Th align="right">Acum.</Th></tr></thead>
            <tbody>
              {[
                ['Obra · pavimentação', 184000, 920000],
                ['Obra · rede elétrica', 68000, 312000],
                ['Marketing · ads', 12000, 64000],
                ['Comissões corretores', 62400, 280000],
                ['Folha + impostos', 38000, 190000],
                ['Manutenção portaria', 8400, 42000],
              ].map((r,i) => (
                <tr key={i} style={{borderTop:'1px solid var(--line-soft)'}}>
                  <Td>{r[0]}</Td>
                  <Td align="right" mono>{fmtBRL(r[1])}</Td>
                  <Td align="right" mono muted>{fmtBRL(r[2])}</Td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function CashflowChart() {
  const data = [
    {m:'Jun/25', in:280000, out:240000},
    {m:'Jul/25', in:320000, out:260000},
    {m:'Ago/25', in:380000, out:280000},
    {m:'Set/25', in:410000, out:300000},
    {m:'Out/25', in:445000, out:310000},
    {m:'Nov/25', in:420000, out:320000},
    {m:'Dez/25', in:380000, out:330000},
    {m:'Jan/26', in:435000, out:280000},
    {m:'Fev/26', in:460000, out:300000},
    {m:'Mar/26', in:475000, out:340000},
    {m:'Abr/26', in:432000, out:340000},
    {m:'Mai/26', in:485600, out:372400},
  ];
  const max = Math.max(...data.flatMap(d=>[d.in, d.out]));
  return (
    <div style={{display:'flex', alignItems:'flex-end', gap:14, height:200, padding:'0 4px'}}>
      {data.map(d => (
        <div key={d.m} style={{flex:1, display:'flex', flexDirection:'column', alignItems:'center'}}>
          <div style={{height:160, width:'100%', display:'flex', gap:3, alignItems:'flex-end'}}>
            <div style={{flex:1, height:`${d.in/max*100}%`, background:'var(--green)', borderRadius:'3px 3px 0 0'}} title={`Entrada: ${fmtBRL(d.in)}`}/>
            <div style={{flex:1, height:`${d.out/max*100}%`, background:'var(--terra)', borderRadius:'3px 3px 0 0'}} title={`Saída: ${fmtBRL(d.out)}`}/>
          </div>
          <div style={{fontSize:10, color:'var(--ink-soft)', marginTop:8, fontFamily:'var(--mono)'}}>{d.m}</div>
        </div>
      ))}
    </div>
  );
}

// ─── Documentos ─────────────────────────────────────────────
function BoDocs() {
  return (
    <div>
      <SectionHeader eyebrow="◇ Repositório" title="Documentos & contratos" sub="Contratos assinados, anexos legais, plantas e memoriais"/>
      <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(260px, 1fr))', gap:14, marginBottom:24}}>
        {[
          ['Contratos assinados', 47, 'file', 'var(--green)'],
          ['Aguardando assinatura', 6, 'edit', 'var(--terra)'],
          ['Plantas técnicas', 12, 'layers', 'var(--lago)'],
          ['Convenção condomínio', 1, 'file', 'var(--green-deep)'],
          ['Memoriais descritivos', 4, 'file', 'var(--ink-soft)'],
          ['Licenças e alvarás', 8, 'check', 'var(--success)'],
        ].map(([t, n, ic, c]) => (
          <div key={t} className="card" style={{padding:20, display:'flex', gap:14, alignItems:'center', cursor:'pointer'}}>
            <div style={{width:46, height:46, borderRadius:10, background:c, color:'var(--bg-card)', display:'flex', alignItems:'center', justifyContent:'center'}}><Icon name={ic} size={20}/></div>
            <div style={{flex:1}}>
              <div style={{fontSize:13.5, fontWeight:700}}>{t}</div>
              <div className="mono" style={{fontSize:11, color:'var(--ink-soft)'}}>{n} {n === 1 ? 'documento' : 'documentos'}</div>
            </div>
            <Icon name="chevR" size={14}/>
          </div>
        ))}
      </div>

      <div className="card" style={{padding:0, overflow:'hidden'}}>
        <div style={{padding:'14px 20px', borderBottom:'1px solid var(--line-soft)', display:'flex', justifyContent:'space-between'}}>
          <div className="eyebrow">◇ Atividade recente</div>
          <button className="btn btn-sm btn-primary"><Icon name="upload" size={12}/> Upload</button>
        </div>
        <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
          <thead><tr style={{background:'var(--bg-elev)'}}><Th>Documento</Th><Th>Tipo</Th><Th>Cliente</Th><Th>Tamanho</Th><Th>Data</Th><Th>Status</Th></tr></thead>
          <tbody>
            {[
              ['contrato-lote-04-vasconcelos.pdf', 'Contrato', 'Henrique Vasconcelos', '2.1 MB', 'hoje 11:42', 'assinado'],
              ['boleto-parcela-30-pinto.pdf', 'Boleto', 'Rodrigo Pinto', '180 KB', 'hoje 09:15', 'pago'],
              ['rg-rocha-frente.jpg', 'Documento pessoal', 'Ana Carolina Rocha', '850 KB', 'ontem 17:20', 'recebido'],
              ['planta-lote-93.pdf', 'Planta', 'João Pedro Sá', '720 KB', '20/mai 14:30', 'enviado'],
              ['memorial-empreendimento-v3.pdf', 'Memorial', '—', '4.2 MB', '18/mai', 'publicado'],
            ].map((r, i) => (
              <tr key={i} style={{borderTop:'1px solid var(--line-soft)'}}>
                <Td><span style={{display:'inline-flex', alignItems:'center', gap:8}}><Icon name="file" size={13}/> {r[0]}</span></Td>
                <Td muted>{r[1]}</Td>
                <Td>{r[2]}</Td>
                <Td muted className="mono">{r[3]}</Td>
                <Td muted>{r[4]}</Td>
                <Td><StatusBadge type={r[5]==='pago'||r[5]==='assinado'||r[5]==='publicado' ? 'success' : 'muted'}>{r[5]}</StatusBadge></Td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── Relatórios ─────────────────────────────────────────────
function BoRelatorios() {
  return (
    <div>
      <SectionHeader eyebrow="◇ Insights" title="Relatórios" sub="Exporte relatórios pré-construídos ou monte seu próprio dashboard"/>

      <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(280px, 1fr))', gap:14}}>
        {[
          ['Vendas do mês', 'Detalhes de cada venda, comissão, ticket médio', 'mai/2026', 'PDF'],
          ['VGV por quadra', 'Distribuição de valor de venda por bloco', 'tempo real', 'XLSX'],
          ['Funil de conversão', 'Lead → visita → simulação → contrato', '90 dias', 'PDF'],
          ['Inadimplência detalhada', 'Por cliente, idade da dívida, ações da régua', 'mai/2026', 'PDF'],
          ['Andamento da obra', 'Cronograma físico-financeiro', 'tempo real', 'PDF'],
          ['Comissões pagas', 'Por corretor e período', 'mai/2026', 'XLSX'],
          ['Vendas por origem', 'Eficiência de canais de marketing', '90 dias', 'PDF'],
          ['Demonstrativo de caixa', 'Entradas e saídas mensais', 'maio', 'PDF'],
        ].map(([t, sub, periodo, fmt]) => (
          <div key={t} className="card" style={{padding:22, cursor:'pointer', display:'flex', flexDirection:'column', gap:8}}>
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start'}}>
              <div style={{fontSize:14.5, fontWeight:700}}>{t}</div>
              <span style={{padding:'2px 8px', background:'var(--green-soft)', color:'var(--green-deep)', borderRadius:4, fontSize:10, fontWeight:700}}>{fmt}</span>
            </div>
            <div style={{fontSize:12, color:'var(--ink-soft)', lineHeight:1.5, flex:1}}>{sub}</div>
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:8}}>
              <span style={{fontSize:11, color:'var(--ink-faint)'}}>{periodo}</span>
              <button className="btn btn-sm btn-secondary"><Icon name="download" size={12}/> Baixar</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

window.BackofficeApp = BackofficeApp;
