/* Torre Auro — shared components */

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

function Icon({ n, ...rest }) {
  return <i className={`ti ${n}`} aria-hidden="true" {...rest} />;
}

function useScrolled(threshold = 80) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onS = () => setScrolled(window.scrollY > threshold);
    onS();
    window.addEventListener('scroll', onS, { passive:true });
    return () => window.removeEventListener('scroll', onS);
  }, [threshold]);
  return scrolled;
}

function CountUp({ to, duration = 1400 }) {
  const [val, setVal] = useState(to);
  useEffect(() => {
    let raf, start, cancelled = false;
    setVal(0);
    const step = (t) => {
      if (cancelled) return;
      if (!start) start = t;
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(Math.round(to * eased));
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    // Fallback: if rAF doesn't advance (throttled iframe), force-set final value
    const fb = setTimeout(() => { if (!cancelled) setVal(to); }, duration + 200);
    return () => { cancelled = true; cancelAnimationFrame(raf); clearTimeout(fb); };
  }, [to, duration]);
  return <span>{val}</span>;
}

/* routing */
function navigate(route) {
  if (window.location.pathname === route) return;
  window.history.pushState({}, '', route);
  window.dispatchEvent(new PopStateEvent('popstate'));
  window.scrollTo({ top: 0, behavior: 'instant' });
}
function useRoute() {
  const [route, setRoute] = useState(window.location.pathname || '/');
  useEffect(() => {
    const onPop = () => setRoute(window.location.pathname || '/');
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);
  return route;
}

function openChat(context) {
  window.dispatchEvent(new CustomEvent('ta:open-chat', { detail: { context } }));
}

/* number to roman or padded number */
function pad2(n) { return String(n).padStart(2, '0'); }

/* ────────────────── NAV ────────────────── */
function Nav({ route }) {
  const scrolled = useScrolled(60);
  const isHome = route === '/';
  const navCls = `nav ${scrolled || !isHome ? 'is-solid' : ''}`;

  const activeId = (() => {
    if (route === '/') return 'home';
    if (route.startsWith('/eventos')) return 'eventos';
    if (route.startsWith('/perspectiva')) return 'perspectiva';
    if (route === '/contacto') return 'contacto';
    if (route === '/planta-baja' || route.startsWith('/nivel-')) return 'ecosistemas';
    return '';
  })();

  return (
    <header className={navCls}>
      <div className="nav-inner">
        <div className="nav-logo" onClick={() => navigate('/')} aria-label="Torre Auro · Inicio">
          <img src="img/torre-auro-logo-white.png" alt="Torre Auro" />
        </div>
        <nav className="nav-links">
          {NAV_LINKS.map(l => (
            l.mega ? (
              <div key={l.id} className="nav-dd nav-mega">
                <button className={`nav-link ${activeId === l.id ? 'act' : ''}`}>
                  {l.label}<Icon n="ti-chevron-down" style={{ fontSize:10, marginLeft:6 }} />
                </button>
                <div className="nav-mega-menu">
                  <div className="nav-mega-eyebrow">Cuatro ecosistemas · siete niveles</div>
                  <div className="nav-mega-grid">
                    {ECOSYSTEMS.map(e => (
                      <div key={e.id} className="nav-mega-col">
                        <div className="nav-mega-acc" style={{ background:e.accHex }} />
                        <div className="nav-mega-name" onClick={() => navigate('/' + e.primaryFloor)}>{e.name}</div>
                        <div className="nav-mega-desc">{e.descriptor}</div>
                        <ul className="nav-mega-floors">
                          {e.floors.map(fid => {
                            const f = FLOOR_BY_ID[fid];
                            if (!f) return null;
                            return (
                              <li key={fid} onClick={() => navigate(f.route)}>
                                <span className="lvl">{f.sh}</span>
                                <span className="fname">{f.short.split('·')[0].trim().split('—')[0].trim()}</span>
                                <span className="favail">{f.av}/{f.tot}</span>
                              </li>
                            );
                          })}
                        </ul>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            ) : (
              <button
                key={l.id}
                className={`nav-link ${activeId === l.id ? 'act' : ''}`}
                onClick={() => navigate(l.route)}
              >{l.label}</button>
            )
          ))}
        </nav>
        <button className="nav-cta" onClick={() => openChat('general')}>
          <Icon n="ti-message-circle" /> <span className="nav-cta-text">Hablar con un asesor</span>
        </button>
      </div>
    </header>
  );
}

/* ────────────────── FOOTER ────────────────── */
function Footer() {
  return (
    <footer className="foot">
      <div className="container">
        <div className="foot-top">
          <div>
            <div className="foot-logo"><img src="img/torre-auro-logo-white.png" alt="Torre Auro" /></div>
            <p>Distribución comercial vertical en Costa de Oro. Cada nivel tiene su nicho definido, su buyer persona y su propia urgencia comercial.</p>
          </div>
          <div>
            <h5>Niveles</h5>
            <ul>
              <li onClick={() => navigate('/planta-baja')}>PB · Retail premium</li>
              <li onClick={() => navigate('/nivel-1')}>N1 · Salud premium</li>
              <li onClick={() => navigate('/nivel-2')}>N2 · Salud + servicios</li>
              <li onClick={() => navigate('/nivel-3')}>N3 · Mixto inteligente</li>
              <li onClick={() => navigate('/nivel-4')}>N4 · Corporativo medio</li>
              <li onClick={() => navigate('/nivel-5')}>N5 · Corporativo premium</li>
              <li onClick={() => navigate('/nivel-6')}>N6 · Planta completa</li>
            </ul>
          </div>
          <div>
            <h5>Edificio</h5>
            <ul>
              <li>4 niveles de estacionamiento</li>
              <li>Frente dual sobre Ruiz Cortines</li>
              <li>Acceso controlado en lobby</li>
              <li>Entrega en obra gris</li>
              <li onClick={() => navigate('/contacto')}>Solicitar planos</li>
            </ul>
          </div>
          <div>
            <h5>Voz</h5>
            <ul>
              <li onClick={() => navigate('/eventos')}>El Calendario</li>
              <li onClick={() => navigate('/perspectiva')}>Perspectiva (newsletter)</li>
              <li onClick={() => navigate('/contacto')}>Solicitar invitaciones</li>
            </ul>
          </div>
          <div>
            <h5>Contacto</h5>
            <div className="foot-contact-row"><Icon n="ti-phone" /><span>229 302 7197</span></div>
            <div className="foot-contact-row"><Icon n="ti-mail" /><span>contacto@torreauro.com</span></div>
            <div className="foot-contact-row">
              <Icon n="ti-map-pin" />
              <span>Blvd. Adolfo Ruiz Cortines<br/>Costa de Oro, Boca del Río, Ver.</span>
            </div>
          </div>
        </div>
        <div className="foot-bottom">
          <div>© 2026 Torre Auro · Todos los derechos reservados</div>
          <em>Cada nivel, su mercado.</em>
        </div>
      </div>
    </footer>
  );
}

/* ────────────────── CTA BANNER (editorial) ────────────────── */
function CtaBanner({ no, eyebrow, title, sub, primary, secondary, onPrimary, onSecondary }) {
  return (
    <section className="cta-banner">
      <div className="cta-banner-grid">
        <div className="cta-banner-num">{no || '07'}</div>
        <div>
          <div className="kicker light">{eyebrow}</div>
          <h2 style={{ marginTop:24 }} dangerouslySetInnerHTML={{ __html: title }} />
          <p>{sub}</p>
          <div className="btns">
            <button className="btn btn-gold" onClick={onPrimary}>
              <Icon n="ti-message-circle" /> {primary}
            </button>
            {secondary && (
              <button className="btn btn-outline-light" onClick={onSecondary}>
                {secondary}
              </button>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  Icon, useScrolled, CountUp, pad2,
  navigate, useRoute, openChat,
  Nav, Footer, CtaBanner,
});
