/* Torre Auro — Home (editorial, ecosystem-led, 6 sections) */

/* ─── S1 · HERO ─── */
function S1Hero() {
  const [showVideo, setShowVideo] = useState(false);
  const [videoFailed, setVideoFailed] = useState(false);
  const iframeRef = useRef(null);

  useEffect(() => {
    const start = () => {
      setTimeout(() => setShowVideo(true), 1200);
    };
    if (document.readyState === 'complete') start();
    else window.addEventListener('load', start, { once: true });
    return () => window.removeEventListener('load', start);
  }, []);

  // If the iframe never fires its load event within 8s, treat as failed
  useEffect(() => {
    if (!showVideo || videoFailed) return;
    const t = setTimeout(() => {
      const ifr = iframeRef.current;
      if (!ifr || !ifr.dataset.loaded) setVideoFailed(true);
    }, 8000);
    return () => clearTimeout(t);
  }, [showVideo, videoFailed]);

  function handleVideoLoad(e) {
    e.target.dataset.loaded = '1';
  }
  function handleVideoError() {
    setVideoFailed(true);
  }

  return (
    <section className="hero hero-min">
      <div className="hero-bg" />
      {showVideo && !videoFailed && (
        <div className="hero-video" aria-hidden="true">
          <iframe
            ref={iframeRef}
            src="https://www.youtube-nocookie.com/embed/IAsu9xUkV1E?autoplay=1&mute=1&loop=1&playlist=IAsu9xUkV1E&controls=0&showinfo=0&modestbranding=1&playsinline=1&rel=0&disablekb=1&iv_load_policy=3&vq=hd1080&hd=1"
            title="Torre Auro · Costa de Oro"
            allow="autoplay; encrypted-media; picture-in-picture"
            frameBorder="0"
            allowFullScreen
            onLoad={handleVideoLoad}
            onError={handleVideoError}
          />
        </div>
      )}
      <div className="hero-overlay" />
      <div className="container hero-content">
        <h1>
          <span className="break">El ecosistema</span>
          <span className="break"><em>empresarial.</em></span>
        </h1>
        <button
          className="hero-explore"
          onClick={() => document.getElementById('atmospheric')?.scrollIntoView({ behavior:'smooth' })}
        >
          <span>Explorar</span>
          <span className="ar" aria-hidden="true">↓</span>
        </button>

        <div className="hero-footer-min">
          <div>Costa de Oro · Boca del Río</div>
          <div>Frente al Golfo · zona moderna de Veracruz</div>
          <div>7 niveles · 4 ecosistemas</div>
        </div>
      </div>
    </section>
  );
}

/* ─── S2 · ATMOSPHERIC ─── */
function S2Atmospheric() {
  return (
    <section className="atmospheric" id="atmospheric">
      <div className="atmospheric-day bg-cover bg--fachada-dia" aria-hidden="true" />
      <div className="atmospheric-dusk bg-cover bg--fachada-atardecer" aria-hidden="true" />
      <div className="atmospheric-overlay" />
      <div className="atmos-time-tag">
        <span className="swatch" />
        <span>Día → Atardecer</span>
      </div>
      <div className="container atmospheric-content">
        <div className="kicker light">/ Posicionamiento</div>
        <h2 className="atmospheric-line">
          Un solo edificio,<br/>todo un <em>ecosistema</em>.
        </h2>
        <div className="atmospheric-caption">
          Costa de Oro · al cruce de Ruiz Cortines + Av. Tiburón
        </div>
      </div>
    </section>
  );
}

/* ─── S2.5 · LA UBICACIÓN ─── */
// module-level cache so we don't refetch on re-mount/navigation
let _denueCache = null;

function haversine(aLat, aLng, bLat, bLng) {
  const R = 6371000, toR = Math.PI / 180;
  const dLat = (bLat - aLat) * toR, dLng = (bLng - aLng) * toR;
  const s = Math.sin(dLat/2)**2 + Math.cos(aLat*toR)*Math.cos(bLat*toR)*Math.sin(dLng/2)**2;
  return 2 * R * Math.asin(Math.sqrt(s));
}

