/* 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"
            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">
        <div className="hero-locality">Costa de Oro · La ciudad más moderna del Estado</div>
        <h1>
          <span className="break">El ecosistema</span>
          <span className="break">empresarial de</span>
          <span className="break"><em>Boca del Río, Veracruz.</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">
          Donde el entorno<br/>define <em>la percepción</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 ─── */
function SLocation() {
  return (
    <section className="location" id="ubicacion">
      <div className="container">
        <div className="section-head">
          <div className="kicker">/ 01 La ubicación</div>
          <h2>Costa de Oro,<br/><em>el corazón corporativo</em> de Veracruz.</h2>
          <p>Torre Auro se levanta donde se cruzan las dos arterias principales de Boca del Río. La zona más moderna del estado — la de los corporativos, los hospitales privados, los hoteles ejecutivos y el malecón nuevo.</p>
        </div>

        <div className="loc-grid">
          <figure className="loc-aerial">
            <div className="bg-cover bg--boca-aerial" aria-hidden="true" />
            <div className="loc-pin">
              <span className="pin-dot" />
              <span className="pin-label">Torre Auro</span>
            </div>
            <figcaption className="loc-aerial-cap">
              <span className="lbl">Vista aérea</span>
              <span className="val">Costa de Oro · Boca del Río, Veracruz</span>
            </figcaption>
          </figure>

          <div className="loc-facts">
            <div className="loc-eyebrow">Referencias del entorno</div>
            <ul className="loc-list">
              <li>
                <span className="loc-no">01</span>
                <div>
                  <div className="loc-place">WTC Veracruz · Centro de convenciones</div>
                  <div className="loc-dist">3 min · cumbres y exposiciones empresariales</div>
                </div>
              </li>
              <li>
                <span className="loc-no">02</span>
                <div>
                  <div className="loc-place">Torre Extería</div>
                  <div className="loc-dist">Vecino directo · referencia corporativa de la zona</div>
                </div>
              </li>
              <li>
                <span className="loc-no">03</span>
                <div>
                  <div className="loc-place">Andamar Lifestyle Center</div>
                  <div className="loc-dist">5 min · centro gastronómico, retail y hotelero</div>
                </div>
              </li>
              <li>
                <span className="loc-no">04</span>
                <div>
                  <div className="loc-place">Plaza Las Américas</div>
                  <div className="loc-dist">7 min · ancla comercial de Boca del Río</div>
                </div>
              </li>
              <li>
                <span className="loc-no">05</span>
                <div>
                  <div className="loc-place">Torre 1519</div>
                  <div className="loc-dist">Mismo corredor · ecosistema corporativo de Costa de Oro</div>
                </div>
              </li>
              <li>
                <span className="loc-no">06</span>
                <div>
                  <div className="loc-place">Gran Café de la Parroquia</div>
                  <div className="loc-dist">Caminando · ícono gastronómico veracruzano</div>
                </div>
              </li>
              <li>
                <span className="loc-no">07</span>
                <div>
                  <div className="loc-place">Four Points by Sheraton</div>
                  <div className="loc-dist">5 min · hospedaje ejecutivo para socios y clientes</div>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </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 empresa, su <em>entorno.</em></h2>
        </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 (architecture of affinities) ─── */
function S4Tower() {
  // Group floors by ecosystem
  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>Cada nivel se asigna a un ecosistema. Los inquilinos comparten visión, no piso. Quien entra a Torre Auro entra a su entorno natural.</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 z = ZONES[f.zone];
                return (
                  <button
                    key={f.id}
                    className="tower-floor"
                    onClick={() => navigate(f.route)}
                    aria-label={`${f.sh} — ${z.tag}`}
                  >
                    <span className="tower-floor-badge" style={{ background: z.accHex }}>{f.sh}</span>
                    <span className="tower-floor-name">{z.tag}</span>
                    <span className="tower-floor-acc" style={{ background: z.accHex }} />
                  </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>

          {/* Affinity legend */}
          <div className="affinity-list">
            {ECOSYSTEMS.map((e, i) => (
              <div key={e.id} className="affinity-row">
                <span className="affinity-dot" style={{ background: e.accHex }} />
                <div>
                  <div className="affinity-name" onClick={() => navigate('/' + e.primaryFloor)}>
                    <span className="affinity-lvl">{e.levels}</span>
                    <span className="affinity-eco">{e.name}</span>
                  </div>
                  <div className="affinity-desc">{e.descriptor}</div>
                </div>
                <button className="affinity-go" onClick={() => navigate('/' + e.primaryFloor)} aria-label={`Ver ${e.name}`}>
                  <span aria-hidden="true">→</span>
                </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>Tu vista <em>te define.</em></h2>
          <p>Cada nivel de Torre Auro abre a una vista distinta del Golfo y de Costa de Oro. Lo que ven tus clientes y socios desde tu oficina es parte de tu posicionamiento.</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>
          Tu empresa merece<br/>
          <em>el entorno correcto.</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 />
      <S2Atmospheric />
      <SLocation />
      <S3Ecosystems />
      <S4Tower />
      <SVistas />
      <SConversacion />
      <S5Availability />
      <S6Close />
    </div>
  );
}

Object.assign(window, { Home });
