/* 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 [menuOpen, setMenuOpen] = useState(false);
  const navCls = `nav ${scrolled || !isHome ? 'is-solid' : ''} ${menuOpen ? 'menu-open' : ''}`;

  useEffect(() => { setMenuOpen(false); }, [route]);
  useEffect(() => {
    document.body.style.overflow = menuOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);

  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 '';
  })();

  const go = (r) => { setMenuOpen(false); navigate(r); };

  return (
    <header className={navCls}>
      <div className="nav-inner">
        <div className="nav-logo" onClick={() => go('/')} aria-label="Torre Auro · Inicio">
          <img src={window.LOGO_DATA_URI} alt="Torre Auro" />
        </div>
        <nav className="nav-links">
          {NAV_LINKS.filter(l => !l.mega).map(l => (
            <button
              key={l.id}
              className={`nav-link ${activeId === l.id ? 'act' : ''}`}
              onClick={() => go(l.route)}
            >{l.label}</button>
          ))}
        </nav>
        <button
          className="nav-burger"
          aria-label={menuOpen ? 'Cerrar menú' : 'Abrir menú'}
          aria-expanded={menuOpen}
          onClick={() => setMenuOpen(o => !o)}
        >
          <span /><span /><span />
        </button>
      </div>

      {/* Mobile overlay menu */}
      <div className={`nav-mobile ${menuOpen ? 'open' : ''}`}>
        <nav className="nav-mobile-links">
          {NAV_LINKS.filter(l => !l.mega).map(l => (
            <button
              key={l.id}
              className={`nav-mobile-link ${activeId === l.id ? 'act' : ''}`}
              onClick={() => go(l.route)}
            >{l.label}</button>
          ))}
        </nav>
        <div className="nav-mobile-eco">
          <div className="nav-mobile-eco-lbl">Ecosistemas</div>
          {ECOSYSTEMS.map(e => (
            <button key={e.id} className="nav-mobile-eco-item" onClick={() => go('/' + e.primaryFloor)}>
              <span className="dot" style={{ background: e.accHex }} />
              <span>{e.name}</span>
              <span className="lv">{e.levels}</span>
            </button>
          ))}
        </div>
      </div>
    </header>
  );
}

/* ────────────────── FOOTER ────────────────── */
function Footer() {
  return (
    <footer className="foot">
      <div className="container">
        <div className="foot-top">
          <div>
            <div className="foot-logo"><img src={window.LOGO_DATA_URI} alt="Torre Auro" /></div>
            <p>Ecosistema empresarial vertical en Costa de Oro. Cuatro ecosistemas, siete niveles, un mismo distrito de negocios.</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 · Despachos & Servicios</li>
              <li onClick={() => navigate('/nivel-4')}>N4 · Despachos & Servicios</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>Un edificio, un ecosistema.</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,
});