function SLocation() {
  const mapRef = useRef(null);
  const clusterRef = useRef(null);
  const placesRef = useRef([]);   // {lat,lng,name,cat,clase,dist,marker}
  const [ring, setRing] = useState(5000);
  const [active, setActive] = useState('todos');
  const [status, setStatus] = useState('cargando');
  const [counts, setCounts] = useState({});
  const ringRef = useRef(5000), activeRef = useRef('todos');

  function makeMarker(p) {
    const col = DISTRICT_CATS[p.cat]?.color || '#888';
    const icon = window.L.divIcon({
      className: 'lmk-pin-wrap',
      html: `<span class="lmk-pin" style="--c:${col}"><span class="lmk-pin-ring"></span></span>`,
      iconSize: [16, 16], iconAnchor: [8, 8],
    });
    const m = window.L.marker([p.lat, p.lng], { icon });
    m.bindTooltip(`<b>${p.name}</b><br>${p.clase || DISTRICT_CATS[p.cat]?.label || ''}`, {
      direction:'top', offset:[0,-8], className:'lmk-tip',
    });
    m._cat = p.cat;
    return m;
  }

  function applyFilters() {
    const cluster = clusterRef.current;
    if (!cluster) return;
    cluster.clearLayers();
    const r = ringRef.current, cat = activeRef.current;
    const subset = placesRef.current.filter(p =>
      p.dist <= r && (cat === 'todos' || p.cat === cat)
    );
    cluster.addLayers(subset.map(p => p.marker));
  }

  function recount() {
    const r = ringRef.current;
    const c = { todos: 0 };
    placesRef.current.forEach(p => {
      if (p.dist <= r) { c.todos++; c[p.cat] = (c[p.cat] || 0) + 1; }
    });
    setCounts(c);
  }

  async function fetchDenue(signal) {
    if (_denueCache) return _denueCache;
    const { lat, lng } = TORRE_COORD;
    const out = [];
    const seen = new Set();
    await Promise.all(Object.entries(DENUE_TERMS).map(async ([cat, term]) => {
      try {
        const url = `https://www.inegi.org.mx/app/api/denue/v1/consulta/Buscar/${encodeURIComponent(term)}/${lat},${lng}/5000/${DENUE_TOKEN}`;
        const res = await fetch(url, { signal });
        if (!res.ok) return;
        const data = await res.json();
        (data || []).forEach(row => {
          const la = parseFloat(row.Latitud), ln = parseFloat(row.Longitud);
          if (!la || !ln) return;
          const id = row.Id || (row.Nombre + la + ln);
          if (seen.has(id)) return;
          seen.add(id);
          out.push({
            lat: la, lng: ln,
            name: row.Nombre || row.Razon_social || 'Establecimiento',
            clase: row.Clase_actividad || '',
            cat,
            dist: haversine(lat, lng, la, ln),
          });
        });
      } catch (e) { /* ignore per-category */ }
    }));
    _denueCache = out;
    return out;
  }

  useEffect(() => {
    if (!window.L || mapRef.current) return;
    const el = document.getElementById('locmap-leaflet');
    if (!el) return;
    let cancelled = false;
    const ac = new AbortController();

    const { lat, lng } = TORRE_COORD;
    const map = window.L.map(el, {
      center: [lat, lng], zoom: 15,
      scrollWheelZoom: false, zoomControl: true, attributionControl: false,
    });
    mapRef.current = map;
    window.L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', { maxZoom: 19 }).addTo(map);

    // radius rings
    [5000, 3000, 1000].forEach(r => {
      window.L.circle([lat, lng], { radius: r, color: '#C8A45C', weight: 1, opacity: .45, fill: false, dashArray: '4 6' }).addTo(map);
    });

    // Torre anchor
    const torreIcon = window.L.divIcon({
      className: 'lmk-torre-wrap',
      html: '<div class="lmk-torre"><span class="lmk-torre-dot"></span><span class="lmk-torre-flag">Torre Auro</span></div>',
      iconSize: [0, 0],
    });
    window.L.marker([lat, lng], { icon: torreIcon, zIndexOffset: 1000 }).addTo(map);

    const cluster = window.L.markerClusterGroup({
      maxClusterRadius: 100, showCoverageOnHover: false, spiderfyOnMaxZoom: false,
      disableClusteringAtZoom: 17, chunkedLoading: true,
      iconCreateFunction: (c) => {
        const kids = c.getAllChildMarkers();
        const tally = {};
        kids.forEach(m => { tally[m._cat] = (tally[m._cat] || 0) + 1; });
        let dom = null, max = 0;
        for (const k in tally) { if (tally[k] > max) { max = tally[k]; dom = k; } }
        const col = DISTRICT_CATS[dom]?.color || '#1F4C82';
        const n = c.getChildCount();
        const size = n < 8 ? 42 : n < 20 ? 58 : n < 45 ? 76 : 96;
        return window.L.divIcon({
          className: 'lmk-blob-wrap',
          html: `<span class="lmk-blob" style="--c:${col};width:${size}px;height:${size}px"></span>`,
          iconSize: [size, size],
        });
      },
    });
    clusterRef.current = cluster;
    map.addLayer(cluster);
    map.setView([lat, lng], 13);

    (async () => {
      let places = [];
      try { places = await fetchDenue(ac.signal); } catch (e) { /* fallthrough */ }
      if (cancelled || mapRef.current !== map) return;
      let usedFallback = false;
      if (!places || places.length === 0) {
        // fallback to curated static data
        usedFallback = true;
        places = DISTRICT_PLACES.map(p => ({
          ...p, clase: DISTRICT_CATS[p.cat]?.label || '',
          dist: haversine(lat, lng, p.lat, p.lng),
        }));
      }
      places.forEach(p => { p.marker = makeMarker(p); });
      placesRef.current = places;
      applyFilters();
      recount();
      setStatus(usedFallback ? 'fallback' : 'ok');
    })();

    return () => { cancelled = true; ac.abort(); map.remove(); mapRef.current = null; clusterRef.current = null; placesRef.current = []; };
  }, []);

  function pickRing(r) { setRing(r); ringRef.current = r; applyFilters(); recount(); }
  function filterCat(cat) { setActive(cat); activeRef.current = cat; applyFilters(); }

  const RINGS = [{ v:1000, l:'1 km' }, { v:3000, l:'3 km' }, { v:5000, l:'5 km' }];

  // top categories in active ring, sorted by count (for the density read)
  const ranked = Object.entries(DISTRICT_CATS)
    .map(([id, c]) => ({ id, label: c.label, color: c.color, n: counts[id] || 0 }))
    .sort((a, b) => b.n - a.n);
  const topN = ranked.length ? Math.max(...ranked.map(r => r.n), 1) : 1;

  return (
    <section className="locmap" id="ubicacion">
      <div className="container locmap-top">
        <div className="kicker">/ 01 Dónde está Torre Auro</div>
        <h2>En el corazón del <em>distrito de negocios</em> de Boca del Río.</h2>
        <p>Torre Auro está sobre Blvd. Adolfo Ruiz Cortines, en Costa de Oro — el corredor de mayor densidad corporativa de Veracruz. El mapa concentra los giros relevantes para un centro de negocios: corporativo, convenciones, hospedaje ejecutivo, comercio ancla y salud, según el DENUE del INEGI.</p>
      </div>

      <div className="container locmap-grid">
        {/* MAP */}
        <div className="locmap-mapwrap">
          <div id="locmap-leaflet" className="locmap-leaflet" aria-label="Mapa del distrito de negocios"></div>
          <div className="locmap-legend">
            {Object.entries(DISTRICT_CATS).map(([id, c]) => (
              <button key={id} className={`locmap-legitem ${active === id ? 'on' : ''} ${active !== 'todos' && active !== id ? 'dim' : ''}`} onClick={() => filterCat(active === id ? 'todos' : id)}>
                <span className="locmap-legdot" style={{ background: c.color }} />
                <span className="locmap-leglabel">{c.label}</span>
                <span className="locmap-legcount">{counts[id] || 0}</span>
              </button>
            ))}
          </div>
        </div>

        {/* INSIGHT PANEL */}
        <aside className="locmap-panel">
          <div className="locmap-addr">
            <span className="locmap-addr-pin" />
            <div>
              <div className="locmap-addr-name">Torre Auro</div>
              <div className="locmap-addr-line">Blvd. Adolfo Ruiz Cortines · Costa de Oro, Boca del Río, Ver.</div>
            </div>
          </div>

          <div className="locmap-radio">
            <span className="locmap-radio-lbl">Radio de análisis</span>
            <div className="locmap-radio-btns">
              {RINGS.map(r => (
                <button key={r.v} className={`locmap-ring ${ring === r.v ? 'on' : ''}`} onClick={() => pickRing(r.v)}>{r.l}</button>
              ))}
            </div>
          </div>

          <div className="locmap-bignum">
            <span className="locmap-bignum-n">
              {status === 'cargando' ? '···' : (counts.todos || 0)}
            </span>
            <span className="locmap-bignum-lbl">
              negocios a {ring/1000} km de Torre Auro
            </span>
            <span className="locmap-bignum-src">
              {status === 'cargando' ? 'Consultando DENUE · INEGI…'
                : status === 'fallback' ? 'Datos curados · DENUE no disponible'
                : 'Fuente: DENUE · INEGI'}
            </span>
          </div>

          <div className="locmap-density">
            <span className="locmap-density-lbl">Qué te rodea</span>
            {ranked.map(r => (
              <button key={r.id} className={`locmap-bar ${active === r.id ? 'on' : ''}`} onClick={() => filterCat(active === r.id ? 'todos' : r.id)}>
                <span className="locmap-bar-name">{r.label}</span>
                <span className="locmap-bar-track">
                  <span className="locmap-bar-fill" style={{ width: `${(r.n/topN)*100}%`, background: r.color }} />
                </span>
                <span className="locmap-bar-n">{r.n}</span>
              </button>
            ))}
          </div>

          <p className="locmap-note">Toca una categoría para aislarla en el mapa. Acerca el zoom para ver cada negocio; los grupos se concentran alrededor de la torre.</p>
        </aside>
      </div>
    </section>
  );
}

