// Brisas do Lago — fluxo do comprador (visitante)
// Mapa → Detalhe → Simulador → Reservar → Cadastro → Assinatura → Pagamento

const { useState, useEffect, useRef, useMemo } = React;

// ─── Hero / Landing antes do mapa ─────────────────────────────────
function BuyerHero({onExplore}) {
  return (
    <div style={{
      padding: '60px 28px 40px',
      maxWidth: 1400, margin: '0 auto',
      display: 'grid', gridTemplateColumns: 'minmax(0, 1.1fr) minmax(0, 1fr)', gap: 60, alignItems: 'center'
    }} className="hero-grid">
      <div>
        <div className="eyebrow" style={{marginBottom:18, color:'var(--terra-deep)'}}>
          ◇ Loteamento de veraneio · Lagoa do Cassó
        </div>
        <h1 className="display" style={{fontSize: 'clamp(40px, 6vw, 78px)', lineHeight: 0.95, color: 'var(--green-deep)', marginBottom: 22, textWrap: 'balance'}}>
          Seu pedaço<br/>
          de <em style={{fontStyle:'italic', color:'var(--terra)'}}>maranhão</em><br/>
          à beira do lago.
        </h1>
        <p style={{fontSize: 17, color: 'var(--ink-soft)', lineHeight: 1.55, maxWidth: 480, marginBottom: 28}}>
          95 lotes de veraneio entre as Trilhas e a Lagoa do Cassó.
          Píer privativo, portaria 24h e poço artesiano com distribuição individual.
        </p>
        <div style={{display:'flex', gap:12, flexWrap:'wrap'}}>
          <button className="btn btn-primary btn-lg" onClick={onExplore}>
            <Icon name="map" size={16}/> Explorar o mapa
          </button>
          <button className="btn btn-secondary btn-lg">
            <Icon name="phone" size={14}/> Falar com corretor
          </button>
        </div>
        <div style={{display:'flex', gap: 28, marginTop:36, paddingTop: 28, borderTop:'1px solid var(--line)'}}>
          {[
            ['95', 'lotes'],
            ['12', 'quadras'],
            ['28.013', 'm² verde'],
            ['48x', 'sem juros'],
          ].map(([n, l]) => (
            <div key={l}>
              <div className="display" style={{fontSize:28, fontWeight:500, color:'var(--green-deep)'}}>{n}</div>
              <div style={{fontSize:11, color:'var(--ink-soft)', textTransform:'uppercase', letterSpacing:1.2}}>{l}</div>
            </div>
          ))}
        </div>
      </div>
      <div style={{position:'relative', minHeight: 460}}>
        <PhotoPlaceholder type="lago" height={460} label="Lagoa do Cassó · vista do píer"/>
        <div style={{
          position:'absolute', bottom: -28, left: -28,
          background: 'var(--bg-card)', padding: 18, borderRadius: 14,
          boxShadow: 'var(--shadow-2)', maxWidth: 260,
          border:'1px solid var(--line-soft)'
        }}>
          <div className="eyebrow" style={{color:'var(--terra-deep)', marginBottom:6}}>◐ Diferencial</div>
          <div style={{fontFamily:'var(--display)', fontSize:18, color:'var(--green-deep)', fontWeight:500, lineHeight:1.25}}>
            34 lotes com frente direta para a lagoa
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Mapa + filtros + lista lateral ─────────────────────────────
function BuyerMap({onSelect}) {
  const [estilo, setEstilo] = useState('tecnico');
  const [filtroStatus, setFiltroStatus] = useState('disponivel');
  const [filtroVista, setFiltroVista] = useState(null);
  const [filtroQuadra, setFiltroQuadra] = useState(null);
  const [precoMax, setPrecoMax] = useState(700);
  const [areaMin, setAreaMin] = useState(0);
  const [hover, setHover] = useState(null);
  const [variation, setVariation] = useState('A'); // A: mapa+lista, B: cards

  // React ao tweak global de estilo do mapa
  useEffect(() => {
    const onTweak = (e) => {
      if (e.detail?.mapStyle) setEstilo(e.detail.mapStyle);
    };
    window.addEventListener('tweakchange', onTweak);
    return () => window.removeEventListener('tweakchange', onTweak);
  }, []);

  const LOTES = window.BL.LOTES;
  const filtered = LOTES.filter(l => {
    if (filtroStatus && l.status !== filtroStatus) return false;
    if (filtroVista === 'lago' && !l.vistaLago) return false;
    if (filtroVista === 'interior' && l.vistaLago) return false;
    if (filtroQuadra && l.quadra !== filtroQuadra) return false;
    if (l.precoM2 > precoMax) return false;
    if (l.area < areaMin) return false;
    return true;
  });

  const quadras = Array.from(new Set(LOTES.map(l => l.quadra))).sort();

  return (
    <div style={{padding:'0 28px 80px', maxWidth: 1500, margin:'0 auto'}}>
      <SectionHeader
        eyebrow="◐ Mapa de disponibilidade"
        title="Escolha seu lote"
        sub="Clique em qualquer lote disponível para ver dimensões, preço e simular condições. Use os filtros para refinar."
        action={
          <div style={{display:'flex', gap:8}}>
            <button className={"btn btn-sm " + (variation==='A' ? 'btn-primary':'btn-secondary')} onClick={()=>setVariation('A')}>
              <Icon name="map" size={13}/> Mapa
            </button>
            <button className={"btn btn-sm " + (variation==='B' ? 'btn-primary':'btn-secondary')} onClick={()=>setVariation('B')}>
              <Icon name="grid" size={13}/> Galeria
            </button>
          </div>
        }
      />

      {/* Filter bar */}
      <div style={{
        display:'flex', flexWrap:'wrap', gap: 10, marginBottom: 22,
        padding: '14px 16px', background:'var(--bg-card)', borderRadius: 14,
        border:'1px solid var(--line-soft)', alignItems:'center',
      }}>
        <div style={{fontSize:11, fontWeight:700, letterSpacing:1, color:'var(--ink-soft)', textTransform:'uppercase', marginRight:6}}>Filtros</div>

        {/* Status chips */}
        {['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-elev)',
              color: filtroStatus === s ? 'var(--bg-card)' : 'var(--ink-soft)',
              border: '1px solid ' + (filtroStatus === s ? 'var(--green)' : 'var(--line)'),
              cursor:'pointer', whiteSpace:'nowrap'
            }}>
            <span style={{width:6, height:6, display:'inline-block', borderRadius:50,
              marginRight:6, verticalAlign:'middle',
              background: s==='disponivel' ? 'var(--green)' : s==='reservado' ? 'var(--terra)' : s==='negociacao' ? 'var(--lago)' : '#6E7B72'
            }}/>
            {window.STATUS_LABELS[s]}
          </button>
        ))}

        <div style={{width:1, height:24, background:'var(--line)', margin:'0 4px'}}/>

        {/* Vista */}
        <button onClick={() => setFiltroVista(filtroVista === 'lago' ? null : 'lago')}
          style={{
            padding:'5px 11px', borderRadius:100, fontSize:11.5, fontWeight:600,
            background: filtroVista === 'lago' ? 'var(--lago)' : 'var(--bg-elev)',
            color: filtroVista === 'lago' ? 'white' : 'var(--ink-soft)',
            border: '1px solid ' + (filtroVista === 'lago' ? 'var(--lago)' : 'var(--line)'),
            cursor:'pointer', display:'inline-flex', alignItems:'center', gap:4
          }}>
          <Icon name="wave" size={12}/> Vista para o lago
        </button>

        <div style={{width:1, height:24, background:'var(--line)', margin:'0 4px'}}/>

        {/* Preço */}
        <label style={{display:'inline-flex', alignItems:'center', gap:8, fontSize:11.5, color:'var(--ink-soft)'}}>
          R$/m² até <span className="mono" style={{color:'var(--green-deep)', fontWeight:600, minWidth:32}}>{precoMax}</span>
          <input type="range" min={300} max={700} step={20} value={precoMax}
            onChange={e=>setPrecoMax(+e.target.value)} style={{width: 120, accentColor:'var(--green)'}}/>
        </label>
        <label style={{display:'inline-flex', alignItems:'center', gap:8, fontSize:11.5, color:'var(--ink-soft)'}}>
          Área mín. <span className="mono" style={{color:'var(--green-deep)', fontWeight:600, minWidth:40}}>{areaMin}m²</span>
          <input type="range" min={0} max={1300} step={50} value={areaMin}
            onChange={e=>setAreaMin(+e.target.value)} style={{width: 120, accentColor:'var(--green)'}}/>
        </label>

        <div style={{flex:1}}/>
        <div style={{fontSize:12, color:'var(--ink-soft)'}}>
          <span className="mono" style={{fontWeight:700, color:'var(--green-deep)', fontSize:14}}>{filtered.length}</span> lotes
        </div>
      </div>

      {variation === 'A' ? (
        <div style={{display:'grid', gridTemplateColumns:'minmax(0,2.2fr) minmax(0,1fr)', gap:24}}>
          {/* Map */}
          <div style={{
            background:'var(--bg-card)', borderRadius:18, padding:8,
            border:'1px solid var(--line-soft)', position:'relative', overflow:'hidden'
          }}>
            <MapaLoteamento
              estilo={estilo}
              filtroStatus={filtroStatus}
              filtroVista={filtroVista}
              hover={hover}
              onHover={setHover}
              onSelect={onSelect}
            />
            {/* Style switcher (visual variant) */}
            <div style={{position:'absolute', top:18, left:18, display:'flex', gap:4,
              background:'rgba(243, 237, 224, 0.9)', padding:4, borderRadius:100,
              border:'1px solid var(--line)', backdropFilter:'blur(6px)'}}>
              {[['tecnico','Técnico'],['esquematico','Esquemático'],['isometrico','Isométrico']].map(([k, lbl])=> (
                <button key={k} onClick={()=>setEstilo(k)} style={{
                  padding:'5px 12px', borderRadius:100, fontSize:11, fontWeight:600,
                  background: estilo===k ? 'var(--green)' : 'transparent',
                  color: estilo===k ? 'var(--bg-card)' : 'var(--ink-soft)',
                  cursor:'pointer'
                }}>{lbl}</button>
              ))}
            </div>
            {/* Legend */}
            <div style={{position:'absolute', bottom:18, left:18,
              background:'rgba(251, 246, 236, 0.95)', padding:'10px 14px', borderRadius:10,
              border:'1px solid var(--line)', backdropFilter:'blur(6px)',
              display:'flex', gap:14, fontSize:11, fontWeight:600
            }}>
              {[
                ['disponivel', 'Disponível', '#FBF6EC', '#2D4F3C'],
                ['reservado', 'Reservado', '#F5DCC6', '#A8632F'],
                ['negociacao', 'Negociação', '#D7E5EC', '#3B6B7E'],
                ['vendido', 'Vendido', '#DDE3DD', '#6E7B72'],
              ].map(([k, lbl, bg, bd]) => (
                <div key={k} style={{display:'inline-flex', alignItems:'center', gap:5, color:'var(--ink)'}}>
                  <span style={{width:14, height:10, background:bg, border: '1px solid '+bd, borderRadius:2}}/>
                  {lbl}
                </div>
              ))}
            </div>
            {/* Hover tooltip */}
            {hover && (
              <div style={{
                position:'absolute', top:18, right:18, background:'var(--bg-card)',
                padding:'12px 16px', borderRadius:10, boxShadow:'var(--shadow-2)',
                border:'1px solid var(--line)', minWidth: 180,
                pointerEvents:'none'
              }}>
                <div className="eyebrow" style={{marginBottom:4}}>Lote {hover} · Quadra {window.BL.LOTE_BY_NUM[hover]?.quadra}</div>
                <div className="display" style={{fontSize:20, color:'var(--green-deep)', fontWeight:500}}>{fmtBRL(window.BL.LOTE_BY_NUM[hover]?.valorTotal || 0)}</div>
                <div style={{fontSize:11, color:'var(--ink-soft)', marginTop:4}}>
                  {window.BL.LOTE_BY_NUM[hover]?.area.toFixed(0)} m² · {window.BL.LOTE_BY_NUM[hover]?.frente.toFixed(1)}m frente
                </div>
              </div>
            )}
          </div>

          {/* Lista lateral */}
          <div style={{maxHeight: 720, overflowY:'auto', display:'flex', flexDirection:'column', gap:10}}>
            {filtered.slice(0, 30).map(l => (
              <button key={l.numero} onClick={()=>onSelect(l.numero)}
                onMouseEnter={()=>setHover(l.numero)} onMouseLeave={()=>setHover(null)}
                style={{
                  textAlign:'left', background:'var(--bg-card)', border:'1px solid var(--line-soft)',
                  borderRadius:12, padding:'14px 16px', cursor:'pointer',
                  display:'flex', gap:14, alignItems:'center',
                  transition:'all .15s'
                }}
                onMouseOver={e=>{e.currentTarget.style.borderColor='var(--green)'; e.currentTarget.style.transform='translateX(-2px)';}}
                onMouseOut={e=>{e.currentTarget.style.borderColor='var(--line-soft)'; e.currentTarget.style.transform='none';}}
              >
                <div style={{
                  width:46, height:46, borderRadius:10,
                  background: l.vistaLago ? 'var(--lago-soft)' : 'var(--green-soft)',
                  color: l.vistaLago ? 'var(--lago-deep)' : 'var(--green-deep)',
                  display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0,
                  fontFamily:'var(--display)', fontSize:20, fontWeight:600
                }}>{l.numero}</div>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:3, whiteSpace:'nowrap'}}>
                    <span style={{fontWeight:700, fontSize:13}}>Lote {l.numero}</span>
                    <span style={{fontSize:11, color:'var(--ink-soft)'}}>· Q.{l.quadra}</span>
                    {l.vistaLago && <Icon name="wave" size={11}/>}
                  </div>
                  <div style={{fontSize:11.5, color:'var(--ink-soft)'}}>
                    {l.area.toFixed(0)} m² · {l.frente.toFixed(1)}m frente
                  </div>
                </div>
                <div style={{textAlign:'right'}}>
                  <div className="display" style={{fontSize:17, color:'var(--green-deep)', fontWeight:600}}>
                    {fmtBRL(l.valorTotal)}
                  </div>
                  <div style={{fontSize:10.5, color:'var(--ink-soft)'}}>R$ {l.precoM2}/m²</div>
                </div>
              </button>
            ))}
            {filtered.length > 30 && (
              <div style={{textAlign:'center', padding:14, fontSize:12, color:'var(--ink-soft)'}}>
                + {filtered.length - 30} lotes
              </div>
            )}
          </div>
        </div>
      ) : (
        <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(260px, 1fr))', gap:18}}>
          {filtered.map(l => (
            <button key={l.numero} onClick={()=>onSelect(l.numero)}
              style={{
                textAlign:'left', background:'var(--bg-card)', border:'1px solid var(--line-soft)',
                borderRadius:14, padding:0, cursor:'pointer', overflow:'hidden',
                display:'flex', flexDirection:'column'
              }}>
              <PhotoPlaceholder type={l.vistaLago ? 'lago' : 'aerea'} height={140} label={`Lote ${l.numero} · Q.${l.quadra}`}/>
              <div style={{padding:'14px 16px 16px'}}>
                <div style={{display:'flex', justifyContent:'space-between', marginBottom:8}}>
                  <StatusPill status={l.status} size="sm"/>
                  {l.vistaLago && <Icon name="wave" size={14} stroke={1.5}/>}
                </div>
                <div className="display" style={{fontSize:22, fontWeight:500, color:'var(--green-deep)'}}>
                  {fmtBRL(l.valorTotal)}
                </div>
                <div style={{fontSize:12, color:'var(--ink-soft)', marginTop:4}}>
                  {l.area.toFixed(0)} m² · R$ {l.precoM2}/m² · {l.frente.toFixed(1)}m frente
                </div>
              </div>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── Detalhe do lote ────────────────────────────────────────
function BuyerLoteDetail({lote, onBack, onContinue, onSimular}) {
  const [variation, setVariation] = useState('A');
  if (!lote) return null;
  return (
    <div style={{padding:'24px 28px 80px', maxWidth: 1400, margin:'0 auto'}}>
      <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:18}}>
        <button className="btn btn-ghost btn-sm" onClick={onBack}>
          <Icon name="chevL" size={14}/> Voltar ao mapa
        </button>
        <div style={{flex:1}}/>
        <div style={{display:'flex', gap:4, background:'var(--bg-card)', padding:4, borderRadius:100, border:'1px solid var(--line)'}}>
          <button onClick={()=>setVariation('A')} className={"btn btn-sm " + (variation==='A' ? 'btn-primary' : 'btn-ghost')} style={{padding:'5px 14px', fontSize:11}}>Variação 1</button>
          <button onClick={()=>setVariation('B')} className={"btn btn-sm " + (variation==='B' ? 'btn-primary' : 'btn-ghost')} style={{padding:'5px 14px', fontSize:11}}>Variação 2</button>
        </div>
      </div>

      {variation === 'A' ? <LoteDetailA lote={lote} onContinue={onContinue} onSimular={onSimular}/> : <LoteDetailB lote={lote} onContinue={onContinue} onSimular={onSimular}/>}
    </div>
  );
}

function LoteDetailA({lote, onContinue, onSimular}) {
  // Variação 1: hero + side panel (mais editorial)
  return (
    <div style={{display:'grid', gridTemplateColumns: 'minmax(0, 1.4fr) minmax(360px, 0.9fr)', gap:36, alignItems:'flex-start'}}>
      <div>
        <PhotoPlaceholder type={lote.vistaLago ? 'lago' : 'aerea'} height={420}/>
        <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:10, marginTop:10}}>
          <PhotoPlaceholder type="aerea" height={110}/>
          <PhotoPlaceholder type="pier" height={110}/>
          <PhotoPlaceholder type="portaria" height={110}/>
        </div>

        <div style={{marginTop:40}}>
          <div className="eyebrow" style={{marginBottom:8}}>◇ Dimensões do lote</div>
          <div style={{display:'grid', gridTemplateColumns:'repeat(2,1fr)', gap:20}}>
            <LotePolygon lote={lote}/>
            <div style={{display:'flex', flexDirection:'column', gap:10}}>
              <DimRow label="Área total" value={`${lote.area.toFixed(2)} m²`} highlight/>
              <DimRow label="Frente" value={`${lote.frente.toFixed(2)} m`}/>
              <DimRow label="Lateral esquerda" value={`${lote.esq.toFixed(2)} m`}/>
              <DimRow label="Fundo" value={`${lote.fundo.toFixed(2)} m`}/>
              <DimRow label="Lateral direita" value={`${lote.dir.toFixed(2)} m`}/>
              <DimRow label="Vista" value={lote.vistaLago ? 'Frente para a Lagoa do Cassó' : 'Interior do empreendimento'}/>
            </div>
          </div>
        </div>

        <div style={{marginTop:36}}>
          <div className="eyebrow" style={{marginBottom:12}}>◇ O que está incluso</div>
          <div style={{display:'grid', gridTemplateColumns:'repeat(2,1fr)', gap:8}}>
            {window.BL.EMPREENDIMENTO.amenidades.map((a,i) => (
              <div key={i} style={{
                display:'flex', alignItems:'center', gap:10, padding:'10px 14px',
                background:'var(--bg-card)', border:'1px solid var(--line-soft)', borderRadius:10
              }}>
                <span style={{color:'var(--green)'}}><Icon name="check" size={14}/></span>
                <span style={{fontSize:13}}>{a.nome}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div style={{position:'sticky', top:96}}>
        <div className="card" style={{padding:28}}>
          <div className="eyebrow" style={{color:'var(--terra-deep)', marginBottom:6}}>◐ Quadra {lote.quadra}</div>
          <h1 className="display" style={{fontSize:46, lineHeight:1, color:'var(--green-deep)', fontWeight:500, marginBottom:8}}>
            Lote {lote.numero}
          </h1>
          <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:24}}>
            <StatusPill status={lote.status}/>
            {lote.vistaLago && <span style={{fontSize:12, color:'var(--lago-deep)', display:'inline-flex', gap:4, alignItems:'center'}}><Icon name="wave" size={13}/> Vista para o lago</span>}
          </div>

          <div style={{
            padding:'18px 0', borderTop:'1px solid var(--line)', borderBottom:'1px solid var(--line)',
            display:'flex', alignItems:'baseline', gap:8, marginBottom:20
          }}>
            <div style={{flex:1}}>
              <div className="eyebrow" style={{fontSize:10}}>Valor à vista</div>
              <div className="display" style={{fontSize:38, color:'var(--green-deep)', fontWeight:600, lineHeight:1, marginTop:4}}>
                {fmtBRL(lote.valorTotal)}
              </div>
              <div style={{fontSize:11.5, color:'var(--ink-soft)', marginTop:6}}>
                ou 48× <span className="mono" style={{color:'var(--green-deep)', fontWeight:700}}>{fmtBRL(lote.valorTotal * 0.8 / 48)}</span>
              </div>
            </div>
          </div>

          {lote.status === 'disponivel' ? (
            <>
              <button onClick={onContinue} className="btn btn-primary btn-lg" style={{width:'100%', marginBottom:10}}>
                Reservar este lote <Icon name="arrowR" size={14}/>
              </button>
              <button onClick={onSimular} className="btn btn-secondary btn-lg" style={{width:'100%'}}>
                Simular parcelamento
              </button>
            </>
          ) : (
            <div style={{padding:'14px 16px', background:'var(--terra-soft)', borderRadius:10, fontSize:12.5, color:'var(--terra-deep)', display:'flex', gap:10, alignItems:'flex-start'}}>
              <Icon name="info" size={16}/>
              <span>Este lote está {window.STATUS_LABELS[lote.status].toLowerCase()}. Deixe seu interesse e avisaremos se voltar a ficar disponível.</span>
            </div>
          )}

          <div style={{marginTop:20, padding:'16px 0 0', borderTop:'1px solid var(--line)', fontSize:12, color:'var(--ink-soft)'}}>
            <div style={{display:'flex', justifyContent:'space-between', padding:'4px 0'}}>
              <span>Reserva online (24h)</span>
              <span style={{fontWeight:600, color:'var(--ink)'}}>Sem custo</span>
            </div>
            <div style={{display:'flex', justifyContent:'space-between', padding:'4px 0'}}>
              <span>Assinatura digital</span>
              <span style={{fontWeight:600, color:'var(--ink)'}}>D4Sign</span>
            </div>
            <div style={{display:'flex', justifyContent:'space-between', padding:'4px 0'}}>
              <span>Pagamento entrada</span>
              <span style={{fontWeight:600, color:'var(--ink)'}}>PIX ou cartão</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function LoteDetailB({lote, onContinue, onSimular}) {
  // Variação 2: layout horizontal, mais "ficha técnica" minimalista
  return (
    <div>
      <div style={{
        background:'var(--green-deep)', color:'var(--bg-card)', borderRadius:24,
        padding:'48px 56px', position:'relative', overflow:'hidden',
        backgroundImage:'radial-gradient(at 90% 10%, rgba(201, 123, 74, 0.25), transparent 50%)'
      }}>
        <div className="eyebrow" style={{color:'#D9C7A8', marginBottom:14}}>
          ◇ Brisas do Lago / Quadra {lote.quadra}
        </div>
        <div style={{display:'flex', alignItems:'flex-end', justifyContent:'space-between', flexWrap:'wrap', gap:32}}>
          <h1 className="display" style={{fontSize:'clamp(56px, 8vw, 110px)', lineHeight:0.9, color:'var(--bg-card)', fontWeight:500, letterSpacing:'-0.03em'}}>
            Lote{' '}
            <span style={{fontStyle:'italic', color:'var(--terra)'}}>{String(lote.numero).padStart(2,'0')}</span>
          </h1>
          <div style={{textAlign:'right'}}>
            <div style={{fontSize:11, color:'#D9C7A8', letterSpacing:1.5, textTransform:'uppercase', marginBottom:8}}>À vista</div>
            <div className="display" style={{fontSize:42, color:'var(--bg-card)', fontWeight:500, lineHeight:1}}>
              {fmtBRL(lote.valorTotal)}
            </div>
            <div style={{fontSize:13, color:'#D9C7A8', marginTop:6}}>
              ou 48× {fmtBRL(lote.valorTotal * 0.8 / 48)}
            </div>
          </div>
        </div>
        <div style={{display:'flex', gap:14, marginTop:32}}>
          <button onClick={onContinue} className="btn btn-terra btn-lg">
            Reservar agora <Icon name="arrowR" size={14}/>
          </button>
          <button onClick={onSimular} className="btn btn-lg" style={{background:'rgba(243, 237, 224, 0.1)', color:'var(--bg-card)', border:'1px solid rgba(243, 237, 224, 0.3)'}}>
            Simular parcelamento
          </button>
        </div>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:1, marginTop:30, background:'var(--line)', border:'1px solid var(--line)', borderRadius:14, overflow:'hidden'}}>
        {[
          ['Área', `${lote.area.toFixed(0)} m²`],
          ['Frente', `${lote.frente.toFixed(1)} m`],
          ['Fundo', `${lote.fundo.toFixed(1)} m`],
          ['R$/m²', `R$ ${lote.precoM2}`],
        ].map(([k, v]) => (
          <div key={k} style={{background:'var(--bg-card)', padding:'24px 22px'}}>
            <div className="eyebrow" style={{fontSize:10, marginBottom:8}}>{k}</div>
            <div className="display" style={{fontSize:32, color:'var(--green-deep)', fontWeight:500, lineHeight:1}}>{v}</div>
          </div>
        ))}
      </div>

      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:30, marginTop:30}}>
        <div>
          <div className="eyebrow" style={{marginBottom:14}}>◇ Polígono do lote</div>
          <LotePolygon lote={lote}/>
        </div>
        <div>
          <div className="eyebrow" style={{marginBottom:14}}>◇ Inclusões</div>
          <div style={{display:'flex', flexDirection:'column', gap:8}}>
            {window.BL.EMPREENDIMENTO.amenidades.map((a,i) => (
              <div key={i} style={{
                display:'flex', alignItems:'center', gap:12, padding:'10px 0',
                borderBottom:'1px solid var(--line-soft)'
              }}>
                <span style={{color:'var(--terra)'}}><Icon name="check" size={14}/></span>
                <span style={{fontSize:13.5}}>{a.nome}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function DimRow({label, value, highlight}) {
  return (
    <div style={{
      display:'flex', justifyContent:'space-between', alignItems:'center', gap:12,
      padding:'10px 0', borderBottom:'1px solid var(--line-soft)',
      ...(highlight ? {background:'var(--green-soft)', padding:'14px 16px', borderRadius:10, border:'none'} : {})
    }}>
      <span style={{fontSize:12.5, color:'var(--ink-soft)', flexShrink:0}}>{label}</span>
      <span className={highlight ? 'display' : ''} style={{
        fontWeight: highlight ? 500 : 600,
        fontSize: highlight ? 22 : 13.5,
        color: highlight ? 'var(--green-deep)' : 'var(--ink)',
        fontFamily: highlight ? 'var(--display)' : 'var(--mono)',
        whiteSpace:'nowrap', textAlign:'right'
      }}>{value}</span>
    </div>
  );
}

function LotePolygon({lote}) {
  // Desenha um polígono representando o lote com cotas
  // Aproxima como trapézio: frente em baixo, fundo em cima, com laterais esq/dir
  const f = lote.frente, fu = lote.fundo, e = lote.esq, d = lote.dir;
  const maxDim = Math.max(f, fu, e, d);
  const scale = 180 / maxDim;
  const W = 260, H = 260, cx = W/2, cy = H/2;
  const fW = f * scale, fuW = fu * scale, eH = (e + d) / 2 * scale;
  // Vértices: tl, tr, br, bl
  const tl = [cx - fuW/2, cy - eH/2];
  const tr = [cx + fuW/2, cy - eH/2];
  const br = [cx + fW/2, cy + eH/2];
  const bl = [cx - fW/2, cy + eH/2];
  return (
    <svg viewBox="0 0 260 260" style={{width:'100%', height:'auto', background:'var(--bg-card)', borderRadius:12, border:'1px solid var(--line-soft)'}}>
      <polygon points={[tl, tr, br, bl].map(p=>p.join(',')).join(' ')}
        fill="rgba(45, 79, 60, 0.08)" stroke="var(--green)" strokeWidth="2"/>
      <text x={cx} y={cy + 4} textAnchor="middle" fontFamily="var(--display)" fontSize="22" fill="var(--green-deep)" fontWeight="600">
        {lote.area.toFixed(0)}m²
      </text>
      {/* labels */}
      <text x={cx} y={tl[1] - 6} textAnchor="middle" fontSize="10" fill="var(--ink-soft)">{fu.toFixed(1)}m (fundo)</text>
      <text x={cx} y={br[1] + 14} textAnchor="middle" fontSize="10" fill="var(--ink-soft)">{f.toFixed(1)}m (frente)</text>
      <text x={tl[0] - 6} y={cy} textAnchor="end" fontSize="10" fill="var(--ink-soft)">{e.toFixed(1)}m</text>
      <text x={tr[0] + 6} y={cy} textAnchor="start" fontSize="10" fill="var(--ink-soft)">{d.toFixed(1)}m</text>
    </svg>
  );
}

// ─── Simulador ──────────────────────────────────────────────
function BuyerSimulador({lote, onBack, onContinue}) {
  const [entradaPct, setEntradaPct] = useState(10);
  const [parcelas, setParcelas] = useState(48);

  const entrada = lote.valorTotal * entradaPct / 100;
  const saldoRestante = lote.valorTotal - entrada;
  const parcela = saldoRestante / parcelas;

  return (
    <div style={{padding:'24px 28px 80px', maxWidth: 1200, margin:'0 auto'}}>
      <button className="btn btn-ghost btn-sm" onClick={onBack} style={{marginBottom:14}}>
        <Icon name="chevL" size={14}/> Voltar
      </button>
      <SectionHeader eyebrow={`Lote ${lote.numero} · Quadra ${lote.quadra}`} title="Simulador de parcelamento" sub="Ajuste entrada e número de parcelas. Sem juros até 48 vezes."/>

      <div style={{display:'grid', gridTemplateColumns:'minmax(0, 1.4fr) minmax(0, 1fr)', gap:36}}>
        <div className="card" style={{padding:32}}>
          <div className="eyebrow" style={{marginBottom:18}}>◇ Configurar entrada</div>
          <label style={{display:'block', marginBottom:8, fontSize:13, fontWeight:600}}>Entrada</label>
          <div style={{display:'flex', alignItems:'center', gap:18, marginBottom:8}}>
            <input type="range" min={5} max={50} step={5} value={entradaPct}
              onChange={e=>setEntradaPct(+e.target.value)}
              style={{flex:1, accentColor:'var(--green)'}}/>
            <div style={{minWidth:90, textAlign:'right'}}>
              <div className="mono" style={{fontSize:18, fontWeight:700, color:'var(--green-deep)'}}>{entradaPct}%</div>
              <div style={{fontSize:11, color:'var(--ink-soft)'}}>{fmtBRL(entrada)}</div>
            </div>
          </div>

          <div className="eyebrow" style={{marginTop:32, marginBottom:14}}>◇ Número de parcelas</div>
          <div style={{display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:8}}>
            {[12, 24, 36, 48].map(n => (
              <button key={n} onClick={()=>setParcelas(n)}
                style={{
                  padding:'14px 8px', borderRadius:10,
                  background: parcelas===n ? 'var(--green)' : 'var(--bg-elev)',
                  color: parcelas===n ? 'var(--bg-card)' : 'var(--ink)',
                  border:'1px solid ' + (parcelas===n ? 'var(--green)' : 'var(--line)'),
                  cursor:'pointer'
                }}>
                <div className="display" style={{fontSize:24, fontWeight:500}}>{n}×</div>
                <div style={{fontSize:10.5, opacity:0.7, marginTop:2}}>{n === 48 ? '4 anos' : n === 36 ? '3 anos' : n === 24 ? '2 anos' : '1 ano'}</div>
              </button>
            ))}
          </div>

          <div style={{marginTop:32, padding:'22px 24px', background:'var(--green-soft)', borderRadius:14}}>
            <div className="eyebrow" style={{marginBottom:8, color:'var(--green-deep)'}}>◇ Você pagará</div>
            <div style={{display:'flex', alignItems:'baseline', gap:8}}>
              <span className="display" style={{fontSize:38, fontWeight:500, color:'var(--green-deep)'}}>
                {fmtBRL(parcela)}
              </span>
              <span style={{fontSize:14, color:'var(--ink-soft)'}}>× {parcelas} meses</span>
            </div>
            <div style={{fontSize:12.5, color:'var(--ink-soft)', marginTop:6}}>
              após entrada de {fmtBRL(entrada)} · sem juros · IGPM anual
            </div>
          </div>
        </div>

        <div style={{display:'flex', flexDirection:'column', gap:16}}>
          <div className="card" style={{padding:24}}>
            <div className="eyebrow" style={{marginBottom:14}}>◇ Resumo</div>
            <div style={{display:'flex', flexDirection:'column', gap:10, fontSize:13.5}}>
              <div style={{display:'flex', justifyContent:'space-between'}}>
                <span style={{color:'var(--ink-soft)'}}>Valor do lote</span>
                <span style={{fontWeight:600}}>{fmtBRL(lote.valorTotal)}</span>
              </div>
              <div style={{display:'flex', justifyContent:'space-between'}}>
                <span style={{color:'var(--ink-soft)'}}>Entrada ({entradaPct}%)</span>
                <span style={{fontWeight:600}}>{fmtBRL(entrada)}</span>
              </div>
              <div style={{display:'flex', justifyContent:'space-between'}}>
                <span style={{color:'var(--ink-soft)'}}>Saldo financiado</span>
                <span style={{fontWeight:600}}>{fmtBRL(saldoRestante)}</span>
              </div>
              <div style={{display:'flex', justifyContent:'space-between'}}>
                <span style={{color:'var(--ink-soft)'}}>{parcelas} parcelas de</span>
                <span style={{fontWeight:600, color:'var(--green-deep)'}}>{fmtBRL(parcela)}</span>
              </div>
              <div style={{height:1, background:'var(--line)', margin:'6px 0'}}/>
              <div style={{display:'flex', justifyContent:'space-between', fontSize:15}}>
                <span style={{fontWeight:700}}>Total</span>
                <span className="display" style={{fontSize:22, fontWeight:600, color:'var(--green-deep)'}}>{fmtBRL(lote.valorTotal)}</span>
              </div>
            </div>
          </div>
          <button onClick={onContinue} className="btn btn-primary btn-lg" style={{width:'100%'}}>
            Reservar com estas condições <Icon name="arrowR" size={14}/>
          </button>
          <button className="btn btn-secondary btn-sm" style={{width:'100%'}}>
            <Icon name="download" size={13}/> Baixar simulação em PDF
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  BuyerHero, BuyerMap, BuyerLoteDetail, BuyerSimulador,
});
