/* ============================================================
   Empreendimentos — RegiaoView & ImovelView (SPA inline)
   ============================================================ */

const EIC = {
  pin:  (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12 21s7-5.5 7-11a7 7 0 10-14 0c0 5.5 7 11 7 11z"/><circle cx="12" cy="10" r="2.5"/></svg>),
  bed:  (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 18v-6a2 2 0 012-2h14a2 2 0 012 2v6M3 14h18M6 10V7a1 1 0 011-1h10a1 1 0 011 1v3"/></svg>),
  area: (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M4 4h16v16H4zM4 9h5M4 15h5M15 4v5M15 15v5"/></svg>),
  car:  (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 16v2M19 16v2M4 12l1.5-4.5A2 2 0 017.4 6h9.2a2 2 0 011.9 1.5L20 12M3 12h18v4H3zM6.5 14h.01M17.5 14h.01"/></svg>),
  arrow:(<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>),
  check:(<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12.5l4.5 4.5L19 6.5"/></svg>),
  back: (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{transform:'rotate(180deg)'}}><path d="M5 12h14M13 6l6 6-6 6"/></svg>),
  sim:  (<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M9 7h6M9 11h6M9 15h4M7 3h10a1 1 0 011 1v16l-3-2-3 2-3-2-3 2V4a1 1 0 011-1z"/></svg>),
};

/* ---- Mapa interativo com marcadores do Órulo ---- */
function MapaZona({ list, zone }) {
  const containerRef = useRef(null);
  const mapRef       = useRef(null);

  // Chave baseada nos dados reais para detectar quando o Orulo carregou
  const dataKey = zone + '|' + list.filter(e => e.lat).length;

  useEffect(() => {
    let tid = null;

    function initMap() {
      const L = window.L;
      if (!L || !containerRef.current) return;

      // Destrói instância anterior
      if (mapRef.current) { mapRef.current.remove(); mapRef.current = null; }

      const comCoord = list.map((e, i) => ({ ...e, _idx: i })).filter(e => e.lat && e.lng);
      if (!comCoord.length) return;

      const avgLat = comCoord.reduce((s, e) => s + e.lat, 0) / comCoord.length;
      const avgLng = comCoord.reduce((s, e) => s + e.lng, 0) / comCoord.length;

      const map = L.map(containerRef.current, {
        center: [avgLat, avgLng],
        zoom: 13,
        zoomControl: true,
        preferCanvas: true,
      });
      mapRef.current = map;

      L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
        attribution: '©<a href="https://www.openstreetmap.org/copyright">OSM</a> ©<a href="https://carto.com/">CARTO</a>',
        maxZoom: 19,
      }).addTo(map);

      comCoord.forEach(e => {
        const marker = L.circleMarker([e.lat, e.lng], {
          radius: 9, fillColor: '#c9a84c', color: '#fff',
          weight: 2, opacity: 1, fillOpacity: 0.92,
        }).addTo(map);

        marker.bindTooltip(e.nome, { permanent: false, direction: 'top', offset: [0, -10] });
        marker.bindPopup(`
          <div style="font:600 13px/1.4 sans-serif;min-width:170px;color:#1a1a2e">
            <div style="font-size:14px;margin-bottom:4px">${e.nome}</div>
            <div style="font-weight:400;color:#555;font-size:12px">${e.bairro}</div>
            <div style="margin:6px 0;color:#b8862c;font-weight:700">${e.preco}</div>
            <div style="font-size:11px;color:#666">${e.dorms} · ${e.area}</div>
            <a href="#imovel?z=${zone}&e=${e._idx}"
               style="display:inline-block;margin-top:8px;padding:5px 12px;background:#c9a84c;color:#fff;border-radius:6px;text-decoration:none;font-size:12px;font-weight:700">
              Ver detalhes →
            </a>
          </div>
        `, { maxWidth: 240 });
      });

      // Recalcula tamanho após o container ter dimensões reais
      setTimeout(() => { if (mapRef.current) mapRef.current.invalidateSize(); }, 200);
    }

    // Aguarda 1 frame para o container ser pintado com altura real
    tid = setTimeout(initMap, 50);

    return () => {
      clearTimeout(tid);
      if (mapRef.current) { mapRef.current.remove(); mapRef.current = null; }
    };
  }, [dataKey]);

  return <div ref={containerRef} style={{ width: '100%', height: '100%' }} />;
}

/* ---- Hook: sincroniza com window.CRUZ_EMP ao carregar do Órulo ---- */
function useCruzEmp() {
  const [emp, setEmp] = useState(window.CRUZ_EMP);
  useEffect(() => {
    const onReady = () => setEmp({ ...window.CRUZ_EMP });
    window.addEventListener('cruzemp:ready', onReady);
    return () => window.removeEventListener('cruzemp:ready', onReady);
  }, []);
  return emp;
}

/* ---- Lista de empreendimentos por zona ---- */
function RegiaoView({ zone }) {
  const ZONES = window.CRUZ_ZONES;
  const EMP   = useCruzEmp();
  const z     = (ZONES[zone]) ? zone : 'zona-sul';
  const info  = ZONES[z];
  const list  = EMP[z] || [];
  const listRef = useRef(null);

  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'instant' });
  }, [z]);

  useEffect(() => {
    const box = listRef.current;
    if (!box) return;
    const cards = box.querySelectorAll('.emp');
    if (!cards.length) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(en => { if (en.isIntersecting) { en.target.classList.add('in'); io.unobserve(en.target); } });
    }, { threshold: 0.08 });
    cards.forEach((el, i) => {
      el.style.transitionDelay = (i % 3) * 0.07 + 's';
      io.observe(el);
    });
    return () => io.disconnect();
  }, [z, list.length]);

  return (
    <React.Fragment>
      <Header />
      <div style={{ paddingTop: 80, background: 'var(--navy-950)', minHeight: '100vh' }}>
        <div className="rg-head">
          <a className="rg-back" href="#">
            <span style={{ width: 16, height: 16, display: 'inline-flex' }}>{EIC.back}</span>
            Todas as regiões
          </a>
          <h1>Empreendimentos na <span className="gold-ital">{info.label}</span></h1>
          <p>{info.desc}</p>
          <div className="rg-zonas">
            {Object.entries(ZONES).map(([k, v]) => (
              <a key={k} className={`rg-zona${k === z ? ' active' : ''}`} href={`#regiao?z=${k}`}>{v.label}</a>
            ))}
          </div>
        </div>

        <div className="rg-split">
          <div className="rg-map">
            <MapaZona list={list} zone={z} />
          </div>
          <div>
            <div className="rg-count">{list.length} empreendimentos disponíveis</div>
            <div className="rg-list" ref={listRef} style={{ marginTop: 16 }}>
              {list.map((e, i) => {
                const detail = `#imovel?z=${z}&e=${i}`;
                return (
                  <div key={i} className="emp">
                    <a className="emp-cardlink" href={detail} aria-label={`Ver detalhes de ${e.nome}`}></a>
                    <div className="emp-photo">
                      <span className="emp-status">{e.status}</span>
                      {e.mcmv && <span className="emp-mcmv">MCMV</span>}
                      <image-slot id={`emp-${z}-${i}`} fit="cover" radius="0" placeholder={`Foto · ${e.nome}`} src={(e.imagens && e.imagens[0]) || ''}></image-slot>
                    </div>
                    <div className="emp-body">
                      <h3>{e.nome}</h3>
                      <span className="emp-loc">
                        <span style={{ width: 15, height: 15, display: 'inline-flex', color: 'var(--gold-600)' }}>{EIC.pin}</span>
                        {e.bairro} · {info.label}
                      </span>
                      <p className="emp-desc">{e.desc}</p>
                      <div className="emp-specs">
                        <span className="emp-spec"><span style={{ width: 15, height: 15, display: 'inline-flex', color: 'var(--gold-600)' }}>{EIC.bed}</span>{e.dorms}</span>
                        <span className="emp-spec"><span style={{ width: 15, height: 15, display: 'inline-flex', color: 'var(--gold-600)' }}>{EIC.area}</span>{e.area}</span>
                        <span className="emp-spec"><span style={{ width: 15, height: 15, display: 'inline-flex', color: 'var(--gold-600)' }}>{EIC.car}</span>{e.vagas}</span>
                      </div>
                      <div className="emp-foot">
                        <span className="emp-price"><em>A partir de</em><strong>{e.preco}</strong></span>
                        <a className="emp-btn" href={detail}>
                          Ver detalhes
                          <span style={{ width: 16, height: 16, display: 'inline-flex' }}>{EIC.arrow}</span>
                        </a>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
      <Footer />
      <WhatsFloat />
    </React.Fragment>
  );
}

/* ---- Lightbox de fotos ---- */
function Lightbox({ fotos, descricoes, inicio, onClose }) {
  const [idx, setIdx] = useState(inicio || 0);

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'ArrowRight') setIdx(i => (i + 1) % fotos.length);
      if (e.key === 'ArrowLeft')  setIdx(i => (i - 1 + fotos.length) % fotos.length);
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [fotos.length]);

  const prev = () => setIdx(i => (i - 1 + fotos.length) % fotos.length);
  const next = () => setIdx(i => (i + 1) % fotos.length);

  return (
    <div className="lb-overlay" onClick={onClose}>
      <div className="lb-box" onClick={e => e.stopPropagation()}>
        <button className="lb-close" onClick={onClose}>✕</button>
        <button className="lb-nav lb-prev" onClick={prev}>‹</button>
        <div className="lb-img-wrap">
          <img key={idx} src={fotos[idx]} alt={descricoes[idx] || ''} className="lb-img" />
          {descricoes[idx] && <div className="lb-caption">{descricoes[idx]}</div>}
        </div>
        <button className="lb-nav lb-next" onClick={next}>›</button>
        <div className="lb-counter">{idx + 1} / {fotos.length}</div>
        <div className="lb-thumbs">
          {fotos.map((f, i) => (
            <img key={i} src={f} alt="" className={`lb-thumb${i === idx ? ' active' : ''}`} onClick={() => setIdx(i)} />
          ))}
        </div>
      </div>
    </div>
  );
}

/* ---- Detalhe do empreendimento ---- */
function ImovelView({ zone, empIdx }) {
  const ZONES = window.CRUZ_ZONES;
  const EMP   = useCruzEmp();
  const z     = (ZONES[zone]) ? zone : 'zona-sul';
  const list  = EMP[z] || [];
  const ei    = (isNaN(empIdx) || empIdx < 0 || empIdx >= list.length) ? 0 : empIdx;
  const info  = ZONES[z];
  const e     = list[ei];

  const [detalhe, setDetalhe]       = useState(null);
  const [lbInicio, setLbInicio]     = useState(null);
  const [lbPlanta, setLbPlanta]     = useState(null);

  useEffect(() => {
    if (!e) return;
    window.scrollTo({ top: 0, behavior: 'instant' });
    setLbInicio(null);
    setLbPlanta(null);
    const prev = document.title;
    document.title = `${e.nome} · ${info.label} · Wanderson Cruz`;
    return () => { document.title = prev; };
  }, [z, ei, !!e]);

  useEffect(() => {
    if (!e || !e.oruloId) return;
    setDetalhe(null);
    fetch(`/api/orulo-building?id=${e.oruloId}`, { signal: AbortSignal.timeout(10000) })
      .then(r => r.ok ? r.json() : null)
      .then(d => { if (d && d.ok) setDetalhe(d); })
      .catch(() => {});
  }, [e && e.oruloId]);

  if (!e) return (
    <React.Fragment>
      <Header />
      <div style={{ paddingTop: 120, minHeight: '60vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 16, background: 'var(--navy-950)', textAlign: 'center', padding: '120px 24px 80px' }}>
        <h2 style={{ fontSize: 'clamp(22px,3vw,34px)', fontWeight: 700 }}>Empreendimento não encontrado</h2>
        <p style={{ color: 'var(--text-on-dark-dim)' }}>Os dados ainda estão carregando ou este imóvel não está disponível.</p>
        <a href={`#regiao?z=${z}`} className="btn btn-gold" style={{ marginTop: 8 }}>Ver empreendimentos da {info.label}</a>
      </div>
      <Footer />
    </React.Fragment>
  );

  const fotosObj = (detalhe && detalhe.imagens) ? detalhe.imagens : (e.imagens || []).map(url => ({ url, descricao: '' }));
  const fotosUrls = fotosObj.map(f => f.url || f);
  const fotosDesc = fotosObj.map(f => f.descricao || '');
  const plantas   = (detalhe && detalhe.plantas && detalhe.plantas.length > 0)
    ? detalhe.plantas : (e.plantas || []);
  const totalFotos = fotosUrls.length;

  const leadMsg = `Olá Wanderson! Tenho interesse no empreendimento ${e.nome} (${e.bairro}, ${info.label}). Pode me passar mais detalhes?`;
  const waHref  = waLink(leadMsg);

  return (
    <React.Fragment>
      <Header />
      {lbInicio !== null && (
        <Lightbox fotos={fotosUrls} descricoes={fotosDesc} inicio={lbInicio} onClose={() => setLbInicio(null)} />
      )}
      {lbPlanta !== null && plantas.length > 0 && (
        <Lightbox
          fotos={plantas.map(p => p.url || p.urlSmall || '')}
          descricoes={plantas.map(p => p.descricao || '')}
          inicio={lbPlanta}
          onClose={() => setLbPlanta(null)}
        />
      )}
      <div style={{ paddingTop: 80, background: 'var(--navy-950)', minHeight: '100vh' }}>
        <div className="im-wrap">
          <a className="im-back" href={`#regiao?z=${z}`}>
            <span style={{ width: 16, height: 16, display: 'inline-flex' }}>{EIC.back}</span>
            Empreendimentos · {info.label}
          </a>

          <div className="im-gallery">
            <div className="im-main" style={{ cursor: fotosUrls.length ? 'zoom-in' : 'default' }} onClick={() => fotosUrls.length && setLbInicio(0)}>
              <span className="im-badge">{e.status}</span>
              <image-slot id={`ig-${z}-${ei}-0`} fit="cover" radius="0" placeholder={`Foto · ${e.nome}`} src={fotosUrls[0] || ''}></image-slot>
              {totalFotos > 3 && (
                <button className="im-more" onClick={ev => { ev.stopPropagation(); setLbInicio(3); }}>
                  +{totalFotos - 3} fotos
                </button>
              )}
            </div>
            <div className="im-side">
              <div className="im-cell" style={{ cursor: fotosUrls[1] ? 'zoom-in' : 'default' }} onClick={() => fotosUrls[1] && setLbInicio(1)}>
                <image-slot id={`ig-${z}-${ei}-1`} fit="cover" radius="0" placeholder="Foto 2" src={fotosUrls[1] || ''}></image-slot>
              </div>
              <div className="im-cell" style={{ cursor: fotosUrls[2] ? 'zoom-in' : 'default' }} onClick={() => fotosUrls[2] && setLbInicio(2)}>
                <image-slot id={`ig-${z}-${ei}-2`} fit="cover" radius="0" placeholder="Foto 3" src={fotosUrls[2] || ''}></image-slot>
              </div>
            </div>
          </div>

          <div className="im-grid">
            <div className="im-content">
              <div className="im-head">
                <h1 style={{ fontSize: 'clamp(28px,4vw,44px)', lineHeight: 1.05, fontWeight: 700, letterSpacing: '-0.025em' }}>{e.nome}</h1>
                <span className="im-loc">
                  <span style={{ width: 16, height: 16, display: 'inline-flex', color: 'var(--gold-400)' }}>{EIC.pin}</span>
                  {e.bairro} · {info.label}
                </span>
              </div>

              {e.mcmv && (
                <div style={{ display:'inline-flex', alignItems:'center', gap:6, background:'var(--gold-600)', color:'var(--navy-950)', borderRadius:6, padding:'4px 10px', fontSize:12, fontWeight:700, marginBottom:12 }}>
                  ✓ Minha Casa Minha Vida
                </div>
              )}

              <div className="im-specs">
                <div className="im-spec"><span>Dormitórios</span><strong><span style={{ width: 18, height: 18, display: 'inline-flex', color: 'var(--gold-400)' }}>{EIC.bed}</span>{e.dorms}{e.suites ? ` · ${e.suites}` : ''}</strong></div>
                <div className="im-spec"><span>Área privativa</span><strong><span style={{ width: 18, height: 18, display: 'inline-flex', color: 'var(--gold-400)' }}>{EIC.area}</span>{e.areaRange || e.area}</strong></div>
                <div className="im-spec"><span>Vagas</span><strong><span style={{ width: 18, height: 18, display: 'inline-flex', color: 'var(--gold-400)' }}>{EIC.car}</span>{e.vagas}</strong></div>
                <div className="im-spec"><span>Status</span><strong>{e.status}</strong></div>
                {e.banhs && <div className="im-spec"><span>Banheiros</span><strong>{e.banhs}</strong></div>}
                {e.andares && <div className="im-spec"><span>Andares</span><strong>{e.andares} andares{e.torres > 1 ? ` · ${e.torres} torres` : ''}</strong></div>}
                {e.unidades > 0 && <div className="im-spec"><span>Unidades disp.</span><strong>{e.unidades}</strong></div>}
                {e.incorporadora && <div className="im-spec"><span>Incorporadora</span><strong>{e.incorporadora}</strong></div>}
              </div>

              {e.endereco && (
                <div style={{ display:'flex', alignItems:'flex-start', gap:6, color:'var(--slate-400)', fontSize:13, marginBottom:8, marginTop:-4 }}>
                  <span style={{ width:14, height:14, display:'inline-flex', color:'var(--gold-500)', flexShrink:0, marginTop:1 }}>{EIC.pin}</span>
                  {e.endereco}
                </div>
              )}

              <div className="im-section">
                <h2>Sobre o empreendimento</h2>
                {(e.sobre || [e.desc]).map((p, i) => <p key={i}>{p}</p>)}
              </div>

              {e.lazer && e.lazer.length > 0 && (
                <div className="im-section">
                  <h2>Lazer e diferenciais</h2>
                  <div className="im-lazer">
                    {e.lazer.map((l, i) => (
                      <span key={i} className="im-lz">
                        <span style={{ width: 16, height: 16, display: 'inline-flex', color: 'var(--gold-400)', flexShrink: 0 }}>{EIC.check}</span>
                        {l}
                      </span>
                    ))}
                  </div>
                </div>
              )}

              {plantas.length > 0 && (
                <div className="im-section">
                  <h2>Plantas</h2>
                  <div className="im-plantas">
                    {plantas.map((pl, pi) => {
                      const titulo   = pl.descricao || pl.t || `Planta ${pi + 1}`;
                      const srcPlant = pl.url || pl.urlSmall || '';
                      return (
                      <div key={pi} className="im-planta im-planta-click" onClick={() => setLbPlanta(pi)} title="Ampliar planta">
                        <div className="im-ph-box">
                          <image-slot id={`pl-${z}-${ei}-${pi}`} fit="contain" radius="0" placeholder={`Planta · ${titulo}`} src={srcPlant}></image-slot>
                        </div>
                        <div className="im-cap">{titulo} <span className="im-cap-zoom">🔍</span></div>
                      </div>
                    )})}
                  </div>
                </div>
              )}
            </div>

            <aside className="im-aside">
              <div className="im-card">
                <div className="price">
                  <em>A partir de</em>
                  <strong>{e.preco}</strong>
                  {e.precoPorM2 && <span style={{ display:'block', fontSize:12, color:'var(--slate-400)', fontWeight:400, marginTop:2 }}>{e.precoPorM2} · {e.areaRange || e.area}</span>}
                </div>
                <p className="note">{e.mcmv ? 'Elegível ao Minha Casa Minha Vida. Fale com o Wanderson e descubra suas condições de aprovação.' : 'Fale com o Wanderson e descubra as melhores condições de financiamento.'}</p>
                <a className="btn btn-wa" href={waHref} target="_blank" rel="noopener" style={{ width: '100%', marginTop: 18 }}>
                  <span style={{ width: 18, height: 18 }}>{Icons.whats}</span>
                  Tenho interesse
                </a>
                <a className="sim" href="#analise">
                  <span style={{ width: 16, height: 16, display: 'inline-flex' }}>{EIC.sim}</span>
                  Simular financiamento
                </a>
                <div className="im-trust">
                  <img src="assets/wanderson-avatar.jpg?v=3" alt="Wanderson Cruz" />
                  <div><strong>Wanderson Cruz</strong><span>Especialista MCMV · CRECI 299734-F</span></div>
                </div>
              </div>
            </aside>
          </div>
        </div>
      </div>
      <Footer />
      <WhatsFloat />
    </React.Fragment>
  );
}

Object.assign(window, { RegiaoView, ImovelView });