/* ─── S3 · LOS 4 ECOSISTEMAS ─── */
function S3Ecosystems() {
  return (
    <section className="section paper" id="ecosistemas">
      <div className="container">
        <div className="section-head">
          <div className="kicker">/ 02 Los cuatro ecosistemas</div>
          <h2>Cada giro, su <em>ecosistema.</em></h2>
          <p>Torre Auro agrupa a sus inquilinos por afinidad. Cuatro ecosistemas donde cada empresa convive con quienes comparten su tipo de cliente, su ritmo y su perfil profesional.</p>
        </div>
        <div className="eco-grid">
          {ECOSYSTEMS.map((e, i) => (
            <article
              key={e.id}
              className="eco-card"
              onClick={() => navigate('/' + e.primaryFloor)}
              style={{ '--acc': e.accHex }}
            >
              <div className="eco-card-img">
                <div className={`bg-cover ${e.bgClass}`} aria-hidden="true" />
                <div className="eco-card-overlay" style={{ background:`linear-gradient(180deg, transparent 40%, ${e.accHex}D8 100%)` }} />
                <span className="eco-card-no">{pad2(i + 1)}</span>
              </div>
              <div className="eco-card-body">
                <div className="eco-card-levels">{e.levels}</div>
                <h3>{e.name}</h3>
                <p>{e.descriptor}</p>
                <span className="eco-card-link">
                  Explorar <span aria-hidden="true">→</span>
                </span>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ─── S4 · LA TORRE — interactive floor + plan ─── */
function S4Tower() {
  const [selId, setSelId] = useState('nivel-1');
  const [fading, setFading] = useState(false);

  function selectFloor(id) {
    if (id === selId) return;
    setFading(true);
    setTimeout(() => { setSelId(id); setFading(false); }, 200);
  }

  const floor = FLOOR_BY_ID[selId] || FLOORS[5];
  const z = ZONES[floor.zone];

  return (
    <section className="section cream" id="torre">
      <div className="container">
        <div className="section-head">
          <div className="kicker">/ 03 La torre</div>
          <h2>Una arquitectura<br/>de <em>afinidades.</em></h2>
          <p>Selecciona un nivel para ver su plano y su perfil de ecosistema. Cada piso está asignado a un entorno específico — los inquilinos comparten visión, no solo espacio.</p>
        </div>

        <div className="tower-grid">
          {/* Architectural elevation */}
          <div className="tower-elevation">
            <div className="tower-elevation-head">
              <div className="tower-label">Elevación · Costa de Oro</div>
              <div className="tower-label" style={{textAlign:'right'}}>7 niveles<br/><span style={{color:'var(--muted-2)'}}>Esc. 1:200</span></div>
            </div>
            <div className="tower-stack">
              {FLOORS.map((f) => {
                const fz = ZONES[f.zone];
                const isSel = f.id === selId;
                return (
                  <button
                    key={f.id}
                    className={`tower-floor ${isSel ? 'sel' : ''}`}
                    onClick={() => selectFloor(f.id)}
                    aria-label={`${f.sh} — ${fz.tag}`}
                    aria-pressed={isSel}
                    style={isSel ? { borderColor: fz.accHex, background:'linear-gradient(90deg, rgba(0,0,0,.04), #fff 40%)' } : {}}
                  >
                    <span className="tower-floor-badge" style={{ background: fz.accHex }}>{f.sh}</span>
                    <span className="tower-floor-name">{f.short.split('·')[0].trim()}</span>
                    <span className="tower-floor-acc" style={{ background: isSel ? fz.accHex : 'var(--line)' }} />
                  </button>
                );
              })}
            </div>
            <div className="tower-base"><span>LOBBY · ACCESO</span></div>
            <div className="tower-park"><span>S1 · ESTACIONAMIENTO</span></div>
            <div className="tower-park s2"><span>S2</span></div>
          </div>

          {/* Floor detail panel */}
          <div className={`floor-detail ${fading ? 'fade' : ''}`}>
            {/* Tag + header */}
            <div className="floor-detail-head" style={{ borderColor: z.accHex }}>
              <span className="floor-detail-tag" style={{ color: z.accHex }}>
                <span style={{width:7,height:7,background:z.accHex,borderRadius:'50%',display:'inline-block'}} />
                {z.tag}
              </span>
              <div className="floor-detail-sh">{floor.sh}</div>
              <h3 className="floor-detail-name">{floor.name}</h3>
              <p className="floor-detail-desc">{floor.desc}</p>
            </div>

            {/* Plan */}
            {floor.planClass ? (
              <figure className="floor-plan-mini">
                <div className="floor-plan-mini-frame">
                  <div className={`floor-plan-mini-img ${floor.planClass}`}
                    role="img" aria-label={`Plano ${floor.sh}`} />
                </div>
                <figcaption className="floor-plan-mini-cap">
                  <div>
                    <span className="floor-plan-lbl">Nivel</span>
                    <span className="floor-plan-val">{floor.sh}</span>
                  </div>
                  <div>
                    <span className="floor-plan-lbl">Ancla · C</span>
                    <span className="floor-plan-val">137 m²</span>
                  </div>
                  <div>
                    <span className="floor-plan-lbl">Consolid. · B</span>
                    <span className="floor-plan-val">120 m²</span>
                  </div>
                  <div>
                    <span className="floor-plan-lbl">Boutique · A</span>
                    <span className="floor-plan-val">3 × 85 m²</span>
                  </div>
                </figcaption>
              </figure>
            ) : null}

            {/* Stats + CTA */}
            <div className="floor-detail-foot">
              <div className="floor-stat">
                <span className="floor-stat-num" style={{ color: z.accHex }}>
                  {floor.av}/{floor.tot}
                </span>
                <span className="floor-stat-lbl">disponibles</span>
              </div>
              <div className="floor-stat">
                <span className="floor-stat-num">{FMT(floor.pMin)}</span>
                <span className="floor-stat-lbl">desde / mes</span>
              </div>
              <button className="btn btn-navy btn-sm" onClick={() => navigate(floor.route)}>
                Ver el nivel <Icon n="ti-arrow-right" />
              </button>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─── S4.5 · VISTAS · real interiors gallery ─── */
function SVistas() {
  const shots = [
    { cls:'bg--interior-vista-2', label:'Niveles altos · panorámica',  lvl:'N5 — N6' },
    { cls:'bg--interior-n4',      label:'Vista al Golfo de México',    lvl:'N4' },
    { cls:'bg--interior-vista-1', label:'Acceso poniente · obra gris', lvl:'N5' },
  ];
  return (
    <section className="vistas">
      <div className="container">
        <div className="section-head">
          <div className="kicker">/ 04 El entorno · vistas reales</div>
          <h2>Lo que se ve<br/><em>desde adentro.</em></h2>
          <p>Cada nivel de Torre Auro abre a una vista distinta del Golfo y de Costa de Oro. El entorno que rodea a una empresa forma parte de cómo opera y de cómo la perciben sus clientes.</p>
        </div>
        <div className="vistas-grid">
          {shots.map((s, i) => (
            <figure key={i} className="vista-card">
              <div className={`vista-img ${s.cls}`} aria-label={s.label} />
              <figcaption>
                <span className="vista-lvl">{s.lvl}</span>
                <span className="vista-label">{s.label}</span>
              </figcaption>
            </figure>
          ))}
        </div>
      </div>
    </section>
  );
}
/* ─── S5.5 · LA CONVERSACIÓN — voice teaser ─── */
function SConversacion() {
  const sorted = [...POSTS].sort((a, b) => b.dateISO.localeCompare(a.dateISO));
  const latestPost = sorted[0];
  const featured = EVENTS.find(e => e.status === 'featured');

  return (
    <section className="conv">
      <div className="container">
        <div className="section-head" style={{ marginBottom:56 }}>
          <div className="kicker">/ 05 La conversación</div>
          <h2>Lo que pasa<br/><em>en Torre Auro.</em></h2>
          <p>El ecosistema no es solo el edificio. Es la agenda de eventos, el punto de vista editorial y la comunidad que se construye con el tiempo.</p>
        </div>

        <div className="conv-grid">
          {featured && (
            <article className="conv-card conv-card-event" onClick={() => navigate('/eventos/' + featured.slug)}>
              <div className="conv-card-img">
                <div className={`bg-cover ${featured.cover}`} aria-hidden="true" />
                <div className="conv-card-overlay" />
                <span className="conv-card-tag">El calendario · {STATUS_META[featured.status]}</span>
              </div>
              <div className="conv-card-body">
                <div className="conv-date-block">
                  <span className="d">{new Date(featured.dateISO + 'T12:00:00').getDate()}</span>
                  <span className="m">{new Date(featured.dateISO + 'T12:00:00').toLocaleDateString('es-MX', { month:'short' }).replace('.', '').toUpperCase()}</span>
                </div>
                <div className="conv-kind">{featured.kind}</div>
                <h3>{featured.title}</h3>
                <p>{featured.short}</p>
                <span className="conv-link">Ver el evento <span aria-hidden="true">→</span></span>
              </div>
            </article>
          )}

          {latestPost && (
            <article className="conv-card conv-card-post" onClick={() => navigate('/perspectiva/' + latestPost.slug)}>
              <div className="conv-card-img">
                <div className={`bg-cover ${latestPost.cover}`} aria-hidden="true" />
                <div className="conv-card-overlay" />
                <span className="conv-card-tag">Perspectiva · {latestPost.issue.split(' · ').pop()}</span>
              </div>
              <div className="conv-card-body">
                <div className="conv-kind">{latestPost.eyebrow}</div>
                <h3>{latestPost.title}</h3>
                <p>{latestPost.excerpt}</p>
                <div className="ed-meta-row">
                  <span>{latestPost.date}</span>
                  <span className="dot">·</span>
                  <span>{latestPost.readMin} min de lectura</span>
                </div>
                <span className="conv-link" style={{ marginTop:24 }}>Leer la entrada <span aria-hidden="true">→</span></span>
              </div>
            </article>
          )}
        </div>

        <div className="conv-cta">
          <button className="btn btn-outline" onClick={() => navigate('/eventos')}>
            Ver todo el calendario <Icon n="ti-arrow-right" />
          </button>
          <button className="btn btn-outline" onClick={() => navigate('/perspectiva')}>
            Leer Perspectiva <Icon n="ti-arrow-right" />
          </button>
        </div>
      </div>
    </section>
  );
}

function S5Availability() {
  return (
    <section className="section paper">
      <div className="container">
        <div className="section-head">
          <div className="kicker">/ 06 Disponibilidad actual</div>
          <h2>El edificio,<br/><em>al día de hoy.</em></h2>
        </div>

        <div className="avail-list">
          {ECOSYSTEMS.map((e) => {
            const floors = e.floors.map(id => FLOOR_BY_ID[id]).filter(Boolean);
            const totalAv = floors.reduce((a, f) => a + f.av, 0);
            const totalTot = floors.reduce((a, f) => a + f.tot, 0);
            return (
              <div key={e.id} className="avail-row" onClick={() => navigate('/' + e.primaryFloor)}>
                <span className="avail-dot" style={{ background: e.accHex }} />
                <div className="avail-text">
                  <div className="avail-eco">{e.name}</div>
                  <div className="avail-status">{e.status}</div>
                </div>
                <div className="avail-count">
                  <span className="num">{totalAv}<span className="of">/{totalTot}</span></span>
                  <span className="lbl">espacios</span>
                </div>
                <span className="avail-arrow" aria-hidden="true">→</span>
              </div>
            );
          })}
        </div>

        <div className="avail-footer">
          <button className="btn btn-outline" onClick={() => navigate('/nivel-1')}>
            Ver disponibilidad completa <Icon n="ti-arrow-right" />
          </button>
        </div>
      </div>
    </section>
  );
}

/* ─── S6 · CIERRE ─── */
function S6Close() {
  return (
    <section className="close-banner">
      <div className="container close-inner">
        <div className="close-num">07</div>
        <h2>
          Un lugar en el<br/>
          <em>ecosistema empresarial.</em>
        </h2>
        <div className="close-actions">
          <button className="btn btn-gold" onClick={() => navigate('/contacto')}>
            Solicitar información <Icon n="ti-arrow-right" />
          </button>
          <button className="btn btn-outline-light" onClick={() => {
            document.getElementById('ecosistemas')?.scrollIntoView({ behavior:'smooth' });
          }}>
            Explorar ecosistemas
          </button>
          <button className="btn-link-light" onClick={() => openChat('general')}>
            Conocer disponibilidad <span aria-hidden="true">→</span>
          </button>
        </div>
      </div>
    </section>
  );
}

/* ─── HOME ─── */
function Home() {
  return (
    <div className="home">
      <S1Hero />
      <SLocation />
      <S2Atmospheric />
      <S3Ecosystems />
      <S4Tower />
      <SVistas />
      <SConversacion />
      {/* <S5Availability /> */}
      <S6Close />
    </div>
  );
}

Object.assign(window, { Home });
